Require user input until is correct [duplicate] - python-3.x

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
What is the best way of repeatedly asking for the user for correct input?
For example I'd like to continue checking if the a value is an int or not and when it is finally say ok you picked number.
I'm stuck here:
try:
a = int(input())
except:
print("incorrect pick a number and try again")
#Somewhere here
print("Ok thanks you finally picked a number")

The only exception you want to catch is the ValueError raised by int should it not be able to convert its argument to an integer. The try statement will be in a loop that you will explicitly break out of if you don't get an exception.
while True:
response = input()
try:
a = int(response)
except ValueError:
print("incorrect pick a number and try again")
else:
print("Ok thanks you finally picked a number")
break

if you want/must mantain this code, i think the unique way is using a loop.
while True:
try:
a = int(input('Insert a number:'))
print ('Your number is {}'.format(a))
break
except ValueError:
print("incorrect pick a number and try again")
So if the user inserts an integer, the code prints number and break the loop else repeats the request.
I hope it's useful for you!

You can do it like this:
a = None
while type(a) != int:
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
Essentially:
Create a variable with NoneType so when you first run the program it can access the while loop because the conditions meats.
Loop until the type of that variable is not int.
Request the user input and try to cast as integer, if it fails print an error and try again.
When the input is of integer type it exit the loop and print the final message.
You can use type() or isinstance() to check, but as suggested by #chepner avoid the usage of type because it simply returns the type of an object whereas, isinstance() returns true if the object argument is an instance of the classinfo argument, or of a (direct, indirect or virtual) subclass thereof.
To help you understand:
class foo:
pass
class bar(foo):
pass
isinstance(foo(), foo) # returns True
type(foo()) == foo # returns True
isinstance(bar(), foo) # returns True
type(bar()) == foo # returns False,and this probably won't be what you want.
In the case you want to use isinstance() the code will result as:
a = None
while not isinstance(a, int):
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
As pointed out by #L3viathan you can also do:
a = None
while a is None:
try:
a = int(input())
except:
print("incorrect pick a number and try again")
print("Ok thanks you finally picked a number")
In this case you loop until a get a value, that will be done only if the exception is not thrown.

while True:
try:
number=int(input("Enter a number: "))
except:
print("incorrect pick a number and try again")
else:
print("ok Thanks you finally picked a number ")
break

Related

How to make a try-parse in Python 3 that gives a message if string instead of int is entered and that gives the user the chance to try again?

I`m trying to make a try-parse in Python 3. And it workes as it should (if I enter an int it return what I entered and if I enter a string it gives an error) but I would like to return a message to the user insted of getting the error message from the computer if I enter a string instead of int. For exemple print("Error! Please enter a number") and then give the user the chance to try again. Anyone who have a tip on how I could do?
def try_parse_int(text):
try:
return int(text)
except:
return None
Thank you in advance!
You can easily do that by having the function call itself recursively :
def get_int():
print('Please, enter a number:')
val = input('=> ')
try:
return int(val)
except ValueError:
print("Error, that isn't a number!")
return get_int()

Function that to exit from other function

I wanted to create to a function which, when called in other function it exits the previous function based on the first function's input.
def function_2(checking):
if checking == 'cancel':
# I wanted to exit from the function_1
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
I wanted the code for the function_2 so that it exits from function_1, I know that I can put the if statement in function_1 itself but ill use this to check more than one in input in the same function or even in different function I cant put the if block everywhere it will look unorganized so i want to create a function and it will be convenient to check for more than one word like if cancel is entered i wanted to exit the programm if hello is entered i wanted to do something, to do something its ok but to exit from the current function with the help of other function code please :) if any doubts ask in the comment ill try to give you more info im using python 3.x.x on Windows8.
Why not simply:
def should_continue(checking):
if checking == 'cancel':
return False
return True
def function_1():
the_input = input("Enter the text: ")
if not should_continue(the_input):
return
This is the best solution I think.
Another alternative is to raise an Exception, for example:
def function_2(checking):
if checking == 'cancel':
raise KeyboardInterrupt
def function_1():
the_input = input("Enter the text: ")
function_2(the_input)
try:
function_1()
except KeyboardInterrupt:
print("cancelled by user")

How do I get my function to return something other than a reference?

When I run this function it returns None and a reference instead of the intended value.
I already am using "return" which is supposed to make the function return the intended value, but like I said it is still returning a reference.
def querydate():
querydate = int(input("Please enter a year between 2000 and 2017 for
processing injury data "))
numberchoice0 = querydate
while numberchoice0 is querydate:
try:
while int(numberchoice0)<2000:
print("oopsie, that year is before those for which this
query searches.")
quit()
while int(numberchoice0)>2017:
print("oopsie, that year is after those for which this
query searches.")
quit()
except ValueError:
print ('That was not an integer!')
affirmations = ('YES', 'Y')
answer = input("Do you want to continue? (Yes/Y/y):\n")
if answer.strip().upper() in affirmations:
continue
else:
return querydate()
print(querydate())
def verify():
verify = input("please enter 'yes' or 'no' ")
if verify == "no":
print("You should be more careful about inputting data!")
quit()
while verify != "yes":
print(verify, "is not an appropriate input. If you answered 'YES'
or 'Yes' please enter 'yes'")
continue
if verify == "yes":
print("Great! Let us continue")
verify()
I expect the output to be a number between 2000 and 2017, but when I print querydate() it returns "None", and when I reference querydate() with verify() it actually returns <function querydate at 0x000001F1DCFB9A60>
return does not make the function return the intended value, one has to explicitly specify it according to what one wants to return.
You wanted the output from 2000 to 2017 so you need to return the value that returns this.
def querydate():
qDate = int(input("Please enter a year between 2000 and 2017 for
processing injury data "))
numberchoice0 = qDate
while numberchoice0 is qDate:
try:
while int(numberchoice0)<2000:
print("oopsie, that year is before those for which this
query searches.")
quit()
while int(numberchoice0)>2017:
print("oopsie, that year is after those for which this
query searches.")
quit()
except ValueError:
print ('That was not an integer!')
affirmations = ('YES', 'Y')
answer = input("Do you want to continue? (Yes/Y/y):\n")
if answer.strip().upper() in affirmations:
continue
else:
return qDate #returning the integer instead of None
print(querydate())
def verify():
verify = input("please enter 'yes' or 'no' ")
if verify == "no":
print("You should be more careful about inputting data!")
quit()
while verify != "yes":
print(verify, "is not an appropriate input. If you answered 'YES'
or 'Yes' please enter 'yes'")
continue
if verify == "yes":
print("Great! Let us continue")
verify()
Also since you had returned explicitly nothing, referencing querydate() with verify() should return the address reference but if you had returned an integer like querydate or numberchoice0 then it returns a year from range 2000-2017.
Edit:
As far as your TypeError: 'int' object is not callable is concerned, it happens due to the naming of local variable and function name being same. So at first the identifier querydate refers to the function querydate() then it goes inside the function and now it refers to a variable querydate and no longer refers to the function when assigning of var querydate is encountered. So changing the name of one of the identifiers fixes the issue.

Defining function difficulties ["NameError: name 'number' is not defined"]

Okay, trying to make a simple game of Guessing Numbers but I can't find the mistake in this code. Still pretty new to python so probably the reason why but I can't figure out what is wrong with it.
import random
from time import sleep
def start():
print("Welcome To The Guessing Game \n Try to guess the number I'm thinking of \n Good luck!")
selectRandomNumber()
guessCheck(number, numberInput=1)
def restart():
print("Creating new number ...")
sleep(1)
print("OK")
selectRandomNumber()
guessCheck(number,numberInput=1)
def selectRandomNumber():
number = random.randint(0,1000)
tries = 0
return
def tryAgain():
while True:
try:
again = int(input("Do you want to play again? y/n:"))
except ValueError:
print("Couldn't understand what you tried to say")
continue
if again == "y" or "yes":
print("Awesome! Lets go")
restart()
elif again == 'n' or "no":
print("Goodbye!")
break
else:
print("Not a valid option")
continue
def guessCheck(number,numberInput=1):
while True:
try:
numberInput = int(input("What number do you think it is?: "))
except ValueError:
print("Couldn't understand that. Try again")
continue
if numberInput > number:
print("Too high")
tries += 1
continue
elif numberInput < number:
print("Too low")
tries += 1
continue
elif numberInput == number:
print("Congrats! You got my number")
tryAgain()
number = selectRandomNumber()
print(number)
start()
Every time I try to run the program I keep getting the same mistake.
It tells me:
Traceback (most recent call last):
File "python", line 60, in <module>
start()
File "python", line 8, in start
guessCheck(number, numberInput)
NameError: name 'number' is not defined
Don't quite understand what that means.
Some help would be appreciated. Thanks!
* UPDATE *
Was able to fix the part about defining the variable but now new problem happened where when I try to run
Same code as before but added
guessCheck(number,numberInput=1)
and also added the variable number at the end
number = selectRandomNumber()
print(number)
start()
when I run it I get this
None # this is from `print(number)` so instead of getting a number here I'm getting `None`
Welcome To The Guessing Game
Try to guess the number I'm thinking of
Good luck!
What number do you think it is?:
The Traceback is telling you this:
We got to start().
start() called guessCheck().
We tried to pass two pieces of information to guessCheck(): the variable names number and numberInput.
We don't have those variables defined yet! numberInput doesn't get defined until once we've already started guessCheck(), and number isn't actually defined anywhere.
As Manoj pointed out in the comments, you probably want number to hold the output of selectRandomNumber(). So, instead of just calling selectRandomNumber() in start(), try number = selectRandomNumber() instead.
You can add a print(number) on the line right after that to make sure number has a value assigned to it.
Now number has a value, going into your call to guessCheck(). That still leaves numberInput undefined though. You can set a default value for function arguments like this:
guessCheck(number, numberInput=1)
That way, when guessCheck is called but numberInput hasn't been defined yet, it will automatically give it the value 1 until you set it explicitly.
You may encounter other issues with your code the way it is. My advice would be to start really simply - build up your game from each individual piece, and only put the pieces together when you're sure you have each one working. That may seem slower, but trying to go too fast will cause misunderstandings like this one.

Notify user if wrong data type entered (Python 3)

How do I change this code so that the program can notify the user that he/she has entered a text instead of a number?
Enter_a_Number = int(input("Enter a Number: "))
if Enter_a_Number == str:
print("Only Numbers Allowed")
You need to explore the basics of error-handling.
See Python.org Tutorial - Handling Exceptions
while (True):
try:
Enter_a_Number = int(input("Enter a Number: "))
break
except ValueError:
print("Invalid number")
print(Enter_a_Number)
In this specific case, the int() function will 'throw' a ValueError if it can not convert the string to an integer. You can decide what to do when that happens.

Resources