How to input text in python - python

So I just started trying out python yesterday and I want to code something where I can input text then the something will be added once enter is pressed
for example:
If I input: Sam Smith
After pressing enter . . .
I would get: Welcome Sam Smith

name = input('What is your name? ')
print('Welcome ' + name)
First, the user is asked for the name which is then stored in a variable. Then, a message is printed using the stored name.

Python2.x:
>>> name = raw_input("Please enter the name..")
Please enter the name..Sam Smith
>>> name
'Sam Smith'
>>> print "Welcome " + name
Welcome Sam Smith
Python3.x:
>>> name = input("Please enter the name..")
Please enter the name..Sam Smith
>>> name
'Sam Smith'
>>> print("Welcome " + name)
Welcome Sam Smith

Related

i am trying to put the last sentence "else : print("are you without a name?")" in a loop where it keep asking until a valid answer is given

name = input("what is your name: ")
while name:
if name.isnumeric():
name = input("please write a valid name ")
else:
print(f"hello {name}")
break
else :
print("are you without a name?")
You can directly ask for the input and check if valid in the while statement, looping until a valid name has been entered. That whole clause can be this 3 simpler lines.
while not (name := input("what is your name: ")).isalpha():
print("please write a valid name ")
print(f"hello {name}")
Output:
$ python script.py
what is your name: Agent007
please write a valid name
what is your name: 1234
please write a valid name
what is your name: Bond
hello Bond

Creating lists in python, if statement syntax error

I'm creating a project that has two lists of popular boy and girl names. it instructs the user to enter a boy a girl name and then lets them know if that name was popular. I'm pretty sure I have everything right, but I keep on getting a syntax error in line 18 (elif statement under if gender == 'g'), highlighting the colon after elif. If anyone has any idea why that would be very helpful because i can't figure it out
def main():
# Open a file for reading.
infile = open('GirlNames.txt', 'r')
infile2 = open('BoyNames.txt', 'r')
# Read the contents of the file into a list.
GirlNames = infile.readlines()
BoyNames = infile2.readlines()
# Close the file.
infile.close()
gender = input('Enter g to search for a girl name, b for a boys name, or both for both')
if gender == 'g':
girl = input('Please enter a girls name: ')
if girl in GirlNames:
print (girl, "was a popular girl's name between 2000 and 2009")
elif:
print (girl, "was not a popular girl's name between 2000 and 2009")
if gender == 'b':
boy = input('Please enter a boys name: ')
if boy in BoyNames:
print (boy, "was a popular boy's name between 2000 and 2009")
elif:
print (boy, "was not a popular boy's name between 2000 and 2009")
elif gender == 'both':
girl1 = input("Please enter a girl's name ")
boy1 = input("please enter a boy's name ")
if girl1 in GirlNames:
print (girl1, "was a popular girl's name between 2000 and 2009")
if boy1 in BoyNames:
print (boy1, "was a popular boy's name between 2000 and 2009")
# Call the main function.
main()

breaking a loop when enter is pressed

I'm trying to break the loop once Enter is pressed, while writing data to a file. This is what I have so far. I also don't want to limit the number of time the loop is run either... (example output is below)
def main():
myfile = open('friends.txt','w')
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
while friend != '':
for n in range():
friend = input('Enter first name of friend or Enter to quit')
age = input('Enter age (integer) of this friend')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
myfile.close()
main()
This is how to output is supposed to be when its ran right.
Enter first name of friend or Enter to quit Sally
Enter age (integer) of this friend 20
Enter first name of friend or Enter to quit Sam
Enter age (integer) of this friend 24
Enter first name of friend or Enter to quit
File was created
def main():
myfile = open('friends.txt','w')
while True:
friend = input('Enter first name of friend or Enter to quit: ')
if not friend:
myfile.close()
break
else:
age = input('Enter age (integer) of this friend: ')
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
main()
Output:
Enter first name of friend or Enter to quit: Mack
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit: Steve
Enter age (integer) of this friend: 11
Enter first name of friend or Enter to quit:
Process finished with exit code 0
You had a couple of errors in your code, such as using range() and indentation and using input for a string, when raw_input may have been a better choice.
To do what you want, you should put the write at the beginning of your loop, and after asking for the name, check if it's empty and, if it is, break. Code is below:
def main():
myfile = open('friends.txt','w')
friend = raw_input('Enter first name of friend or Enter to quit')
age = int(raw_input('Enter age (integer) of this friend'))
while friend != '':
while True:
myfile.write(friend +'\n')
myfile.write(str(age) +'\n')
friend = raw_input('Enter first name of friend or Enter to quit')
if not friend:
break
age = int(raw_input('Enter age (integer) of this friend'))
print('File was created')
myfile.close()
main()

Making a greeting program in python

Really easy stuff, sorry in advance for the idiotic question but I'm just not understanding how to do this... I want to make a function that asks the user's name and then greets the user by name.
so if I were to do greet(yo)...
What's your name? Tom
Yo, Tom
I've got this so far:
def greet(yo):
print("Whats your name")
raw_input(name)
return yo + name
Save the return value from raw_input into a variable:
def greet(yo):
name = raw_input("What's your name: ")
return yo + name
print greet("hi! ")
Demo:
>>> greet('hi! ')
What's your name: Tom
'hi! Tom'
For python 2, use raw_input to get input.
For python 3, use input to get input.
def greet(greeting):
name = raw_input("Hi, whats your name?") #python 2
return greeting + name
print greet("Hi, ")
# Python program that asks the user to enter their name, and then greet them.
name = input("Hello, What's your name?")
# Then type in your name.
print("Hello " + name+ " it's nice to meet you"+ "!")
For example:
Hello, What's your name?Bob
Hello Bob it's nice to met you!

Saving Raw_input to a list when used in a While Loop

I have already posted a question today and it had 2 problems on it. One of which was solved perfectly, then it got a little complicated. So forgive me but I am posting the other question separately as it confused some peeps:
I am new to python so apologies in advance. Any help is much appreciated. I have been stuck on this code for 2weeks now and I have tunnel vision and cannot work it out:
Basically our assignment was to get to grips with Object-Oriented Programming. We unfortunately have to use "get" and "set" which I've learnt a lot of people dislike, however, as per our tutor we have to do it like that. We were told tp create a program whereby the user is presented with a screen with 3 options. 1. adding a student. 2. viewing a student and 3. removing a student.. within my AddStudent function I have to ask the user to enter fname Lname age degree studying id number (these are the easy bits) and also module name and grade for each module, I have managed to create a loop whereby it will ask the user over and over to enter modules and corresponding grades and will break from said loop when the user enters -1 into the modulname field. However, when trying saving it to a list named students[] ... (which is at the very top of my code above all functions, to apparently make it global) it saves all input from the user re: age name etc but when it comes to saving module names and grades it only saves the last input and not the multiple inputs I need it to. I am unsure if it is within my AddStudent function where it isn't saving or within my ViewStudent function: Both are below (remember I HAVE to use the GET and SET malarky) ;)
students[] # Global List
def addStudent():
print
print "Adding student..."
student = Student()
firstName = raw_input("Please enter the student's first name: ")
lastName = raw_input("Please enter the student's last name: ")
degree = raw_input("Please enter the name of the degree the student is studying: ")
studentid = raw_input("Please enter the students ID number: ")
age = raw_input("Please enter the students Age: ")
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
student.setFirstName(firstName) # Set this student's first name
student.setLastName(lastName)
student.setDegree(degree)# Set this student's last name
student.setGrade(grade)
student.setModuleName(moduleName)
student.setStudentID(studentid)
student.setAge(age)
students.append(student)
print "The student",firstName+' '+lastName,"ID number",studentid,"has been added to the system."
........................
def viewStudent():
print "Printing all students in database : "
for person in students:
print "Printing details for: " + person.getFirstName()+" "+ person.getLastName()
print "Age: " + person.getAge()
print "Student ID: " + person.getStudentID()
print "Degree: " + person.getDegree()
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
your problem is that the module is a single variable you keep changing. instead, make it a list.
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
should be something like
modules = []
while True:
moduleName = raw_input("Please enter module name: ")
if moduleName == "-1":
break
grade = raw_input ("Please enter students grade for " + moduleName+": ")
modules.append((moduleName, grade))
add a new variable to student which is "Modules" and is a list.
and then modules will be a list of tuples which are (moduleName, grade) and to display them, change the line in viewstudent from:
print "Module: " + person.getModuleName()
print "Grades: " + person.getGrade()
to:
for module, grade in person.getModules():
print "Module: " + module
print "Grades: " + grade
It seems you need something like this:
modules = {}
while True:
module_name = raw_input("Please enter module name: ")
if module_name:
grade = raw_input ("Please enter students grade for " + module_name +": ")
modules[module_name] = grade
Modules is a dictionary ("hash map" in other languages), each mod name is key and grades are values, or you could also do it with tuples, wherever floats your boat.
Instead of checking for -1 as a stop condition you check if is true, in python anything empty is evaluated to false.

Categories