Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have user true/false input in python?

Tags:

python

I'm new to python.

I want the program to ask

"is Johnny hungry? True or false?"

user inputs True then print is "Johnny needs to eat."

user inputs false then print "Johnny is full."

I know to add an int I type in

johnnyHungry = int(input("Is johnny hungry ")) 

but I want them to enter True/false, not an int.

like image 251
Matt Avatar asked Nov 28 '22 23:11

Matt


1 Answers

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!")
like image 163
Joran Beasley Avatar answered Dec 05 '22 03:12

Joran Beasley