-1

import sys

super_heroes = {'Iron Man' : 'Tony Stark',
            'Superman' : 'Clark Kent',
            'Batman' : 'Bruce Wayne',
            }

print ('Who is your favorite Superhero?')

name = sys.stdin.readline()

print ('Do you know that his real name is', super_heroes.get(name))

I'm doing a simple code here that should read an input in a dictionary and print it out after a string of letters, but when ran it prints out

" Who is your favorite Superhero?

Iron Man

Do you know that his real name is None "

Even Though the input is in my dictionary.

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44

3 Answers3

2

Your input is having a newline at the end of the line.

I have tried it online REPL. Check it

try following to resolve it.

name = sys.stdin.readline().strip()

After stripping Check here

Ratul Sharker
  • 7,484
  • 4
  • 35
  • 44
1

sys.stdin.readline() returns the input value including the newline character, which is not what you expect. You should replace sys.stdin.readline() with input() or raw_input(), which are really more pythonic ways to get input values from the user, without including the newline character. raw_input() is preferable to ensure that the returned value is of string type.

To go a little bit further, you can then add a test if name in super_heroes: to perform specific actions when the favorite superhero name is not in your dictionary (instead of printing None). Here is an example:

super_heroes = {'Iron Man' : 'Tony Stark',
                'Superman' : 'Clark Kent',
                'Batman' : 'Bruce Wayne',
               }

print ('Who is your favorite Superhero?')

name = raw_input()

if name in super_heroes:
    print ('Do you know that his real name is', super_heroes[name], '?')
else:
    print ('I do not know this superhero...')
Laurent H.
  • 6,316
  • 1
  • 18
  • 40
0

sys.std.readline() appends a line break at the end of user input you may want to replace it before getting your Super Hero:

name = name.replace('\n','')
Rehan Azher
  • 1,340
  • 1
  • 9
  • 17