Reputation: 47
I am trying to learn python, and currently I am trying to build a ticket machine that in this case simulates a payment step. because it is a simulation for demonstration purposes I ask the user through an Boolean input to enter True or false. for some reason when I enter False, it will still be interpreted as True. Below is my code:
def payment():
global tries
print("Payment can be done by PIN. Please follow the instructions on the payment terminal\n")
time.sleep(2)
payment_succeeded = bool(input("for demonstration purpose: did the payment succeed?"))
if payment_succeeded is True:
print("Payment succeeded.\n")
trip_time()
time.sleep(1)
elif tries < 3:
tries +=1
print("Payment Failed. please try again\n")
time.sleep(0.5)
payment()
else:
print("Payment has failed. Stopping purchase.\n")
the global "tries" variable has a value of 1 by default
Upvotes: 0
Views: 5920
Reputation: 1121296
bool()
does not translate 'False'
to False
. It only looks at the truth value of the string, and only the empty string is considered false.
So, entering anything other than an empty string is considered true:
>>> bool(input(''))
Howdy!
True
>>> bool(input('')) # Hitting enter results in an empty string
False
You'd be better off testing for certain strings:
response = input("for demonstration purpose: did the payment succeed?")
payment_succeeded = response.lower() in ('y', 'yes', 'it did', 'true', 'you betcha')
if payment_succeeded: # no need for "is True" here
Now typing anything other than one of the expected strings will result in payment_succeeded
being set to False
.
You probably want to limit that a little more by providing expected input, and re-ask if that's not given:
while True:
response = input("for demonstration purpose: did the payment succeed, yes or no?").lower()
if response in ('y', 'yes', 'n', 'no'):
payment_succeeded = response in ('y', 'yes')
break
print('Sorry, I did not understand that input, please try again.')
Upvotes: 3