What did I do wrong - python-3.x

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.

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

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

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

Related

How do I search for a substring in a string then find the character before the substring in python

I am making a small project in python that lets you make notes then read them by using specific arguments. I attempted to make an if statement to check if the string has a comma in it, and if it does, than my python file should find the comma then find the character right below that comma and turn it into an integer so it can read out the notes the user created in a specific user-defined range.
If that didn't make sense then basically all I am saying is that I want to find out what line/bit of code is causing this to not work and return nothing even though notes.txt has content.
Here is what I have in my python file:
if "," not in no_cs: # no_cs is the string I am searching through
user_out = int(no_cs[6:len(no_cs) - 1])
notes = open("notes.txt", "r") # notes.txt is the file that stores all the notes the user makes
notes_lines = notes.read().split("\n") # this is suppose to split all the notes into a list
try:
print(notes_lines[user_out])
except IndexError:
print("That line does not exist.")
notes.close()
elif "," in no_cs:
user_out_1 = int(no_cs.find(',') - 1)
user_out_2 = int(no_cs.find(',') + 1)
notes = open("notes.txt", "r")
notes_lines = notes.read().split("\n")
print(notes_lines[user_out_1:user_out_2]) # this is SUPPOSE to list all notes in a specific range but doesn't
notes.close()
Now here is the notes.txt file:
note
note1
note2
note3
and lastly here is what I am getting in console when I attempt to run the program and type notes(0,2)
>>> notes(0,2)
jeffv : notes(0,2)
[]
A great way to do this is to use the python .partition() method. It works by splitting a string from the first occurrence and returns a tuple... The tuple consists of three parts 0: Before the separator 1: The separator itself 2: After the separator:
# The whole string we wish to search.. Let's use a
# Monty Python quote since we are using Python :)
whole_string = "We interrupt this program to annoy you and make things\
generally more irritating."
# Here is the first word we wish to split from the entire string
first_split = 'program'
# now we use partition to pick what comes after the first split word
substring_split = whole_string.partition(first_split)[2]
# now we use python to give us the first character after that first split word
first_character = str(substring_split)[0]
# since the above is a space, let's also show the second character so
# that it is less confusing :)
second_character = str(substring_split)[1]
# Output
print("Here is the whole string we wish to split: " + whole_string)
print("Here is the first split word we want to find: " + first_split)
print("Now here is the first word that occurred after our split word: " + substring_split)
print("The first character after the substring split is: " + first_character)
print("The second character after the substring split is: " + second_character)
output
Here is the whole string we wish to split: We interrupt this program to annoy you and make things generally more irritating.
Here is the first split word we want to find: program
Now here is the first word that occurred after our split word: to annoy you and make things generally more irritating.
The first character after the substring split is:
The second character after the substring split is: t

Passing in arguments to method Python interpreter from shell

I am learning how to use Python. I would like to learn how I can pass in arguments for a function. In Java I know we can use BufferedReader or Scanner to receive user input. How do we get user input with Python? I have a function to print spaces based on user input. How do I do this?
def right_justify(s):
s = " " * 70 - s.len()
print(s)
right_justify(s)
I want to print enough spaces so s's rightmost character appears in the 70th column on the user's screen.
Stolen from: https://www.pythonforbeginners.com/basics/getting-user-input-from-the-keyboard
Raw_Input
raw_input is used to read text (strings) from the user:
name = raw_input("What is your name? ")
print "your name is: ",name
type(name)
output:
What is your name? fred
your name is: fred
type 'str'>

How to fix Python dict.get() returns default value after returning key value?

When i try to input e.g. "help move" this code prints the corresponding help message to "move" and the default value. But if I understand dict.get(key[, value]) right, the default value should only come up if the key (e.g. "run" instead of "move") is not in the dictionary.
I've tried to check if my key is a string and has no whitespace. Don't know what / how to check else.
#!/usr/bin/env python3
def show_help(*args):
if not args:
print('This is a simple help text.')
else:
a = args[0][0]
str_move = 'This is special help text.'
help_cmd = {"movement" : str_move, "move" : str_move,
"go" : str_move}
#print(a) # print out the exact string
#print(type(a)) # to make sure "a" is a string (<class 'str'>)
print(help_cmd.get(a), 'Sorry, I cannot help you.')
commands = {"help" : show_help, "h" : show_help}
cmd = input("> ").lower().split(" ") # here comes a small parser for user input
try:
if len(cmd) > 1:
commands[cmd[0]](cmd[1:])
else:
commands[cmd[0]]()
except KeyError:
print("Command unkown.")
I excpect the ouput This is a special help text. if I enter help move, but the actual output is This is special help text. Sorry, I cannot help you with "move"..
The crux of the issue is in this line:
print(help_cmd.get(a), 'Sorry, I cannot help you with "{}".'.format(a))
Your default is outside of the call to get, so it is not acting as a default and is being concatenated. For it to be a default, revise to:
print(help_cmd.get(a, 'Sorry, I cannot help you with "{}".'.format(a)))

How do i display an input in Python within a print statement

name = input('What is You name ')
this shows me only the input, I need to display 'hello' as well!!
print ('Hello', input(name))
When I try to type this :-
name = input('What is You name ')
print ('Hello')
input(name)
Why is that it displays the name directly and not the hello keyword. Could anyone please update on the same and share a coed that might be helpful.
This is even the exact example in the docs
person = input('Enter your name: ')
print('Hello', person)

Ask for input, stops asking when enter is pressed, then displays an alphabetically sorted list, print each item separately on a diff line

Challenge:
Need to write a program that asks the user to enter some data, for instance the names of their friends. When the user wants to stop providing inputs, he just presses Enter. The program then displays an alphabetically sorted list of the data items entered. Do not just print the list, but print each item separately, on a different line.
y = []
def alfabetisch( element ):
return element
while True:
user_input = input("Prompt: ")
if user_input != "":
y += [user_input]
if user_input == "":
break
for element in y:
y.sort( key= alfabetisch )
print( element )
I've made some changes and it works 'sometimes' now. If I put in the following input at the 'prompt:'
[Great, Amazing, Super, Sweet, Nice] it gives back: [Great, Great, Nice, Super, Sweet] so that is two times 'Great' and leaves out 'Amazing'
But when I give in the following input at the 'prompt:' [Amorf, Bread, Crest, Draft, Edith, Flood] it gives back: [Amorf, Bread, Crest, Draft, Edith, Flood], so with this particular input it does what I wanted it to do.
What am I doing wrong here, can anyone provide some pointers?
The input of a user is a string.
If the user doesn't input anything the output of input() function is '' ( as mentioned in the comments).
If the user inputs more than one item, as you mentioned for instance a list of friend names then iterating over the string will give you all the chars that compose that string.
A more Pythonic way of doing that will be:
user_input = input("Prompt: ")
print('\n'.join(sorted(user_input.split())))

Resources