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

comander derp
  • 63
  • 1
  • 9
  • 2
    Use `==` instead of `is`. – StardustGogeta Sep 28 '16 at 00: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. – idjaw Sep 28 '16 at 00:34
  • With `sys.stdin.readline()`, you want `answer==name.strip()` otherwise use `input()` – dawg Sep 28 '16 at 00:34
  • Also see [here](http://stackoverflow.com/questions/2988017/string-comparison-in-python-is-vs) and [here](http://stackoverflow.com/questions/3345202/python-getting-user-input). – TigerhawkT3 Sep 28 '16 at 01:59

2 Answers2

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')

Tom Sitter
  • 1,082
  • 1
  • 10
  • 23
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)
dwks
  • 602
  • 5
  • 10