Crozear
Crozear

Reputation: 35

Why if-then statement isn't working?

This is the code that I made when I tried making an if-then statement but, it always defaults to else. Also i just started trying to code from online tutorials today.

print('yes or no?')

if sys.stdin.readline() == 'yes' : 
    print('Yay')
else : 
    print('Aww')

This is what happens:

Console:yes or no?

Me:yes

Console:Aww

I've been looking stuff up for half an hour and can't figure out how to fix this please help

Upvotes: 2

Views: 77

Answers (3)

Crozear
Crozear

Reputation: 35

Ok I used user_input and input instead of sys.stdin.readline() on strings and i used it in a basic calculator here it is :

import random
import sys
import os


user_input = input("Would you like to add or subtract?")
if user_input == 'add' :
    print('What would you like to add?')
    plus1 = float(sys.stdin.readline())
    print('Ok so %.1f plus what?' % (float(plus1)))
    plus2 = float(sys.stdin.readline())
    print('%.1f plus %.1f equals %.1f' % (float(plus1),float(plus2), float(plus1+plus2)))
elif user_input == 'subtract' :
    print('What would you like to subtract?')
    minus1 = float(sys.stdin.readline())
    print('Ok so %.1f minus what?' % (float(minus1)))
    minus2 = float(sys.stdin.readline())
    print('%.1f minus %.1f equals %.1f' % (float(minus1), float(minus2), float(minus1 - minus2)))
    else :
        print('That is not one of the above options')

Thanks alot guys!

Upvotes: 0

DevLounge
DevLounge

Reputation: 8437

sys.stdin.readline() reads a line which ends with '\n' (when you hit "enter").

So you need to remove this '\n' from the captured input using strip().

print('yes or no?')

if sys.stdin.readline().strip() == 'yes' : 
    print('Yay')
else : 
    print('Aww')

I tried to explain and solve your specific problem but you could of course use raw_input() or input() (PY3) as mentioned in the other answer.

Upvotes: 2

Mark Schultz-Wu
Mark Schultz-Wu

Reputation: 374

In python, getting the input of a user's string can be done via input() (or in python 2.7, use raw_input()).

If you include the code:

user_input = raw_input("yes or no?")

This will first print the string "yes or no?", then wait for user input (through stdin), then save it as a string named user_input.

So, you change your code to be:

user_input = raw_input("yes or no?")
if user_input == "yes":
    print("Yay")
else:
    print("Aww")

this should have the desired effect.

Upvotes: 1

Related Questions