Boolean variable does not get updated - python-3.x

I've got a simple piece of code that asks for user input and returns a boolean variable. In case the input was unacceptable, the user has the chance to correct herself. But the boolean gets properly updated only when the else part of the if-statement is not invoked. When it is, the function always returns False.
def tryAgain():
bol = False
print('Do you want to try again? (Y/N)')
answer = input('> ').lower()
if (answer == 'y' or answer == 'n'):
if answer == 'y':
bol = True
else:
print('Your answer could not be parsed')
tryAgain()
return bol

That line of
tryAgain()
should be
bol = tryAgain()
And it will work. :-)
Oops... as per what Saeed said... Hadnt read his comment before replying.

Related

Require user input until is correct [duplicate]

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

Python 3 How to Ask user for specific input and reject invalid inputs

I have a question on how to check a user's input and make sure they are returning a specific string. Currently, the function when called will ask the user for their input. However, if they choose a string that is not part of the function, the else statement will execute and continue the code. I am trying to figure out how to loop this function, until a user inputs one of the strings that the function is looking for. Can anyone help me with this? I am new to python and would appreciate any help.
def dwarf_class_definer(dwarf_class):
if dwarf_class == "Thane":
print("'Ahhh Nobility'")
elif dwarf_class == "Mekanik":
print("'Interesting a Mechanic'")
elif dwarf_class == "Ancestrite":
print("'A spiritualist. I see...'")
elif dwarf_class == "Prisoner":
print("'Never met a gen-u-ine 'Last chancer.'")
elif dwarf_class == "Civilian":
print("'ehhh a civilian? Wut you doing here?'")
else:
print("You aren't choosing a valid class.")
dwarf_class = input("Which Class will you choose?: ")
dwarf_class_definer(dwarf_class)
A while loop will keep going until you tell it not to anymore. You can see when an expected value is supplied, the break command will terminate the while loop. A dictionary can also make your code a lot cleaner and easier to maintain compared to a bunch of if statements.
dwarf_classes = {
"Thane": "'Ahhh Nobility'",
"Mekanik": "'Interesting a Mechanic'",
"Ancestrite": "'A spiritualist. I see...'",
"Prisoner": "'Never met a gen-u-ine 'Last chancer.'",
"Civilian": "'ehhh a civilian? Wut you doing here?'",
}
while True:
dwarf_class = input("Which Class will you choose?: ")
if dwarf_class in dwarf_classes.keys():
print(dwarf_classes[dwarf_class])
break
print("You aren't choosing a valid class.")
example:
$ python3 so.py
Which Class will you choose?: Python!
You aren't choosing a valid class.
Which Class will you choose?: Prisoner
'Never met a gen-u-ine 'Last chancer.'

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.

how do I break while loop by raw_input()? python 3

I need some help understanding the differences between the following. In the first example, I want the loop to break when the user inputs False:
true = True
while true:
print("Not broken")
true = input("to break loop enter 'False' ")
There was a question asked at:
how do I break infinite while loop with user input
Which gives this solution:
true= True
while true:
print("Not broken")
true = input("to break loop enter 'n' ")
if true == "n":
break
else:
continue
And I don't understand why the first method doesn't work and the second does??? Why doesn't python take the input as if someone was changing the script and change the variable "true"? Whats going on behind the scenes?
Any help would be appreciated. Thanks in advance :)
The while statement is conditional, and the user entering the String "False" will still resolve to a True outcome.
For an idea of what Python considers True and False, checkout this link: https://realpython.com/python-conditional-statements/
Building on this answer Converting from a string to boolean in Python?, the best way to check is:
true = True
while true is not 'False':
print("Not broken")
true = input("to break loop enter 'False' ")

Scopes within while loops

from random import randint
isRunning =True
while isRunning:
dice1 = randint(1,7)
dice2 = randint(1,7)
print("The first die landed on ℅d and the second landed on ℅d." ℅ (dice1,dice2))
user_input = input("Contiue? Yes or No?\n>")
if user_input == "Yes" or "yes":
print("="*16)
elif user_input == "No" or "no":
isRunning = False
I feel like I'm making such a simple mistake and when I decided to look into global variables and what not it still doesn't help. Could anyone explain why the while loop doesn't terminate, although the variable was set to false.
if user_input== "Yes" or "yes" should be
if user_input== "Yes" or user_input =="yes", alternatively it's equivalent to if any(user_input==keyword for keyword in["Yes", "yes"]):
your original if clause is splitting to
if user_input=="Yes" or if "yes" and if "yes" always true, therefore your if-elseif clause always go to if clause.

Resources