I\'m new to python.
I want the program to ask
\"is Johnny hungry? True or false?\"
user inputs True
then print is
def get_bool(prompt):
while True:
try:
return {"si": True, "no": False}[input(prompt).lower()]
except KeyError:
print ("Invalido ingresa por favor si o no!")
respuesta = get_bool("Quieres correr este programa: si o no")
if (respuesta == True):
x = 0
else:
x = 2
johnnyHungry = input("Is johnny hungry ")
if johnnyHungry == "True":
...
I expect that you can take it from there?
I hope this code works for you. Because I already tried this code and it worked fine.
johnnyHungry = str(input("Is johnny hungry "))
def checking(x):
return 'yes' == True
return 'no' == False
if checking(johnnyHungry) == True:
print("Johnny needs to eat.")
elif checking(johnnyHungry) == False:
print("Johnny is full.")
I'm sorry if it's long, I'm new to programming either.
you can use a simple helper that will force whatever input you want
def get_bool(prompt):
while True:
try:
return {"true":True,"false":False}[input(prompt).lower()]
except KeyError:
print "Invalid input please enter True or False!"
print get_bool("Is Jonny Hungry?")
you can apply this to anything
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print "Thats not an integer silly!"
You can turn something into True
or False
using bool
:
>>> bool(0)
False
>>> bool("True")
True
>>> bool("")
False
But there is a problem with a user entering "True" or "False" and assuming we can turn that string
into a bool:
>>> bool("False")
True
This is because a string
is considered truthy if it's not empty.
Typically, what we do instead is allow a user to enter a certain subset of possible inputs and then we tell the user that only these values are allowed if the user enters something else:
user_answer = input("Is johnny hungry ").lower().strip()
if user_answer == "true":
# do something
elif user_answer == "false":
# do something else
else:
print("Error: Answer must be True or False")
You could just try bool(input("...")) but you would get into trouble if the user doesn't input a bool. You could just wrap it in a try statement.