I have the program working how I'd like it to, but I cannot seem to figure out how to add validation for the user test score input. The inputs need to be from 0 - 100 and validate each entered score.
How would I modify my code to use a validation loop for input to be >= 0 and <= 100 in the prompt_scores function?
I previously attempted a while loop but it was ignored when placed on each individual input.
def calc_average(scoreOne, scoreTwo, scoreThree):
average = (scoreOne + scoreTwo + scoreThree)/3
return average
def determine_grade(studentScore):
if studentScore < 60:
return "F"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def prompt_scores():
enteredScoreOne = int(input("Please enter score 1: "))
enteredScoreTwo = int(input("Please enter score 2: "))
enteredScoreThree = int(input("Please enter score 3: "))
return enteredScoreOne, enteredScoreTwo, enteredScoreThree
def print_results(scoreOne, scoreTwo, scoreThree):
print("\nScore\tLetter Grade" )
print(str(scoreOne) + "\t\t" + determine_grade(scoreOne), \
str(scoreTwo) + "\t\t" + determine_grade(scoreTwo), \
str(scoreThree) + "\t\t" + determine_grade(scoreThree), sep = "\n")
def main():
scoreOne, scoreTwo, scoreThree = prompt_scores()
print_results(scoreOne, scoreTwo, scoreThree)
print("-----------------------")
print("Average score: " + str(int(calc_average(scoreOne, scoreTwo,scoreThree))))
print(" Final grade: " + determine_grade(int(calc_average(scoreOne, scoreTwo, scoreThree))))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main == "Y" or rerun_main == "y":
main()
main()
enteredScoreOne = int(input("Please enter score 1: "))
while enteredScoreOne not in range(0, 101):
print("[!] Invalid input!")
enteredScoreOne = int(input("Please enter score 1: "))
And so on for the other variables.
If you're running Python 2 (given that you're using input to read strings, you're not, but I'll add this just in case), you'd better replace in range(...) with (0 <= enteredScoreOne <= 100) as range would return a list, which would consume a little bit of extra memory.
You can check the entered value while getting input if you use function and can force the user to enter the value between 0-100 using recursion also i can see you are using additional functions for which python itself has a built in eg: sum(). Also try to save memory and processing wherever possible now it may not seem a big issue but when you have 1000 lines of code even these small things will save you. Here i mean instead of calling a function twice you can save the result in a variable and use it. I added all these in my code and have given the answer.
def get_input():
try:
score=int(input("please enter score : "))
if (score >=0 and score <100):
return score
else:
print("Score should be inbetween 0-100. Try again :-(:-(:-(")
get_input()
except:#if user enters any special char except float or int tell him to enter int
print("Only integer is accepted")
def determine_grade(avg):
if studentScore < 60:
return "E"
elif studentScore < 70:
return "D"
elif studentScore < 80:
return "C"
elif studentScore < 90:
return "B"
elif studentScore < 101:
return "A"
def print_results(*args):
for i,j in enumerate(args):
print("score "+str(i)+" = "+str(j)+" grade = "+determine_grade(j))
def main():
score1 = get_input()
score2 = get_input()
score3 = get_input()
print_results(score1, score2, score3)
print("-----------------------")
avg=sum([score1,score2,score3])/3
print("Average score: " + str(avg))
print(" Final grade: " + determine_grade(avg))
rerun_main = input("Do you want to continue? Enter y/n: ")
if rerun_main.lower() == "y":
main()
main()
Related
# function to calculate average marks of the list
def average_marks(marks):
total_sum_of_scores = sum(marks)
total_num_of_sub = len(marks)
average_marks = total_sum_of_scores / total_num_of_sub
return average_marks
# funtion to compute grade based on average_marks
def compute_grade(average_marks):
if average_marks >= 80:
grade = "A"
elif average_marks >= 60:
grade = "B"
elif average_marks >= 50:
grade = "C"
else:
grade = "F"
return grade
marks = [75,77,94,78,83,86,72]
average_marks = average_marks(marks)
grade = compute_grade(average_marks)
print("Your result is: ",average_marks , "and your grade is:", grade)
Instead of using a predefined list. I want to take input from users. Users will enter number and when "done" is entered, the programme is terminated. Below is what i have tried but no luck.
def marks():
n = int(input("Enter your number"))
marks = []
for i in range(n):
element = int(input("Please enter students score: "))
marks.append(element)
result = marks
print(marks)
marks()
Try this:
marks = input("Please enter your scores: ").split()
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After getting input from console, you should create a loop which breaks when guessed number equal to input. For example:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
After revision, code seems like:
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while result != guess:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
break
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
It's because python programs runs from top to bottom, and when it reaches the bottom it's done and stops running. To stop this order we have multiple different ways:
We can call a function, as you do in you're program.
Selection Control Structures: As if statements
Iteration Control Structures: As loops
The last one is the one you need in this solution. Wrap code in a while loop, with the correct condition, in you're example, this would be
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
The best way woul be to use a will loop as follow:
while guess != num:
You should use while True:, because your guessing code runs only once without it
import random
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 10)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
att = 1
num = num_gen()
while True:
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
# Process - Guess and Display Result
result = num_check(guess, num)
if result == 'high':
print('Your guess was HIGH! Please guess another number between 1 and 100: ')
att += 1
elif result == 'low':
print('Your guess was LOW! Please guess another number between 1 and 100: ')
att += 1
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
break
how can you expect it to run more than 1 time if you have not used any loop in the program. For example in this case you should use a while loop, then only it will prompt the user again and again and will check for the conditions, set a game variable to be True. When the number is matched then simply set the game variable to be False and it will end the loop.
import random
# Set the game variable initially to be True
game = True
# Define function - Number Generator
def num_gen():
num = random.randrange(1, 101)
return num
# Define function - Number Check
def num_check(x, y):
result = ''
if x > y:
result = 'high'
elif x < y:
result = 'low'
else:
result = 'correct'
return result
# Call - Number Generator
num = num_gen()
# Input - Guess
guess = int(input('Please guess a number between 1 and 100: '))
att = 1
# Process - Guess and Display Result
result = num_check(guess, num)
while game:
if result == 'high':
guess = int(input('Your guess was HIGH! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
elif result == 'low':
guess = int(input('Your guess was LOW! Please guess another number between 1 and 100: '))
att += 1
result = num_check(guess, num)
else:
print('Your guess was CORRECT! You got it in ' + str(att) + ' attempts!')
game = False
Error is saying grade isn't defined and I don't know how to define it. I googled a bunch but I don't think the information helped much. Or at least it didn't click in my brain... I appreciate the help.
class ClassGrader:
earnedTotal = 0.0
Total = 0.0
grade = Grade()
while 'earned' != 'exit':
earned = input("What is the grade earned? or type *exit* to proceed to the next section: ")
if earned == 'exit':
while 'subTotal' != 'exit':
subTotal = input("What is the total of assignment? Enter the next... or type *exit* for the average grade: ")
if subTotal == 'exit':
average = earnedTotal/Total
print("The average of "+str(earnedTotal)+"/"+str(Total)+" is "+str(average*100)) + grade.Grade(average)
exit()
else:
Total=float(subTotal)+Total
print(Total)
else:
earnedTotal=float(earned)+earnedTotal
print(earnedTotal)
def Grade(i):
if i >= 90:
return "A"
elif i >= 80:
return "B"
elif i >= 70:
return "C"
elif i >= 60:
return "D"
else:
return "F"
You did have many, many problems here, not the least of which is unclear requirements. What you have here should be functions, not classes. You are confused between variables and strings. Here is something that mostly does what I THINK you want.
As a user experience thing, it's not fair to require them to type the whole word "exit" to stop the process. One mistake, and this will crash converting the string to float. You should just have them press "enter" and check for an empty string. I haven't done that here.
def Grade(avg):
return "FFFFFFDCBAA"[int(avg*10)]
def ClassGrader():
earnedTotal = 0.0
Total = 0.0
while True:
earned = input("What is the grade earned? or type *exit* to proceed to the next section: ")
if earned == 'exit':
break
earnedTotal+=float(earned)
print(earnedTotal)
while True:
subTotal = input("What is the total of assignment? Enter the next... or type *exit* for the average grade: ")
if subTotal == 'exit':
break
Total+=float(subTotal)
print(Total)
average = earnedTotal/Total
print(f"The average of {earnedTotal}/{Total} is {average*100)", Grade(average))
ClassGrader()
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')
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