1

Im new to this so Im sorry if this isn't the best way to ask the question...

here is the code -

import sys

print("What is ur name?")
name = sys.stdin.readline()

answer = "jack"

if name is answer :
    print("ur awesome")
exit();

right now when I run it in cmd I don't get anything printed even though I input - jack? thank you in advance

4
  • 2
    Use == instead of is. Commented Sep 28, 2016 at 0:31
  • Be careful with sys.stdin.readline(). It will preserve newline. So if you enter jack, it will actually be jack\n. So, answer == "jack" will be False when it should really be true. You are better off using input() instead. Commented Sep 28, 2016 at 0:34
  • With sys.stdin.readline(), you want answer==name.strip() otherwise use input() Commented Sep 28, 2016 at 0:34
  • Also see here and here. Commented Sep 28, 2016 at 1:59

2 Answers 2

6

Firstly, replace is with ==. is checks whether the two underlying strings are the same entity (in memory) whereas == just wants to check if they have the same value.

Because the source of "jack" is coming from two sources (one from the user, another hard-coded by you) they are two seperate objects.

As @dawg mentioned you also have to use the .strip() to get rid of the newline when using sys.stdin.readline() for input. The best way to read input is to use the input() method in python3, or raw_input() in python2.

name = input('What is your name?\n')

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

2 Comments

You need .strip() since the sys.stdin.readline() includes the \n
I like the explanation, but offering a solution would make the answer even better :)
4

Use == for string comparison. Also, readline() will include the newline at the end of the string. You can strip it with e.g.

name = name.strip()

Alternatively, you can use raw_input() (input() in python 3) instead of readline(), as it will not include the newline to begin with.

name = raw_input("What is your name?\n")

It's helpful to be able to print a string to see if it has any extra whitespace, e.g.

print("name: [%s]\n" % name)

1 Comment

Great, but please add reference to input()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.