Cant get str to work in if-loop Python 3 - python

I wrote a grade calculator where you put a float in and get a grade based on what you scored. The problem I have is that I belive I need a float(input... But that becomes an error if you write letters in the box...
def scoreGrade():
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
score = float(input("Please write the score you got on the test, 0-10: "))
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Is there a way to get rid of the float and print the last statement if you write something else that the score from 0-10?

Something like this:
score = None
while score is None:
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
continue
Keep on asking until the float cast works without raising the ValueError exception.

You could do
try:
score = float(input("Please write the score you got on the test, 0-10: "))
except ValueError:
print("Grow up and write your score between 0 and 10")
scoreGrade()

I would suggest to use EAFP approach and separate handling good and bad inputs.
score_as_string = input("Please write the score you got on the test, 0-10: ")
try:
score_as_number = float(score_as_string)
except ValueError:
# handle error
else:
print_grade(score_as_number)
def print_grade(score):
"""
Determine the grade from a score
"""
gradeA = "A"
gradeB = "B"
gradeC = "C"
gradeD = "D"
gradeF = "F"
if score >= 9:
print("You did really good, your grade is:", gradeA, ". Congratulations")
elif score >= 7:
print("Your results are good. They earn you a:", gradeB, ". Better luck next time")
elif score >= 5:
print("Not too bad. You got a:", gradeC)
elif score >= 4:
print("That was close...:", gradeD)
elif score < 4:
print("You need to step up and take the test again:", gradeF)
else:
print("Grow up and write your score between 0 and 10")
Note that typically you want to return from functions, not print inside them. Using function output as part of print statement is detail, and function does not have to know that.

Related

Test average and grade

def calc_average(a,b,c,d,f):#function used to calculate average
return (a+b+c+d+f)//5
def determine_grade(test_score):#function used to determine letter grade
if gradeAverage > 89:
return "A"
elif gradeAverage > 79:
return "B"
elif gradeAverage > 69:
return "C"
elif gradeAverage > 59:
return "D"
else:
return "F"
test1 = float(input("Please enter test score for test1: "))#prompt user to enter grade
test2 = float(input("Please enter test score for test2: "))#prompt user to enter grade
test3 = float(input("Please enter test score for test3: "))#prompt user to enter grade
test4 = float(input("Please enter test score for test4: "))#prompt user to enter grade
test5 = float(input("Please enter test score for test5: "))#prompt user to enter grade
gradeAverage = calc_average(test1, test2, test3, test4, test5)#variable
finalgrade = determine_grade(gradeAverage)#variable
print(finalgrade)#display grade
print(gradeAverage)display grade letter
This is a problem in the "starting out with Python" book, I am supposed to calculate the average grade of 5 test scores and give a letter grade. My problem is, I wonder if I need the variables or not. If there is a better way I would like to know.
You can use for loops and lists to eliminate some variables and also generalize a bit:
def calc_average(grades): #function used to calculate average, now takes a list
return sum(grades)//len(grades)
grades = []
number_of_tests = int(input("input the total number of test results >>"))
for i in range(1, number_of_tests+1):
g = int(input("input grade " + str(i) +" >>"))
grades.append(g)
avg = calc_average(grades)
print(avg)
I would explain everything in detail, but I am sure your text book will soon enough tell you about "for loops", "lists", and so on. They usually start slow, and let you do unnecessary work so you can get used to the basics. Keep on reading m8 :)
(Or watch this video, in my opinion this is one of the best beginners guides out there: https://youtu.be/rfscVS0vtbw)
Please allow me to share a few comments:
The function determine_grade(test_score) takes in a parameter test_score, and should be using this parameter to determine the grade, instead of the global parameter gradeAverage. So your code should be:
def determine_grade(test_score):#function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
The calculation for average should not be a floor division (a+b+c+d+f)//5. This floor division formula outputs only the integer value and ignores the decimals behind. So the formula should be (a+b+c+d+f)/5.
A for loop would be elegant, and avoiding repeated codes. Then a list test_list could be used to store the test scores and be passed to the function calc_average to calculate the average.
The final code should look like this:
def calc_average(test_list): #function used to calculate average
return sum(test_list)/len(test_list)
def determine_grade(test_score): #function used to determine letter grade
if test_score > 89:
return "A"
elif test_score > 79:
return "B"
elif test_score > 69:
return "C"
elif test_score > 59:
return "D"
else:
return "F"
n = 5
test_list = []
for i in range(n):
score = float(input("Please enter test score for test{}: ".format(i+1))) #prompt user to enter grade
test_list.append(score)
gradeAverage = calc_average(test_list) #variable
finalgrade = determine_grade(gradeAverage) #variable
print(finalgrade) #display grade
print(gradeAverage) #display grade letter
Output
Please enter test score for test1: 66
Please enter test score for test2: 77
Please enter test score for test3: 88
Please enter test score for test4: 86
Please enter test score for test5: 69
C
77.2

I need help on a python guessing game

I need help changing the range and showing the user what the range is so they know if they are closer or not. I have given the description I have been given. On what I need to do . I have given the code that I have come up wit so far. Let me know if you need anything else from me.
Step 6 – Guiding the user with the range of values to select between
Add functionality so that when displaying the guess prompt it will display the current range
to guess between based on the user’s guesses accounting for values that are too high and too
low. It will start out by stating What is your guess between 1 and 100, inclusive?, but as
the user guesses the range will become smaller and smaller based on the value being higher
or lower than what the user guessed, e.g., What is your guess between 15 and 32,
inclusive? The example output below should help clarify.
EXAMPLE
----------------
What is your guess between 1 and 44 inclusive? 2
Your guess was too low. Guess again.
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
play()
#Part 1
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.")
print("\n")
def play():
''' Plays a guessing game'''
number = int(random.randrange(1,10))
guess = int(input("What is your guess between 1 and 10 inclusive ?: "))
number_of_guess = 0
while guess != number :
(number)
#Quit
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
#Guessing
if guess < number:
if guess < number:
guess = int(input("Your guess was too low. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
if guess > number:
if guess > number:
guess = int(input("Your guess was too high. Guess Again: "))
number_of_guess += 1
elif guess not in range(1,11):
print("Invalid guess – out of range. Guess doesn’t count. : ")
guess = int(input("Guess Again: "))
else:
guess = input("Soemthing went wrong guess again: ")
#Winner
if guess == number :
number_of_guess += 1
print("Congratulations you won in " + str(number_of_guess) + " tries!")
again()
def again():
''' Prompts users if they want to go again'''
redo = input("Do you want to play again (Y or N)?: ")
if redo.upper() == "Y":
print("OK. Let’s play again.")
play()
elif redo.upper() == "N":
print("OK. Have a good day.")
sys.exit(0)
else:
print("I’m sorry, I do not understand that answer.")
again()
main()
What you'll need is a place to hold the user's lowest and highest guess. Then you'd use those for the range checks, instead of the hardcoded 1 and 11. With each guess, if it's a valid one, you then would compare it to the lowest and highest values, and if it's lower than the lowest then it sets the lowest value to the guess, and if it's higher than the highest it'll set the highest value to the guess. Lastly you'll need to update the input() string to display the lowest and highest guesses instead of a hardcoded '1' and '10'.
You need to simplify a lot your code. Like there is about 6 different places where you ask a new value, there sould be only one, also don't call method recursivly (call again() in again()) and such call between again>play>again.
Use an outer while loop to run games, and inside it an inner while loop for the game, and most important keep track of lower_bound and upper_bound
import random
import sys
def main():
print("Assignment 6 BY enter name.")
welcome()
redo = "Y"
while redo.upper() == "Y":
print("Let’s play")
play()
redo = input("Do you want to play again (Y or N)?: ")
def welcome():
print("Welcome to the guessing game. I have selected a number between 1 and 100 inclusive. ")
print("Your goal is to guess it in as few guesses as possible. Let’s get started.\n")
def play():
lower_bound, upper_bound = 0, 100
number = int(random.randrange(lower_bound, upper_bound))
print(number)
guess = -1
number_of_guess = 0
while guess != number:
guess = int(input(f"What is your guess between {lower_bound} and {upper_bound - 1} inclusive ?: "))
if guess == -999:
print("Thanks for Playing")
sys.exit(0)
elif guess not in list(range(lower_bound, upper_bound)):
print("You're outside the range")
continue
number_of_guess += 1
if guess < number:
print("Your guess was too low")
lower_bound = guess
elif guess > number:
print("Your guess was too high")
upper_bound = guess
print("Congratulations you won in", number_of_guess, "tries!")

How To Determine Grades in Python [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
This is using Python 3, through a website known as Repl.it
I am currently working on solving a question that states:
"Write a program that will take a grade between 100 and 0 zero and print the letter grade according to the scale:
90 or above is equivalent to an A grade
80-89 is equivalent to a B grade
70-79 is equivalent to a C grade
65-69 is equivalent to a D grade
64 or below is equivalent to an F grade
if user gives something other then integer or something that is not between 0 and 100 give an error and ask again.
Example run:
Enter the number grade: asd
Program only accepts integers between 0 and 100
Enter the number grade: 65
Your grade is D"
My current code is as follows:
def printgrade(score):
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 65:
print("D")
elif score <= 64:
print("F")
else:
print("ERROR")
def main():
score = int(input("Enter a score: "))
print("Your grade is:", printgrade(score))
main()
The only error message that I am receiving is that print is invalid syntax, but I cannot figure out as to why, am I just missing something? Any comments will be greatly appreciated.
Besides the error with the ( going through the code some modifications could make this a little more optimal. We can use a try, except block to eliminate the ERROR else statement and handle that directly when we receive the input if is not a valid int and we force a valid int between 0 and 100 using a while statement. Next our function should return 'A' or B, C etc. Then when we can use the print('Your grade is: ', printgrade(score)) as desired
def printgrade(score):
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 65:
return "D"
else:
return "F"
def main():
score = ''
while score not in range(0,101):
try:
score = int(input("Enter a score: "))
except ValueError:
print('Invalid Entry')
print("Your grade is:", printgrade(score))
main()
def printgrade(score):
if score >= 90: return "A"
elif score >= 80: return "B"
elif score >= 70: return "C"
elif score >= 65: return "D"
elif score <= 64: return "F"
else: return "ERROR"
def main():
score = int(input("Enter a score: "))
print("Your grade is:", printgrade(score))
main()
Hope it helps. You have to return value and not print them inside the sub function as your print function is expecting a value from your sub function.

basic looping in Python

New to this so please bear with me. I'm trying to run a loop that asks the user to input a number between 1 and 100. I want to make it to where if they enter a number outside of 100 it asks again. I was able to do so but I can't figure out if I'm using the correct loop. Also whenever I do get inbetween 1 and 100 the loop continues.
code below:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
else:
while user_input > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
I think the clearest way to do this is to start with a loop that you break out of when you finally get the right answer. Be sure to handle a bad input like "fubar" that isn't an integer
while True:
try:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
break
print("Not between 1 and 100, try again")
except ValueError:
print("Not a number, try again")
In python 3 you can use range to do bounds checking. If you do
if user_input in range(1, 101)
range will calculate the result without actually generating all of the numbers.
When your code is run, it will continue to ask for an input, even if the input given is less than 100. One way to fix this would be to do this:
try_again = 1000
user_input = int(input("Enter a number between 1 and 100: "))
if user_input >= 1 and user_input <= 100:
print("NICE!")
elif user_input > 100:
while try_again > 100:
try_again = int(input("try again "))
if try_again >= 1 and try_again <= 100:
print("There you go!")
This code first tests if the user's input is more than 100, then runs a while statement in which the base value is more than 100. When the user inputs another value, if it is over 100, it continues, otherwise it does not.
Below is an example of a program that gets you the output that you are seeking:
attempts = 0
while True:
user_input = int(input("Enter a number between 1 and 100: "))
if user_input > 100 or user_input < 1:
print('Please try again')
attempts += 1
continue
elif attempts >= 1 and user_input <= 100 and user_input >= 1:
print('There you go!')
break
else:
print('Nice!')
break
Start by putting your prompt for the user within the loop so that the user can be asked the same prompt if the fail to enter a number between 1 and 100 the first time. If the user input is greater than 100 or less than 1, we will tell the user to try again, we will add 1 to attempts and we will add a continue statement which starts the code again at the top of the while loop. Next we add an elif statement. If they've already attempted the prompt and failed (attempts >= 1) and if the new input is less than or equal to 100 AND the user input is also greater than or equal to 1, then the user will get the 'There you go' message that you assigned to them. Then we will break out of the loop with a break statement in order to avoid an infinite loop. Lastly we add an else statement. If the user satisfies the prior conditions on the first attempt, we will print 'Nice' and simply break out of the loop.

School test grader

I have tried to write a code where you simply type your test score (out of 100) and it gives you a grade (A,B,C,D..etc). However the code I have written, for some reason, gives me the wrong grade when I give it a random number. for example, I typed 6 and it give me a D (instead of a U).
Here is my code:
score=int(input("What score did you get on your test?"))
if int(0)>=score<=int(39):
print ("You have got a U in your test.")
elif int(40)>=score<=int(49):
print ("You have got a D in your test.")
elif int(50)>=score<= int(59):
print ("You have got a C in your test.")
elif int(60)>=score<= int(69):
print ("You have got a B in your test.")
else:
("You have got an A in your test, well done!")
Your inequalities are incorrect. Currently, the condition for U is
if score is smaller than 0 and smaller than 39
It should be
if score is greater than 0 and smaller than 39
so
if int(0) <= score <= int(39)
However, you can simplify all of your code a considerable amount, as others have pointed out. You can remote the double-sided inequalities and replace them with single ones, remove the int conditions, since you're not expecting any non-ints (the numbers 39, 49 etc. are hardcoded), and you should also add an error message of some kind for any grades below 0 or above 100 (currently, they return a U and A respectively, but it should really be an error).
A better solution:
score=int(input("What score did you get on your test?"))
if score < 0:
print("How did you manage to get less than zero?!")
elif score <= 39:
print ("You have got a U in your test.")
elif score <= 49:
print ("You have got a D in your test.")
elif score <= 59:
print ("You have got a C in your test.")
elif score <= 69:
print ("You have got a B in your test.")
elif score <= 100:
print ("You have got an A in your test, well done!")
else
print ("This isn't a valid grade, it should be between 0 and 100!")

Categories