Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating if/else statements dependent on user input

I'm trying to create a simple script that will will ask a question to which the user will input an answer (Or a prompt with selectable answers could appear?), and the program would output a response based on the input.

For example, if I were to say

prompt1=input('Can I make this stupid thing work?')

I would have something along the lines of

if prompt1='yes': 
    print('Hooray, I can!')

else prompt1='No':
    print('Well I did anyway!')

elif prompt1=#an answer that wouldn't be yes or no
    #repeat prompt1

I'm probably going about this the wrong way. Please be as descriptive as possible as this is a learning exercise for me. Thanks in advance!

like image 941
Shawn R. Avatar asked Oct 21 '25 00:10

Shawn R.


1 Answers

You are pretty close. Read a good tutorial :)

#!python3
while True:
    prompt1=input('Can I make this stupid thing work?').lower()

    if prompt1 == 'yes':
       print('Hooray, I can!')
    elif prompt1 == 'no':
       print('Well I did anyway!')
    else:
       print('Huh?') #an answer that wouldn't be yes or no
  • while True will loop the program forever.
  • Use == to test for equality.
  • Use .lower() to make it easier to test for answers regardless of case.
  • if/elif/elif/.../else is the correct sequence for testing.

Here's a Python 2 version:

#!python2
while True:
    prompt1=raw_input('Can I make this stupid thing work?').lower()

    if prompt1 == 'yes':
       print 'Hooray, I can!'
    elif prompt1 == 'no':
       print 'Well I did anyway!'
    else:
       print 'Huh?' #an answer that wouldn't be yes or no
  • raw_input is used instead of input. input in Python 2 will tries to interpret the input as Python code.
  • print is a statement instead of a function. Don't use () with it.
like image 89
Mark Tolonen Avatar answered Oct 23 '25 15:10

Mark Tolonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!