Wanting to input bowling scores, total, average them - python

Need for a user to input bowling scores and store them, to be totaled and averaged later and they can press "q" or "Q" to quit and total/average them. I've tried fumbling around figuring out loops but not sure how to deal with inputting integers and also accepting "Q" to stop loop. Thanks for any help.
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
Getting error:
Traceback (most recent call last):
File "/Users/ryaber/PycharmProjects/pythonProject/main.py", line 11, in
scores = input("Please enter a score (xxx) or 'q' to exit: ")
File "", line 1, in
NameError: name 'q' is not defined
So not sure how to allow it to accept "Q" to stop loop and total/average them.

Remove .lower() in q.lower() and move it and make it to score.lower().
So if user types in q or Q both will be accepted as quit
You do not need average function or while scores != 'q' instead you could change it to something simple
So complete code -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == 'q':
print("quitting")
break
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
Result:
Please enter a score (xxx) or 'q' to exit: 25
Please enter a score (xxx) or 'q' to exit: 32
Please enter a score (xxx) or 'q' to exit: Q
quitting
The total score is: 57
The score average is: 28.5
Edit -
While this may be complicated, this will solve your problem -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
try: # This will run when scores is a number
scores = int(scores)
if scores.lower() == type(0):
nums.append(int(scores))
except: # Will run when it is a alphabet
if scores.lower() == 'q':
print("quitting")
break
else:
continue
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
break

nums.append(int(scores))
just cast it to an int ...

You only need to convert your input string to an int before storing it:
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))

You need to append integral value of score to the list
nums.append(int(scores))
Also, I guess you might want to use a f-string here
print(f"The total score is: {total}")
EDIT :
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
As pointed out by #PCM, you need to use the .lower() method on the variable
The final working code :
nums = []
scores = ""
while scores != 'q':
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
You can read more about f-strings here

Related

I want to print when the user fails to type a positive number it will tell them the number was not valid (eg -8.25)

def itemPrices():
items = []
while True:
itemAmount = float(input("Enter the amount for the item: "))
if itemAmount < 0:
continue
again = input("Do you want to add another item? Enter 'y' for yes and 'n' for no: ")
items.append(itemAmount)
if again == "y":
continue
elif again == "n":
numItems = len(items)
print(f"You purchased {numItems} items.")
sumAmount = sum(items)
print(f"The total for this purchase is {sumAmount} before tax.")
print(f"The average amount for this purchase is {sumAmount/numItems}.")
if numItems >= 10:
tax = (9/100)*sumAmount
else:
tax = (9.5/100)*sumAmount
print(f"You owe ${tax} in tax.")
break
else:
print("Invalid input")
continue
itemPrices()
while True:
user_input = input("type a number")
try:
if float(user_input) < 0:
print('this number is less than zero please try again')
continue
else:
print("good job this number is valid")
# place the code you want to execute when number is positive here
break
except ValueError:
print("this is not a number please enter a valid number")
continue

Python array loop not looping/validator issues

I'm not exactly sure what I did, but when testing my code it either crashes immediately or gets stuck in a loop. If the first input is a value error (string) and the next is a number it loops as long as the pattern is kept. But if first user entry is int then program crashes. Please any help would be appreciated.
def main():
courseArray = []
keepGoing = "y"
while keepGoing == "y":
courseArray = getValidateCourseScore()
total = getTotal(courseArray)
average = total/len(courseArray)
print('The lowest score is: ', min(courseArray))
print('The highest score is: ', max(courseArray))
print('the average is: ', average)
keepGoing = validateRunAgain(input(input("Do you want to run this program again? (Y/n)")))
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray)
except ValueError:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
counter += 1
return courseArray
def valScore(courseArray):
score = int(courseArray)
if score < 0:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
elif score > 100:
print("Please enter a valid score between 0-100")
courseArray.append(int(input("Enter a number between 1 and 100: ")))
else:
return courseArray
def validateRunAgain(userInput):
if userInput == "n" or userInput == "N":
print("Thanks for using my program")
return "n"
elif userInput == "y" or userInput == "Y":
return "y"
else:
print("Please enter y or n")
validateRunAgain(input("Do you want to run this program again? (Y/n)"))
return getValidateCourseScore()
def getTotal(valueList):
total = 0
for num in valueList:
total += num
return total
main()
There are too many inputs from the user, so I have cut down on them and changed it.
Here are the sections of your code which I have changed :
Here valScore() I presume validates the input score so, I also gave the index of element to be validated. If it is not valid we remove it from the array and raise ValueError, since it raises error our counter is not updated.
keepGoing = validateRunAgain()
def getValidateCourseScore():
courseArray = []
counter = 1
while counter < 6:
try:
courseArray.append(int(input("Enter the number of points received for course: ")))
valScore(courseArray, counter - 1)
counter += 1
except ValueError:
print("Please enter a valid score between 0-100")
continue
return courseArray
def valScore(courseArray, counter):
score = courseArray[counter]
if score < 0 or score > 100:
courseArray.pop()
raise ValueError
def validateRunAgain():
while True:
userInput = input("Do you want to run this program again? (Y/n)")
if userInput == 'y' or userInput == 'Y':
return 'y'
elif userInput == 'n' or userInput == 'N':
print('thank you for using my program')
return 'n'
else:
print('Enter Y or N')

How to stop loop?

I'm a step away from completing my binary converter, though it keeps on repeating, it's and endless loop.
def repeat1():
if choice == 'B' or choice == 'b':
while True:
x = input("Go on and enter a binary value: ")
try:
y = int(x, 2)
except ValueError:
print("Please enter a binary value, a binary value only consists of 1s and 0s")
print("")
else:
if len(x) > 50:
print("The number of characters that you have entered is", len(x))
print("Please enter a binary value within 50 characters")
z = len(x)
diff = z - 50
print("Please remove", diff, "characters")
print(" ")
else:
print(x, "in octal is", oct(y)[2:])
print(x, "in decimal is", y)
print(x, "in hexidecimal is", hex(y)[2:])
print(" ")
def tryagain1():
print("Type '1' to convert from the same number base")
print("Type '2' to convert from a different number base")
print("Type '3' to stop")
r = input("Would you like to try again? ")
print("")
if r == '1':
repeat1()
print("")
elif r == '2':
loop()
print("")
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
else:
print("You didn't enter any of the choices! Try again!")
tryagain1()
print("")
tryagain1()
I'm looking for a way to break the loop specifically on the line of code "elif r== '3':. I already tried putting 'break', but it doesn't seem to work. It keeps on asking the user to input a binary value even though they already want to stop. How do I break the loop?
elif r == '3':
print("Thank you for using the BraCaLdOmbayNo Calculator!")
return 0
else:
print("You didn't enter any of the choices! Try again!")
choice = try again()
if choice == 0:
return 0
print("")
tryagain1()
return is suppose to be used at the end of the Function or code when you have nothing else to do

Finding A Collective Average & Letter Grade For Tests & Assignments

I am using Python 3.4.1 and I am trying to write a code that does the following:
class Student(object):
def __init__(self, name):
self.name, self.grades = name, []
def append_grade(self, grade):
self.grades.append(grade)
def average(self):
return sum(self.grades) / len(self.grades)
def letter_grade(self):
average = self.average()
for value, grade in (90, "A"), (80, "B"), (70, "C"), (60, "D"):
if average >= value:
return grade
else:
return "F"
def main():
print()
a_class = [] # "class" by itself is a reserved word in Python, avoid using
while True:
print()
print('{} students in class so far'.format(len(a_class)))
another_student = input('Do you have another student to enter (y/n) ? ')
if another_student[0].lower() != 'y':
break
print()
student_name = input('What is the student\'s ID? ')
a_class.append(Student(student_name))
print()
print('student :', student_name)
print('------------------------------------------------')
number_of_tests = int(input('Please enter the number of tests : '))
for test_num in range(1, number_of_tests+1):
print('test grade {}'.format(test_num), end='')
score = float(input(' : '))
if score < 0: # stop early?
break
number_of_assignments = int(input('Please enter the number of assignments : '))
for assignment_num in range(1, number_of_assignments+1):
print('assignment grade {}'.format(assignment_num), end='')
score2 = float(input(' : '))
if score2 < 0: # stop early?
break
number_of_participation = int(input('Please enter 1 to add participation grade : '))
for participation_num in range(1, number_of_participation+1):
print('participation grade {}'.format(participation_num), end='')
score3 = float(input(' : '))
if score3 < 0: # stop early?
break
a_class[-1].append_grade(score + score2 + score3) # append to last student added
print_report(a_class)
def print_report(a_class):
print()
print('Student Grades')
print()
for student in sorted(a_class, key=lambda s: s.name):
print('student: {:20s} average test score: {:3.2f} grade: {}'.format(
student.name, student.average(), student.letter_grade()))
print()
print('The class average is {:.2f}'.format(class_average(a_class)))
def class_average(a_class):
return sum(student.average() for student in a_class) / len(a_class)
main()
The task here is to get the letter grade of a student by adding 3 different things and getting the average. I need to be able to input the test scores, assignment scores, and 1 participation grade. Those need to average out and give me a final letter grade. I was able to find out how to do just one set of scores to average but when I added the other scores, the average is wrong. What can I edit here?
I didn't look in great detail, but this:
a_class[-1].append_grade(score + score2 + score3)
...makes me suspect that you are adding a single value to the list of grades, that is above 100%. That might account for your averages being too high.
Instead, you likely should:
a_class[-1].append_grade(score)
a_class[-1].append_grade(score2)
a_class[-1].append_grade(score3)

how to implement empty string in python

I need to be able to prompt the user to enter an empty string so it can check if the answer is correct. but every time I do that I can error saying invalid literal for int()
so I need to change my user_input so it can accept int() and strings(). how do I make that possible ?
# program greeting
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value.\n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.")
print("--------------------")
#print("Enter coins that add up to 81 cents, one per line.")
import sgenrand
#prompt the user to start entering coin values that add up to 81
while True:
total = 0
final_coin= sgenrand.randint(1,99)
print ("Enter coins that add up to", final_coin, "cents, on per line")
user_input = int(input("Enter first coin: "))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
while total <= final_coin:
user_input = int(input("Enter next coin:"))
if user_input != 1 and user_input!=5 and user_input!=10 and user_input!=25:
print("invalid input")
else:
total = total + user_input
if total > final_coin :
print("Sorry - total amount exceeds", (final_coin))
elif total < final_coin:
print("Sorry - you only entered",(total))
else:
print("correct")
goagain= input("Try again (y/n)?:")
if goagain == "y":
continue
elif goagain == "n":
print("Thanks for playing ... goodbye!" )
break
Store the value returned by input() in a variable.
Check that the string is not empty before calling int().
if it's zero, that's the empty string.
otherwise, try int()ing it.

Categories

Resources