What I'm trying to do is ask users for two inputs, if one of the inputs is less than zero or if the input is some string then ask for the inputs again. The only valid input are numbers >=0. So you can't have something like -1 or cat as inputs.
Attempt 1:
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
while int(number_of_books) < 0 or int(number_of_chairs) < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = input("What is the number of books in the game?: ")
number_of_chairs = input("What is the number of chairs in the game?: ")
But from this I realized that the input are always strings so it will ask for input again.
Attempt 2:
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
while number_of_books < 0 or number_of_chairs < 0 or isinstance(number_of_books, str) or isinstance(number_of_chairs, str):
print("Input cannot be less than 0 or cannot be some string.")
number_of_books = int(input("What is the number of books in the game?: "))
number_of_chairs = int(input("What is the number of chairs in the game?: "))
But with this one I realized that you cannot do int('some string')
So I'm wondering if there is a way to do this or is this something not possible?
You should use a while loop for each input, so only the invalid one is asked again. By using while True, you ask for input once, and break once it's valid. Try to convert to int, which raises ValueError if that cannot be done. Exceptions cause the custom error to be printed, and the loop restarted.
while True:
books_input = input("What is the number of books in the game?: ")
try:
number_of_books = int(books_input)
if number_of_books < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
You'd need to do this for each input (maybe there are more than two?), so it makes sense to create a function to do the heavy lifting.
def non_negative_input(message):
while True:
input_string = input(message)
try:
input_int = int(books_input)
if input_int < 0:
raise ValueError
except ValueError:
print('Input must be an integer and cannot be less than zero')
else:
break
return input_int
Calling it:
non_negative_input("What is the number of books in the game?: ")
The solution is to coerce the answer to int() and catch any exceptions, for example:
while True:
try:
number_of_books = int(raw_input('Enter number of books:'))
if number_of_books < 0:
raise ValueError('must be greater than zero')
except ValueError, exc:
print("ERROR: %s" % str(exc))
continue
break
Probably you should put this in a function, and make the prompt a variable (to allow re-use).
Use the try except method
while stringval = input("What is the number you want to enter"):
try:
intval = int(stringval)
if intval > -1:
break
except ValueError:
print 'Invalid answer, try again'
# Process intval now
Related
I am creating a program to find the LCM of two numbers. I want to return 1 when no input is given, but instead I end up with a ValueError as no integer input is given. I know that you can use Try and Except to ignore the ValueError, but I'm not exactly sure how you use them. This is my complete code:
def lcm(number1,number2):
if number1>number2:
largernumber= number1
else:
largernumber=number2
multiple=largernumber
while True:
if largernumber%number1==0 and largernumber%number2==0:
print("The LCM is", largernumber)
break
else:
largernumber=largernumber+multiple
number1=int(input("Please enter number 1: "))
number2=int(input("Please enter number 2: "))
if number1==0 or number2==0:
print("0")
else:
lcm(number1,number2)
You can implement it like this
def lcm(number1,number2):
if number1>number2:
largernumber= number1
else:
largernumber=number2
multiple=largernumber
while True:
if largernumber%number1==0 and largernumber%number2==0:
print("The LCM is", largernumber)
break
else:
largernumber=largernumber+multiple
try:
number1=int(input("Please enter number 1: "))
number2=int(input("Please enter number 2: "))
if number1==0 or number2==0:
print("0")
else:
lcm(number1,number2)
except:
print(1)
I don't want to make the user be able to enter anything other than numbers as the input for the "number" variable, except for the string "done".
Is it possible to somehow make an exception to the rules of the try-except block, and make the user be able to write "done" to break the while loop, while still keeping the current functionality? Or should I just try something different to make that work?
while number != "done":
try:
number = float(input("Enter a number: ")) #The user should be able to write "done" here as well
except ValueError:
print("not a number!")
continue
Separate the two parts : ask the user and verify if it is done, then parse it in a try/except
number = None
while True:
number = input("Enter a number: ")
if number == "done":
break
try:
number = float(number)
except ValueError:
print("not a number!")
continue
print("Nice number", number)
Instead of trying to make exceptions to the rules, you can instead do something like,
while True:
try:
number=input("Enter a number: ")
number=float(number)
except:
if number=="done":
break
else:
print("Not a number")
Check if the error message contains 'done':
while True:
try:
number = float(input("Enter a number: "))
except ValueError as e:
if "'done'" in str(e):
break
print("not a number!")
continue
also in this case continue is not necessary here (for this example at least) so it can be removed
Maybe convert the number to float afterwards. You can check if number is not equal to done,then convert the number to float
number = 0
while number != "done":
try:
number = input("Enter a number: ") #The user should be able to write "done" here as well
if number=="done":
continue
else:
number = float(number )
except ValueError:
print("not a number!")
continue
There are various ways to approach this situation.
First one that came across my mind is by doing:
while True:
user_input = input("Enter a number: ")
if user_input == "done":
break
else:
try:
number = float(user_input)
except ValueError:
print("not a number!")
continue
while True:
try:
user_input = input("Enter a number: ")
if user_input == "done":
break
number = float(user_input)
except ValueError:
print("not a number!")
continue
You can cast the input to float after checking if the input is 'done'
I am creating a program where you will have to loop through multiple questions each with a condition. If user input for the question does not meet the requirement, it will print out the error and prompt user to re-enter. Else, it will continue with the next question. And not only prompting user to re-enter after all 3 questions are answered.
This it the output I am getting now:
while True:
amount = int(input("Enter amount: "))
rate = int(input("Enter rate: "))
year = float(input("Enter year: "))
if amount<4000:
print("Invalid amount")
continue
elif rate<0:
print("invalid rate")
continue
elif year<0:
print("invalid year")
break
Output:
Enter amount: 1
Enter rate: 3
Enter year: 4
Invalid amount
Enter amount:
Expected output:
Enter amount: 4
Invalid amount
Enter amount:
It's not very clear what are you trying to achieve, but I think you want this:
while True:
amount = int(input("Enter amount: "))
if amount < 4000:
print("Invalid amount")
continue
break
while True:
rate = int(input("Enter rate: "))
if rate < 0:
print("invalid rate")
continue
break
while True:
year = float(input("Enter year: "))
if year < 0:
print("invalid year")
continue
break
This will only ask to re-enter the invalid values.
Another more reusable method would be:
def loop_user_input(input_name, meets_condition):
while True:
value = int(input(f"Enter {input_name}: "))
if not meets_condition(value):
print(f"Invalid {input_name}")
else:
return value
loop_user_input('amount', lambda val: val < 4000)
loop_user_input('rate', lambda val: val < 0)
loop_user_input('year', lambda val: val < 0)
Here you have a loop that only returns when the input value meets the condition, that you pass in. I recommend you check your conditions, because a year normally shouldn't be negative (rate < 0). Also your solution throws an exception, if the user enters something else then an int. Maybe add a try-catch to your solution:
try:
value = int(input(f"Enter {input_name}: "))
except:
print(f"Invalid {input_name}")
continue
I'm making a simple game that shows up "What number do you like" and if u write a number(for example "77") it should show up an EXCEPT but it doesn't
why?
your_name = input("What's your name: ")
this_year = 2019
your_age = int(input("How old are you: "))
year_born = this_year - your_age
print("Hello",your_name,".You are",your_age,"years old","\n\n")
year_when_you_were_born = print("That means that you were
born",year_born)
hundred_year = year_born + 100
print("And that means that you are gonna be 100 years old at the year
of",hundred_year)
number = int(input("What number do you like: "))
try:
question = str(input("Do you wanna print your name that many times:
"))
except ValueError:
print("I don't get it,type words not numbers")
else:
if question == "yes":
word = your_name * question
print(word)
number = int(input("What number do you like: ")) takes the input and converts it to an int. So 77 is fine. However, letters can not be converted to a int, so that will throw a ValueError. For that the line needs to be inside the try block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
Note that question = str(input("Do you wanna print your name that many times: ")) will not throw a ValueError, because both letters and numbers can be converted to a string. So you don't have to put it in the 'try'-block, it is better placed in the 'else' block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
else:
question = str(input("Do you wanna print your name that many times: "))
if question == "yes":
word = your_name * question
print(word)
So I'm kind of very beginner to programming and just learning yet the basics. Now I would like to have my python program to ask the user to give a number and keep asking with a loop if string or something else is given instead.
So this is the best I came out with:
value = False
while value == False:
a = input("Give a number: ")
b = 0
c = b
try:
int(a)
except ValueError:
print("No way")
b += 1
if c == b:
value = True
So is there easier and better way to do this?
You can use this:
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
or this:
while True:
a = input("Give a number: ")
if a.isdigit():
break
print("No way")
while True:
try:
a = int(input("Give a number: "))
break
except ValueError:
print("No way")
continue
This will continue to prompt the user for an integer till they give one.
value = True
while value == True:
a = input("Give a number: ")
try:
int(a)
except ValueError:
print("No way")
continue
print("Yay a Number:", a)
value = False
Is this what you need?