1

I am new at Python and need a little help. I am trying to use the next command in order to get user input from screen: sys.stdin.readline()

All is fine when I want to print something but when I am trying to combine an if else statement it seems that the user input is ignoring the case sensitive string that I wrote in the if == and it always return the else even when I writing the input 'Sam'

I want to make a simple task like this one:

print("What is your name ?")

name = sys.stdin.readline()

print("Hello", name)

if name == 'Sam' :
    print ('You are in our group')
else :
    print('You are not in our group')

What should I do in the sys.stdin.readline() will acknowledge the if == argument ?

Thank you for you Help

3
  • You can use the raw_input() function instead of sys.stdin.readline(), as it ignores the end of line character ('\n') Commented Sep 28, 2016 at 11:35
  • 2
    @Jalo, looks like they're using python3 so it would be input('Prompt: '). Commented Sep 28, 2016 at 11:35
  • 1
    Alright @Holloway, I did not notice Commented Sep 28, 2016 at 11:37

2 Answers 2

3

The line will include the end of line character '\n' (docs). So it's never equal to 'Sam' (except possibly at the end of the file).

Maybe use name = name.strip() to remove it and any extra whitespace characters.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @RemcoGerlich ! Now it's recognize Sam :)
1

In reference to the main post:

I used sys.stdin.readline() and input() in the same code. Worked both times. Below are the codes:

import sys
print('how much was your meal')
price = int(input())
print('how much would you like to tip in percentage')
tip = int(input())
tipamount = price * (tip/100)
print('your tip amount is %s' %tipamount + 'dollars')

Second code:

#import sys
#price = int(sys.stdin.readline())
#print('how much would you like to tip in percentage')
#tip = int(sys.stdin.readline())
#tipamount = price * (tip/100)
#print('your tip amount is %s' %tipamount + 'dollars') 

But when I used sys.stdin.readline in the following code, it didn't work. Instead input() worked. Could someone please explain why sys.stdin.readline worked in the first code but not in this one?

import sys
print('are you looking to study digital media in australia?')
answer = str(sys.stdin.read())
if answer == 'yes':
print('Deakin University has one of the best Digital Science Program!')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.