This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 2 years ago.
What's poppin my coding gang. So atm I'm learning Python and I'm a totally a newbie and I face this problem. So I created a unit converting program and I was successful to make a while loop for unit and everything with the code below works just fine:
weight = int(input("Weight: "))
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
But I also wanted to experiment more and I also wanted to create a while loop for a weight input, so that it will go forever until you type any positive float or integer number, because when I run the program and in weight input I would accidently type a letter - a big red error would appear on my screen saying:
Exception has occurred: ValueError
invalid literal for int() with base 10: 'a'
line 1, in <module>
weight = int(input("Weight: "))
So when I tried to change it to a while loop, it didn't work and my final result looked like this:
weight = int(input("Weight: "))
while weight != int():
if weight==int():
break
else:
print("Invalid unit. Please type a number: ")
weight=int(input())
continue
unit = input("(K)g or (L)bs ? ")
while unit.upper != ("K" or "L"):
if unit.upper()=="L":
converted = weight*0.45
print(f"You are {round(converted)} kilos")
break
elif unit.upper()=="K":
converted=weight//0.45
print(f"You are {converted} pounds")
break
else:
print("Invalid unit. Please type K or L: ")
unit=input()
continue
I know it's shit and at this point I'm stuck, it's just constantly typing me "Invalid unit. Please type a number: " and I can't get out of that loop. I don't even know what to type or what to do anymore so I decided to come here for a help.
I want to make with this code that until you type a number in weight input - you won't be allowed to go further, but after you type correctly - the program will continue to a unit input. Thx
The or operator does not work as you expect.
I suggest to replace it by:
while unit.upper() in "KL":
✅ Tested - I think you need to check the input for weight like this:
weight = input("Weight: ")
while not weight.isdigit():
print("Invalid unit. Please type a number... ")
weight= input("Weight: ")
Related
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
How do I check if a string represents a number (float or int)?
(39 answers)
Closed 8 months ago.
I can't figure out how to handle any exceptions for non-int or float inputs on the program below. Could you guys please point me in the right direction?
def GradeAverager(): #Creating the function of the grade averager
#User initiation input
response = input("\n\nWould you like to average your grades? Press Y for "
"Yes or N to exit: ")
#Defined controlled repsonse variables
y="Y"
n="N"
if response in ["y","Y"]: #If statement based on response (allows for
#different variatios of the inputs)
# User input the # of grades to average
numOfGrades = float(input("\n\nEnter number of grades to be averaged: "))
if type(numOfGrades) is not float:
#Handles non-int exception (NOT WORKING)
raise TypeError("Only Numbers please!")
#Defining the variables for the while statement
x=0
grades = 0
rounded_average = 0
while x < numOfGrades: # While loop to keep asking the user for grades
# based on "numOfGrades"
grades += float(input("\n Enter Grade: ")) # User input is taken
# and added to grades
if not type(grades) is not float:
#Handles non-int exception (NOT WORKING)
raise TypeError("Only Numbers please!")
x += 1 # keeps the loop repeating until it is no longer true
average = grades/numOfGrades # Takes the total of grades and divides it
# by numOfGrades to calculate average
rounded_average = round(average, 1) #Rounds the total to two one decimal
print("\n\nYour Grade Average is: " + str(rounded_average))
#If statements based on result scores
if average > 70:
print("\n You are passing but should study harder :|\n\n")
elif average > 80:
print("\n Good Job! you're getting there! :)\n\n")
elif average > 90:
print("\n Awesome Job! You are Acing this! XD\n\n")
else:
print("\n You need to go back and study! :(\n\n")
elif response in ["n","N"]: #If user answers "no", ends the program
print("\n\nGood Luck!\n\n")
else:
print("\n\nIncorrect Entry\n\n")
GradeAverager()
print("\n\n*****Welcome to the Grade Averager******") #Prints the title
GradeAverager() #Calls the function
You just have an extra "not" in the line:
if not type(grades) is not float:
Change it to:
if not (type(grades) is float):
But in general it's better to do it like this:
if isinstance(grades, float):
but if you dig deeper, you'll realize that grades will always be of type float, only if the value from the input is correct. You need to check this. Review this and decide how best to check if the input value is a valid representation of a number.
UPD:
And as rightly noted in the comments, almost the same with the numOfGrades variable
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
I'm putting together a small program for a friend that requires an input from the user, and depending on the input it does a certain function
Heres my code:
value = input ("Enter Number")
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
However, even entering 1 or 2, it always prints "hmmm".
I've tried everything including making a new function and passing the input into it and still it doesn't take. Any advice?
That's because you are taking input as a string not an integer.
Because of it your value is string and when it is compared with integer 1 or 2 it's coming false and the else condition gets satisfied.
Correct code:
value = int(input ("Enter Number"))
if value == 1:
print("You entered 1")
elif value == 2 :
print("You ented 2!")
else:
print("hmmm")
This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 1 year ago.
I'm trying to get this game to run ad infinitum until the user enters "q" or "quit". For some reason, this isn't quite working out with what I have. I initially tried to do this with two functions but failed miserably, so I consolidated for right now into one function to try to get it going. Still failing, but not as bad.
#Ex9: Guessing game. Generate a number between 1-9 and provide info whether its too high or low
import random
#print("Type q or quit to quit")
#guess = int(input("Please enter a number between 1 to 9: "))
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1 == "quit".lower() or "q".lower():
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
guessing_function()
Basically the issue is that the script just stops after one loop, rather than continue on without the user's input.... Not sure what I'm doing wrong.
Looks like you want to check if the user wanted to quit.
checking "quit".lower() is not correct. "quit" is already lower.
Also the or part of the if statement is incorrect. It will always be True.
Instead you want to check if lowercase of quit1 is either "quit" or "q".
You can do that by giving if quit1.lower() in ("quit","q"). By using in ("quit","q"), the if statement checks against the items in the tuple. This is a much better way to check when you have multiple values to check.
def guessing_function():
while True:
quit1 = print("Type q or quit to quit")
guess = int(input("Please enter a number between 1 to 9: "))
value = random.randint(1,9)
if quit1.lower() in ("quit","q"): #fixed this line
print("Ok we will stop")
break
elif guess > value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too high")
elif guess < value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is too low")
elif guess == value:
print(f"The computer generated {value}")
print(f"You picked {guess}. That value is correct!")
print doesn't prompt for user input(and returns None always), you should replace it with input instead.
The if is also wrong, it should be if quit1 == "quit" or quit1 == "q":. How to test multiple variables against a value? explains it better than I could.
This question already has answers here:
Python - User input data type
(3 answers)
Asking the user for input until they give a valid response
(22 answers)
Closed 4 years ago.
I am very new to programming and Python. To get started I'm working on a little game that will ask the user for some input and then do "something" with it. My problem is I've seem to account for if the user types in an int lower or high than my parameters BUT i can't seem to find a way to re-prompt the user if they type in anything but an int.
With my limited knowledge I thought that when using an if/elif/else statement if you didn't define what the if/elif is looking for than the else statement was there for everything else that you didn't account for?
Looking for some more insight on how to master this fundamental concept
Thank you in advance!
prompt = True
while prompt == True:
user_input = input("Please give me a number that is greater than 0 but less than 10 \n >")
if user_input > 0 and user_input <= 10:
print("Good job " + str(user_input) + " is a great number")
break
elif (user_input > 10):
print("Hey dummy " + str(user_input) + " is greater than 10")
elif (user_input <= 0):
print("Hey dummy " + str(user_input) + " is less than 0")
else:
print("I have no idea what you typed, try again!")
How about something like this?
a = -1
while a < 0 or a > 10:
try:
a = int(input("Enter a number between 0 and 10: "))
except ValueError:
continue
This will only allow the user to enter an int from 0 to 10, this will also remove the need to print those messages if the number is outside of this range, if you would like to keep those messages I could make adjustments and show you how to handle that as well
This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 4 years ago.
Why if i use OR at !!! section, does it break even if i type a number 1 - 9 in the guess input. And why do i not need to type BOTH 'q' and 'quit', because thats what i assume AND means... 'q' AND 'quit'...
import random
while True:
print("\nGuess a number between 1 and 9.")
guess = input("I guess: ")
if guess == 'q' !!!or!!! 'quit':
break
number = random.randrange(1, 10)
try:
if int(guess) < number:
print(f"You guess was too low. The number was {number}")
elif int(guess) > number:
print(f"Your guess was too high. The number was {number}")
elif int(guess) == number:
print(f"Your guess was exactly right! The number was {number}")
except ValueError:
print("Please only guess numbers!")
So with OR it doesn't work and with AND it does. This makes no sense to me. Why is this?
if guess == 'q' or 'quit':
This statement will not work because you are trying to use a string as a boolean. The OR doesn't assume you want the exact same thing to happen like before it, you have to fill the condition again.
if guess == 'q' or guess == 'quit':
This will work because you are now getting a boolean out of the right side instead of just trying to use a string.