How do i display an input in Python within a print statement - python-3.x

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)

Related

Python Error message for entering a number instead of a letter

I just started my programming education with python in school. One of the programs I started with simply asks you your name and then repeats it back to you. I'd like some help with getting an error message to show up if you put in a number rather than letters.
This is what I have:
while True:
name = input("What is your full name? ")
try:
n = str(name)
except ValueError:
print("Please enter your name in letters, not", repr(name))
continue
else:
break
print(name)
You can check the name if only contains letters by using string.isalpha()
in your case you name it n so n.isalpha() will return True or False
for more information:
How can I check if a string only contains letters in Python?

Name formatting in python with string splits

I have gotten mostly through this assignment but I am stuck as to obtain the proper outputs.
This assignment wishes that if the inputs are a full name, that the outputs are "last name, first initial. last initial. If the input was Stacy Estel Graham, the expected output should be Graham, S.E.
"Many documents use a specific format for a person's name. Write a program whose input is:
firstName middleName lastName
and whose output is:
lastName, firstInitial.middleInitial."
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
mod_name.join('.')
print(last_name)
print(mod_name)
I am completely lost on how to proceed.
You need to use '.'.join() to get the initials added.
To extract only the first char from the name, you can do mod_name[i][:1] where i is the index from 0 until last name - 1.
You can do something like this:
full_name = input('Enter your full name :')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')
Here are some of the sample runs:
Enter your full name :Stacy Estel Sugar Graham
Graham, S.E.S.
Enter your full name :Stacy Estel Graham
Graham, S.E.
Enter your full name :Stacy Graham
Graham, S.
Enter your full name :Graham
Graham
Use:
def format_name(name):
names = name.split()
return f"{names[-1]}, {''.join([f'{i[0]}.' for i in names[:-1]])}"
Examples:
format_name('Stacy Estel Graham')
# > 'Graham, S.E.'
format_name('Randall McGrath')
# > 'McGrath, R.'
this code help you,but middle name is must for every person for creating your desire output
import re
s="Stacy Estel Graham"
words=s.split()
k=re.findall("[A-Z]",s)
p=words[-1]+","+k[0]+"."+k[1]
print(p)
Output:
Graham,S.E
Not with re :
full_name = input()
mod_name = full_name.split(' ')
last_name= mod_name.pop(-1)
first_inital = mod_name[0][0]
if len(mod_name) >= 2:
middle_inital = mod_name[1][0]
print(f'{last_name}, {first_inital}.{middle_inital}')
else:
print(f'{last_name}, {first_inital}.')
You can use string indexing and f' string format.
Input:
Hello World Python
Output:
Python, H.W.
full_name = input(')
mod_name = full_name.split(' ')
temp = '.'.join([mod_name[i][0] for i in range (0, len(mod_name) - 1)])
if temp == '':
print (mod_name[-1])
else:
print (mod_name[-1] + ', ' + temp + '.')

Why I am getting a duplicate output in Python?

I am trying the below code. But in the final output, I am getting repeated words. For example, if I input name as Jai, I will get JaiJai.
name = input ("Cheer: ")
for i in name:
name +=i
print('Give me a', i+",", i+"!")
print("What does it spell?")
print(name)
Because of this:
for i in name:
name +=i
for every character in a given word, add this character to the word.
You adding up the value of i to the name variable
this line name +=i is redundant here :)
corrected code:
name = input ("Cheer: ")
for i in name:
print('Give me a', i+",", i+"!")
print("What does it spell?")
print(name)

How can I print the required row when reading a csv file in python

I am a beginner of python, I have an assignment that wants me to read a csv file and print out the related information.
I have an excel file which includes student's ID, school and hobby.
now I want to write a program to show the detail of the student by entering the ID.
requirements are:
print the entire row when ID is correctly input
print "Empty, try again" when ID input is space
print "No record" when the input is invalid or there is no matching record
I manage to fulfill the first 2 requirements but have no idea how to get the third. Seems like my code is always looping through each of the data and print "No record" every time, i.e. if there are 3 records, 3 "No record" will be printed. Could someone help me with it? Much thanks! Below will be my code.
import csv
file = "a.csv"
sID = input("Enter ID: ")
while (sID == " "):
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row[id],row[school],row[hobby])
else:
print("No record")
You need a few changes:
You should use the str.strip() method to test if a string is empty so that it accounts for any number of spaces.
You should quote the column names to make them string literals when using them as indices to access the value of a column in the current row.
You should use the optional else block for your for loop to determine that there is no matching record found, and break the loop if there is one found.
You are missing a right parenthesis for the print call that outputs a row.
With the above changes, your code should look like:
import csv
file = "a.csv"
sID = input("Enter ID: ")
while not sID.strip():
print("Empty input,enter again")
sID = input("Enter ID: ")
with open(file) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
if (sID == row["id"]):
print("{0}{1}{2}".format(row['id'],row['school'],row['hobby']))
break
else:
print("No record")

What did I do wrong

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

Resources