Doesn't let me to input values to x.
It runs and it says that is completed with exit code 0. Why?
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if ' name ' == ' main ':
donuts()
__name__ is a variable. It should have quotes around it. When you surround it with quotes python treats it like a regular string. Replace the bottom with
if __name__ == "__main__":
donuts()
Remove quotes around '__name__' so it becomes __name__:
def donuts():
x = int(input("How many donutes?"))
if x < 10:
print("Numbers of donuts: "+ x)
else:
print("Number of donute: many")
def litere():
x = input("Type a word! : ")
if len(x) <= 2:
print("NULL")
else:
k = len(x) -1
print(x[0:3] + x[k-2])
if __name__ == "__main__":
donuts()
Here is the change I made to your code:
if __name__ == "__main__":
donuts()
Related
As the title says, this is a double integer checker, meaning it has two functions + the main. Please correct me if I do not paraphrase it correctly. Anyways, here is the model:
def is_integer(kraai):
kraai.replace(" ", "")
if len(kraai) == 1:
if kraai.isdigit():
print(valid)
else:
print(invalid)
exit()
elif len(kraai) > 1:
if roek == "-" or roek == "+" or roek.isdigit():
print(valid)
else:
print(invalid)
exit()
elif len(kraai) == 0:
print(invalid)
exit()
def remove_non_integer(kauw):
if len(kauw) >= 1:
for z in kauw:
if not z.isdigit():
ekster = kauw.replace(z, "")
print(invalid)
print(f'''\nNot all characters after the first are integers...
\nnogsteeds, vet raaf!:, {ekster}''')
if __name__ == '__main__':
valid = "valid"
invalid = "invalid"
kraai = input("Welcome to the integer tester. Please give an input: ")
if len(kraai) > 1:
roek = kraai[0]
kauw = kraai[1:]
y = "".join([roek, kauw])
corvidae = is_integer(kraai), remove_non_integer(kauw)
elif len(kraai) < 1:
corvidae = is_integer(kraai)
As you can see, one functions to check the integer while the other functions to remove every non-integer. However, three problems:
It will remove only one unique character
It will print the same message every time a non-integer is in the integer
It will print both 'valid' and 'invalid' for some reason when the remove_integer(x) function filters a non-integer.
Any help?
So yeah there were multiple errors at the time I posted this question.
def is_integer(kraai):
valid = "valid"
invalid = "invalid"
if len(kraai) == 1:
if kraai.isdigit():
print(valid)
elif not kraai.isdigit():
print(invalid)
elif len(kraai) > 1:
if kraai[0] == "-" or kraai[0] == "+" or kraai[0].isdigit():
if kraai[1:].isdigit():
print(True)
print(valid)
else:
print(False)
else:
print(invalid)
elif len(kraai) == 0:
print(invalid)
exit()
def remove_non_integer(bonte_kraai):
invalid = "invalid"
roek = bonte_kraai[0]
kauw = bonte_kraai[1:]
y = "".join([roek, kauw])
for x in kauw:
if x.isalpha():
ekster = ''.join([i for i in y if i.isdigit() or i == "-"])
print(False)
print(invalid, f'''\nNot all characters after the first are integers...
\nnogsteeds, vet raaf!: {ekster}''')
break
if __name__ == '__main__':
kraai = input("Welcome to the integer tester. Please give an input: ")
kraai.replace(" ", "")
if len(kraai) == 1:
corvidae = is_integer(kraai)
elif len(kraai) > 1:
for x in kraai[1:]:
if kraai[1:].isdigit():
corvidae = is_integer(kraai)
break
elif x.isalpha():
bonte_kraai = kraai
corvidae = remove_non_integer(bonte_kraai)
break
The difference between both codes, now, is first of all that they work individually as observable in the if name == 'main' block.
Secondly, I used the 'break' statement to break the loop after it has fulfilled its task. Otherwise it will repeat a number of times and that is unwanted (it should only run once).
Thirdly, as you can see I moved some variables to functions so that pytest doesn't return an 'x is not defined' error. I substituted the variables with indexes [].
Thanks.
Sorry to ask a very long question but I am very new to Python. I started a free course on FutureLearn and a task was to create a calculator. The code I had ended up being a lot longer than other answers and it was too big to fit into the comment section. Just looking for tips for any part of my code that could be squished down. First question on StackOverflow so I'm sorry if this is a bad question.
def main():
operations = ['multiplication', 'division', 'addition', 'subtraction', 'x^y']
def find_op():
while True:
try:
operation = input('What do you want to do? Addition, subtraction, multiplication, division, or x^y??\n')
operations.index(operation.lower())
break
except ValueError:
input('Error!, you must input one of the five options, enter to try again.')
return operations.index(operation.lower())
operation_index = find_op()
match operation_index:
case 0:
num_question_ending = 'multiply with'
case 1:
num_question_ending = 'divide with'
case 2:
num_question_ending = 'add with'
case 3:
num_question_ending = 'subtract with'
case 4:
num_question_ending = 'create an exponential with'
def add():
add_ans = global_number1 + global_number2
print(f'{global_number1} + {global_number2} =\n{add_ans}')
def sub():
sub_ans = global_number1 - global_number2
print(f'{global_number1} - {global_number2} =\n{sub_ans}')
def mult():
mult_ans = global_number1 * global_number2
print(f'{global_number1} multiplied by {global_number2} =\n{mult_ans}')
def div():
while True:
try:
div_ans = global_number1 / global_number2
break
except ZeroDivisionError:
input('Naughty naughty boy trying to divide by 0. '
'Now you gonna have to restart the code. Press enter plz')
main()
print(f'{global_number1} divided by {global_number2} =\n{div_ans}')
def power():
if global_number1 == 0 and global_number2 == 0:
input('Naughty boy trying 0^0, dat is undefined boi. Enter to restart the whole thing.')
main()
pow_ans = global_number1 ** global_number2
print(f'{global_number1} to the power of {global_number2} =\n{pow_ans}')
def get_number1():
while True:
try:
numba1 = input(f'what\'s the first number you want to {num_question_ending}??\n')
float(numba1)
break
except ValueError:
input('input must be a number. enter to try again.')
numba1 = float(numba1)
return numba1
def get_number2():
while True:
try:
numba2 = input(f'what\'s the second number you want to {num_question_ending}??\n')
float(numba2)
break
except ValueError:
input('input must be a number. enter to try again.')
numba2 = float(numba2)
return numba2
global_number1 = get_number1()
global_number2 = get_number2()
match operation_index:
case 0:
mult()
case 1:
div()
case 2:
add()
case 3:
sub()
case 4:
power()
def repeat():
go_again_ans = input('would you like to go again? Y/N\n')
if go_again_ans == 'Y':
main()
elif go_again_ans == 'N':
exit()
else:
input('Error! You need to answer with either Y or N, enter to try again.')
repeat()
repeat()
if __name__ == '__main__':
main()
I think this is the most concise way
I used the menu prompt to save the text, first class functions to not search for the operation and a lambda functions to avoid defining each function in 3 lines, also not checking for the zero I only catch the exception
I am also still learning so excuse me if something is off
Thanks
menu_prompt = f"""
Please enter:
'a' For addition
's' For Subtraction
'm' For Multiplication
'd' For Division
'p' For Exponential operations
'q' To quit
"""
add = lambda x, y: f"{x} + {y} = { x + y}"
subtract = lambda x, y: f"{x} - {y} = { x - y}"
multiply = lambda x, y: f"{x} * {y} = { x * y}"
divide = lambda x, y: f"{x} / {y} = { x / y:.2f}"
power = lambda x, y: f"{x} ^ {y} = { x ** y}"
operations = {
'a': add,
's': subtract,
'm': multiply,
'd': divide,
'p': power
}
def get_number(order):
while True:
try:
return float(input(f"Please enter the {order} number: "))
except ValueError:
print("Please enter a valid number")
def run_selected_operation(operation):
x = get_number("first")
y = get_number("second")
try:
print(operation(x, y))
except ZeroDivisionError:
print("Can not divide by zero, try again")
user_selection = input(menu_prompt)
while user_selection.lower() != 'q':
if user_selection in operations:
selected_operation = operations[user_selection]
run_selected_operation(selected_operation)
else:
print("Please enter a valid selection")
user_selection = input(menu_prompt)
user_selection = input(menu_prompt)
print(menu_prompt)
I'm a beginner Python learner and I'm currently working on Luhn Algorithm to check credit card validation. I wrote most of the code, but I'm stuck with 2 errors I get 1st one is num is referenced before assignment. 2nd one I'm getting is object of type '_io.TextIOWrapper' has no len(). Further help/ guidance will be greatly appreciated.
These are the steps for Luhn Algorithm (Mod10 Check)
Double every second digit from right to left. If this “doubling” results in a two-digit number, add the two-digit
number to get a single digit.
Now add all single digit numbers from step 1.
Add all digits in the odd places from right to left in the credit card number.
Sum the results from steps 2 & 3.
If the result from step 4 is divisible by 10, the card number is valid; otherwise, it is invalid.
Here's what my output is supposed to be
Card Number Valid / Invalid
--------------------------------------
3710293 Invalid
5190990281925290 Invalid
3716820019271998 Valid
37168200192719989 Invalid
8102966371298364 Invalid
6823119834248189 Valid
And here is the code.
def checkSecondDigits(num):
length = len(num)
sum = 0
for i in range(length-2,-1,-2):
number = eval(num[i])
number = number * 2
if number > 9:
strNumber = str(number)
number = eval(strNumber[0]) + eval(strNumber[1])
sum += number
return sum
def odd_digits(num):
length = len(num)
sumOdd = 0
for i in range(length-1,-1,-2):
num += eval(num[i])
return sumOdd
def c_length(num):
length = len(num)
if num >= 13 and num <= 16:
if num [0] == "4" or num [0] == "5" or num [0] == "6" or (num [0] == "3" and num [1] == "7"):
return True
else:
return False
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
main()
You just forgot to initialize num
def main():
filename = input("What is the name of your input file? ")
infile= open(filename,"r")
# initialize num here
num = cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = cc = (infile.readline().strip())
First, maybe you should remove the extra characters:
def format_card(card_num):
"""
Formats card numbers to remove any spaces, unnecessary characters, etc
Input: Card number, integer or string
Output: Correctly formatted card number, string
"""
import re
card_num = str(card_num)
# Regex to remove any nondigit characters
return re.sub(r"\D", "", card_num)
After check if credit card is valid using the Luhn algorithm:
def validate_card(formated_card_num):
"""
Input: Card number, integer or string
Output: Valid?, boolean
"""
double = 0
total = 0
digits = str(card_num)
for i in range(len(digits) - 1, -1, -1):
for c in str((double + 1) * int(digits[i])):
total += int(c)
double = (double + 1) % 2
return (total % 10) == 0
This is a very simpler version of code it is based on lunh's algorithm
def validator(n):
validatelist=[]
for i in n:
validatelist.append(int(i))
for i in range(0,len(n),2):
validatelist[i] = validatelist[i]*2
if validatelist[i] >= 10:
validatelist[i] = validatelist[i]//10 + validatelist[i]%10
if sum(validatelist)%10 == 0:
print('This a valid credit card')
else:
print('This is not valid credit card')
def cardnumber():
result=''
while True:
try:
result = input('Please enter the 16 digit credit card number : ')
if not (len(result) == 16) or not type(int(result) == int) :
raise Exception
except Exception:
print('That is not a proper credit card number. \nMake sure you are entering digits not characters and all the 16 digits.')
continue
else:
break
return result
def goagain():
return input('Do you want to check again? (Yes/No) : ').lower()[0] == 'y'
def main():
while True:
result = cardnumber()
validator(result)
if not goagain():
break
if __name__ == '__main__':
main()
Old thread but the answer concerns me... and the real issue wasn't identified.
Actually, the error is that you have used the identifier (num) for the parameter when defining checkSecondDigits as the identifier/name of the argument when calling the function in the mainline. The function should be called in main() by
even = checkSecondDigits(cc) so the value in cc (which is the argument) is passed into num (as the parameter) for use within the function.
The same rookie error is made with odd_digits and cc_length.
This question (and the initially suggested answer) demonstrates a fundamental mis-understanding of passing arguments to parameters...
The suggested 'declaring' of num just hides this error/misunderstanding and also obfuscates the local and global scopes of num (which should only be local) and cc (which is global) so whilst the suggestion works in this case, it works for the wrong reason and is poor style and bad programming.
Further,
num should not appear anywhere in main() as it should be local to (only appear inside of) the functions called...
The last line in this code should be the same as the first, but the last line incorrectly assigns the data to num instead of cc
cc = (infile.readline().strip())
print(format("Card Number", "20s"), ("Valid / Invalid"))
print("------------------------------------")
while cc!= "EXIT":
even = checkSecondDigits(num)
odd = odd_digits(num)
c_len = c_length(num)
tot = even + odd
if c_len == True and tot % 10 == 0:
print(format(cc, "20s"), format("Valid", "20s"))
else:
print(format(cc, "20s"), format("Invalid", "20s"))
num = (infile.readline().strip())
you can use my code for card validation it is 100% dynamic because of the card structure is stored in CSV file, so it is easy to update here is the code on GitHub profile, python file link, code explanation file link and CSV for datafile link
python code:
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 10 20:55:30 2019
#author: Preyash2047#gmail.com
"""
import csv
import numpy as np
#csv file imported and storf in reader
reader = csv.DictReader(open("card_data.csv"))
#input card number
card_number = input("Enter the card No: ")
#global variable declaration
min_digits=0
max_digits=0
card_number_list = list(card_number)
card_number_list_reverse=card_number_list[::-1]
card_number_length=len(card_number_list)
first_digit = int(card_number_list[0])
#global variable for final output
card_provider_list_number = 0
result_found = False
card_number_digits = 0
mit_name=""
#list
start=[]
end=[]
name=[]
c_d=[]
number_length=[]
min_max_digits_list=[]
#append the list from csv
for raw in reader:
start.append(raw['start'])
end.append(raw['end'])
name.append(raw['name'])
c_d.append(raw['c_d'])
number_length.append(raw['number_length'])
#initialize the value of min_digits & max_digits
def min_max_digits():
global min_digits
global max_digits
for i in range(len(start)):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
min_max_digits_list.append(available_length[j])
min_max_digits_array = np.array(min_max_digits_list)
np.unique(min_max_digits_array)
min_digits=int(min(min_max_digits_array))
max_digits=int(max(min_max_digits_array))
#list to int
def list_to_int(noofdigits):
str1 = ""
return int(str1.join(noofdigits))
#card validation
def iin_identifier():
first_six_digit = list_to_int(card_number_list[0:6])
for i in range(len(start)):
if(first_six_digit >= int(start[i]) and first_six_digit <= int(end[i])):
available_length=number_length[i].split(',')
for j in range(len(available_length)):
if(card_number_length == int(available_length[j])):
global card_provider_list_number
card_provider_list_number = i
global card_number_digits
card_number_digits = available_length[j]
global result_found
result_found = True
#Major Industry Identifier (MII) identification
def mit_identifier():
global first_digit
global mit_name
switcher = {
1: "Airlines",
2: "Airlines",
3: "Travel and Entertainment",
4: "Banking and Financial Services",
5: "Banking and Financial Services",
6: "Merchandising and Banking",
7: "Petroleum",
8: "Health care, Telecommunications",
9: "National Assignment"
}
mit_name=switcher.get(first_digit, "MIT Identifier Not Found")
#Luhn Algorithm or modulo-10 Algorithm
def luhn_algorithm():
for i in range(card_number_length):
if(i%2!=0 and i!=0):
card_number_list_reverse[i]=int(card_number_list_reverse[i])*2
#print(str(i)+" "+ str(card_number_list_reverse[i]))
if(len(str(card_number_list_reverse[i]))==2):
even_number_2=list(str(card_number_list_reverse[i]))
card_number_list_reverse[i] = int(even_number_2[0])+int(even_number_2[1])
#print("\tsubsum "+str(i)+" "+str(card_number_list_reverse[i]))
else:
card_number_list_reverse[i]=int(card_number_list_reverse[i])
division_int = int(sum(card_number_list_reverse)/10)
division_float=sum(card_number_list_reverse)/10
if(division_int-division_float==0):
return True
#initial level number length validation
def card_number_validation():
min_max_digits()
if(card_number_length>= min_digits and card_number_length <= max_digits and first_digit != 0):
iin_identifier()
mit_identifier()
if(result_found and luhn_algorithm()):
print("\nEntered Details are Correct\n")
print("\nHere are the some details we know about you card")
print("\nNo: "+card_number)
print("\nIssuing Network: "+name[card_provider_list_number])
print("\nType: "+c_d[card_provider_list_number]+" Card")
print("\nCategory of the entity which issued the Card: "+mit_name)
else:
print("\nCard Number is Invalid\nPlease renter the number!\n")
else:
print("\nCard Number is Invalid\n")
#method called to run program
card_number_validation()
n = input("Enter 16-digit Credit Card Number:")
lst = []
for i in range(16):
lst.append(n[i])
# print(lst)
# list1 = n.split()
# print(list1)
def validate_credit_card():
global lst
if len(lst) == 16:
for i in range(0, len(lst)):
lst[i] = int(lst[i])
# print(lst)
last = lst[15]
first = lst[:15]
# print(first)
# print(last)
first = first[::-1]
# print(first)
for i in range(len(first)):
if i % 2 == 0:
first[i] = first[i] * 2
if first[i] > 9:
first[i] -= 9
sum_all = sum(first)
# print(first)
# print(sum_all)
t1 = sum_all % 10
t2 = t1 + last
if t2 % 10 is 0:
print("Valid Credit Card")
else:
print("Invalid Credit Card!")
else:
print("Credit Card number limit Exceeded!!!!")
exit()
if __name__ == "__main__":
validate_credit_card()
I have created a battleship like game, and have it all completed except for one detail.
I have the following input statement:
x, y = input("Enter two numbers here: ").split()
with the 2 numbers being entered corresponding to the players chosen coordinates. I also need to be able to handle the entry of 'q' or 'h' for the quit or help options. However, since i am taking two variables from this statement when only a q or h is entered i get the error that the statement needs 2 elements to unpack, which makes sense. Any pointers on how to get around this?
import random, math
class oceanTreasure:
def __init__(self):
self.board = self.board()
self.found = 0
self.left = 3
self.sonarsLeft = 20
self.chests= []
self.chest()
def board(self):
board = []
for x in range(16): # the main list is a list of 60 lists
board.append([])
for y in range(61): # each list in the main list has 15 single-character strings.
board[x].append('~')
return board
def chest(self):
chest1 = [random.randint(0,60), random.randint(0,15)]
chest2 = [random.randint(0,60), random.randint(0,15)]
chest3 = [random.randint(0,60), random.randint(0,15)]
self.chests = [chest1, chest2, chest3]
def getChestsLeft(self):
return self.found
def getChests(self):
return self.chests
def getTreasuresLeft(self):
return self.left
def getSonarsLeft(self):
return self.sonarsLeft
def dropSonar(self,x,y):
ySonar = ['a','b','c','d','e','f','g']
whichAxis, axis = self.checkDistance(x,y)
if whichAxis == True:
sonar = axis
if whichAxis == 'xaxis':
sonar = axis
elif whichAxis == 'yaxis':
sonar = ySonar[axis-1]
elif whichAxis == None:
sonar = axis
self.board[int(y)][int(x)] = sonar
self.sonarsLeft -=1
return axis
def checkDistance(self,x,y):
closest = self.chests[0]
distance = 100
for chest in self.chests:
temp = math.sqrt(math.pow((chest[0]-int(x)),2) + math.pow((chest[1]-int(y)),2))
if temp < distance:
closest = chest
distance = temp
xaxis =math.fabs((closest[0] - int(x)))
yaxis = math.fabs((closest[1]-int(y)))
if yaxis == 0 and xaxis == 0:
self.chests.remove(closest)
self.found +=1
self.left -=1
return True, 'X'
elif xaxis <= 9 and yaxis <=5 :
if yaxis == 0 :
return 'xaxis',int(math.fabs(xaxis))
if xaxis == 0 :
return 'yaxis',int(math.fabs(yaxis))
if min(xaxis//2,yaxis) ==(xaxis//2) :
return 'xaxis', int(math.fabs(xaxis))
elif min(xaxis//2,yaxis) == (yaxis) or xaxis == 0 :
return 'yaxis', int(math.fabs(yaxis))
else: return None,0
def drawBoard(self):
firstLine = ' '
for i in range(1,7):
firstLine += (' '*9) + str(i)
print(firstLine)
secondLine = ' '
secondLine += ('0123456789' *6)
print(secondLine)
print()
i = 0
for i in range(0,16):
boardRow = ''
for x in range(0,61):
boardRow += str(self.board[i][x])
if i < 10:
print(str(i) +' ' + str(boardRow) + str(i))
if i >= 10:
print(str(i) +' ' + str(boardRow) + str(i))
print()
print(secondLine)
print(firstLine)
device = 'devices'
if self.sonarsLeft ==1:
device = 'device'
print('You have %s sonar %s availabe. You have found %s treasures and have %s left' %(self.sonarsLeft, device, self.found, self.left))
ocean = oceanTreasure()
ocean.drawBoard()
gameOver = False
instructionsList = ['This is a treasure hunting game.' , 'You begin the game with 20 sonar devices available (each device has a range of 9 units in the x axis and 5 in the y axis).','When you place a device, if an "O" is displayed that means there are no chests in range.', 'If a number from 1-9 is displayed, the closest chest is within n units away on the X axis.', 'If a letter from a-e is displayed, the closest chest is n units away on the Y axis (a =1, b =2 and so on...).', 'The game ends when you run out of sonar devices, all the treasure is found or you enter "q" to quit.', 'Thanks for playing and happy hunting!']
while ocean.getTreasuresLeft() != 0 and ocean.getSonarsLeft() >0 and gameOver == False:
response = False
coordinate = False
while response == False:
inputString = input("Enter two numbers seperated by a space (X Y): ")
if inputString == 'q':
gameOver = True
response = True
elif inputString == 'h':
for instruction in instructionsList:
print(instruction)
response = True
else:
try:
x,y = inputString.split()
assert int(x) <=60 and int(y) <=15
response = True
coordinate = True
except AssertionError:
print('Please enter a valid move')
if gameOver == True:
break
#whichAxis, axis =ocean.checkDistance(x,y)
#print(axis)
if coordinate == True:
axis = ocean.dropSonar(x,y)
ocean.drawBoard()
if axis == 'X':
print('Congratulations, you have found a treasure!')
if ocean.getTreasuresLeft() == 0:
print('Congratulations, you found all the treasure')
elif ocean.getSonarsLeft() == 0:
print('Sorry, you ran out of sonar devices, the remaining chests were: %s ' % str(ocean.getChests()))
How about separating the tests to be a little clearer:
input_string = input("Enter two numbers here: ")
if input_string == 'q':
do_quit()
elif input_string == 'h':
do_help()
else:
x,y = input_string.split()
That way you can test for your special cases, and process the x and y if they are not found.
may be this, for example:
a = input("text")
b = a.split()
if len(b) == 1:
if b[0] == 'q':
return
elif b[0] == 'h':
print 'it is help ... '
elif len(b) == 2:
# process for two inputted numbers
You can just separate the input:
# get the input
ipt = input("Enter two numbers here: ")
# check if your option is entered
if ipt == 'q' or ipt == 'h':
# do something
else:
x,y = ipt.split()
Hi having trouble trying to fix an error that occurs when I put just a '#' or rogue value in case someone doesn't want to add any data. I don't know how to fix it and I'm hoping to just end the code just like I would with data.
#Gets Data Input
def getData():
fullList = []
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
while inputText != "#":
nameList = []
nameList2 = []
nameList = inputText.split()
nameList2.extend((nameList[0],nameList[1]))
nameList2.append((float(nameList[2]) + float(nameList [3]))/2)
fullList.append(nameList2)
inputText = checkInput("Enter the students first name, last name, first mark, and second mark (# to exit): ")
print("\n")
return fullList
#Calculates Group Average
def calc1(fullList):
total = 0
for x in fullList:
total = total + x[2]
groupAverage = total/(len(fullList))
return(groupAverage)
#Finds Highest Average
def calc2(fullList):
HighestAverage = 0
nameHighAverage = ""
for x in fullList:
if x[2] > HighestAverage:
HighestAverage = x[2]
nameHighAverage = x[0] + " " + x[1]
return (HighestAverage, nameHighAverage)
#Returns Marks above average
def results1(groupAverage,r1FullList):
r1FullList.sort()
print("List of students with their final mark above the group average")
print("--------------------------------------------------------------")
print("{:<20} {:<12}".format("Name","Mark"))
for x in r1FullList:
if x[2] > groupAverage:
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f}".format(name,x[2]))
def calc3(x):
if x[2] >= 80:
return 'A'
elif x[2] >= 65:
return 'B'
elif x[2] >= 50:
return 'C'
elif x[2] < 50:
return 'D'
else:
return 'ERROR'
def results2(fullList):
print("List of Studens with their Final Marks and Grades")
print("-------------------------------------------------")
print("{:<20} {:<12} {:<12}".format("Name","Mark","Grade"))
for x in fullList:
grade = calc3(x)
name = x[0] + " " + x[1]
print("{:<20} {:<12.2f} {:<12}".format(name,x[2],grade))
#Checks for boundary and invalid data
def checkInput(question):
while True:
textInput = input(question)
if textInput == "#":
return textInput
splitList = textInput.split()
if len(splitList) !=4:
print("Invalid Format, Please Try Again")
continue
try:
a = float(splitList[2])
a = float(splitList[3])
if float(splitList[2]) < 0 or float(splitList[2]) > 100:
print("Invalid Format, Please Try Again")
continue
if float(splitList[3]) < 0 or float(splitList[3]) > 100:
print("Invalid Format, Please Try Again")
continue
return(textInput)
except ValueError:
print("Invalid Input, Please Try Again")
continue
#Main Program
#Input Data
fullList = getData()
#Process Data
groupAverage = calc1(fullList)
HighestAverage, nameHighAverage = calc2(fullList)
#Display Results
print("The group average was %.2f" % groupAverage)
print("The student with the highest mark was: %s %0.2f" %(nameHighAverage,HighestAverage))
results1(groupAverage,fullList)
print("\n")
results2(fullList)
Your program works OK for me, unless you enter a # as the first entry, in which case fullList is [] and has length 0. Hence, DivisionByZero at this line: groupAverage = total/(len(fullList)).
You could modify your code to check for this and exit:
import sys
fullList = getData()
if not fullList:
print('No Data!')
sys.exit()