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?
Related
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 would like to check if my input is digit and in range(1,3) at the same time and repeat input till I got satisfying answer.
Right now I do this in this way, but the code is quite not clean and easy... Is there a better way to do this?
Maybe with while loop?
def get_main_menu_choice():
ask = True
while ask:
try:
number = int(input('Chose an option from menu: '))
while number not in range(1, 3):
number = int(input('Please pick a number from the list: '))
ask = False
except: # just catch the exceptions you know!
print('Enter a number from the list')
return number
Will be grateful for help.
I guess the most clean way of doing this would be to remove the double loops. But if you want both looping and error handling, you'll end up with somewhat convoluted code no matter what. I'd personally go for:
def get_main_menu_choice():
while True:
try:
number = int(input('Chose an option from menu: '))
if 0 < number < 3:
return number
except (ValueError, TypeError):
pass
def user_number():
# variable initial
number = 'Wrong'
range1 = range(0,10)
within_range = False
while number.isdigit() == False or within_range == False:
number = input("Please enter a number (0-10): ")
# Digit check
if number.isdigit() == False:
print("Sorry that is not a digit!")
# Range check
if number.isdigit() == True:
if int(number) in range1:
within_range = True
else:
within_range = False
return int(number)
print(user_number())
``
see if this works
def get_main_menu_choice():
while True:
try:
number = int(input("choose an option from the menu: "))
if number not in range(1,3):
number = int(input("please pick a number from list: "))
except IndexError:
number = int(input("Enter a number from the list"))
return number
If your integer number is between 1 and 2 (or it is in range(1,3)) it already means it is a digit!
while not (number in range(1, 3)):
which I would simplify to:
while number < 1 or number > 2:
or
while not 0 < number < 3:
A simplified version of your code has try-except around the int(input()) only:
def get_main_menu_choice():
number = 0
while number not in range(1, 3):
try:
number = int(input('Please pick a number from the list: '))
except: # just catch the exceptions you know!
continue # or print a message such as print("Bad choice. Try again...")
return number
If you need to do validation against non-numbers as well you'll have to add a few steps:
def get_main_menu_choice(choices):
while True:
try:
number = int(input('Chose an option from menu: '))
if number in choices:
return number
else:
raise ValueError
except (TypeError, ValueError):
print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))
Then you can reuse it for any menu by passing a list of valid choices, e.g. get_main_menu_choice([1, 2]) or get_main_menu_choice(list(range(1, 3))).
I would write it like this:
def get_main_menu_choice(prompt=None, start=1, end=3):
"""Returns a menu option.
Args:
prompt (str): the prompt to display to the user
start (int): the first menu item
end (int): the last menu item
Returns:
int: the menu option selected
"""
prompt = prompt or 'Chose an option from menu: '
ask = True
while ask is True:
number = input(prompt)
ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
return int(number)
I need help validating the input from the (random) questions I ask to make sure that the users input is only a number, rather than letters or any other random character. Also along with the validation there should be an error message notifying the user theyve done something wrong as well as repeat their chance to do the question.
So far the section of my code I need validating is the following:
def quiz():
x = random.randint(1, 10)
y = random.randint(1, 10)
ops = {'+': operator.add,'-': operator.sub,'*': operator.mul}
keys = list(ops.keys())
opt = random.choice(keys)
operation = ops[opt]
answer = operation(x, y)
print ("\nWhat is {} {} {}?".format(x, opt, y))
userAnswer= int(input("\nYour answer: "))
if userAnswer != answer: #validate users answer to correct answer
print ("\nIncorrect. The right answer is",answer,"")
print ("\n============= 8 =============")
return False
else:
print("\nCorrect!")
print ("\n============= 8 =============")
return True
for i in range(questions): #ask 10 questions
if quiz():
score +=1
print("\n{}: You got {}/{} questions correct.".format(name, score, questions,))
Thanks in advance!
Use try...except:
while True:
userAnswer = input("\nYour answer: ")
try:
val = float(userAnswer)
break
except ValueError:
print("That's not a number!")
If you want only integers, use int instead of float.
in Single line :
assert input('Enter Number: ').isdigit()
You may use function validate integer input:
def int_validation(user_Input):
try:
val = int(user_Input)
except ValueError:
print(user_Input,' not an integer!')
It would be good to make a function to accept your input. This can then keep prompting the user until a valid number is entered:
def get_number(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("Please enter a number")
You can then change your input line as follows:
userAnswer = get_number("\nYour answer: ")
My code distinguishes whether the input is valid or not. It's not supposed to accept zero or words. If the user plugs zero in, it works and says "anything but zero", "try again" BUT when it asks again, it accepts anything. What do I do to make it continue to ask until there is a valid input??
So far I got:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Please help! Thank you all!
You need to use a loop:
while True:
A = raw_input('Enter A:')
try:
A = float(A)
except ValueError:
print "enter a float!"
else:
if A == 0:
print "Enter not 0"
else:
break
The simplest approach is use a while loop and to move all the logic inside the try breaking if the cast is successful and not equal to 0:
while True:
try:
A = float(raw_input('Enter A: '))
if A != 0:
break
print "anything but zero"
except ValueError:
print "HEY! that is not a float!"
If you actually only want integers you should be casting to int not float.
Use a while loop:
valid = false
while not valid:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
valid = true
except ValueError:
print "HEY! that is not a float!"
A = raw_input("Try again")
Hope this helps :)
while 1==1:
A = raw_input('Enter A: ')
try:
A = float(A)
if A == 0:
print "anything but zero"
A = raw_input("Try again")
else:
#valid input
break
except ValueError:
print "HEY! that is not a float!"
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
flag = True
while flag != False:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
flag = True
break
else:
print "Error, only numbers are allowed"
I do not see the problem.
Why doesn't it enter a loop?
Doesn't print anything, just gets stuck.
flag = False is not required here:
else:
print "Error, only numbers are allowed"
flag = False <--- remove this
Simply use:
while True:
numInput = raw_input("Enter your first number: ")
if is_number(numInput):
numInput = float(numInput)
break
else:
print "Error, only numbers are allowed"
demo:
Enter your first number: foo
Error, only numbers are allowed
Enter your first number: bar
Error, only numbers are allowed
Enter your first number: 123
try this:
while True:
numInput = raw_input("Enter your first number: ")
try:
numInput = float(numInput)
break
except:
print "Error, only numbers are allowed"