How to take user input as tuple and then printing said tuple - python

Very new at python and im trying to figure out how to write a program to ask the users to input the courses and teachers into a tuple and then have users input "done" as an end. To finish it off i need to print the tuple. Any tips?
such as:
"Please enter your courses:" math
"Please enter your teacher:" John
"Please enter your courses:" done
('math', 'john', etc...)

Since you want to add values iteratively, tuples will not be the best choice for this since they are immutable, You can use either dictionary or lists.
Using Lists:
arr = []
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
arr.append((course,teacher))
Using Dicts
d = {}
while True:
course = input("Please enter your courses: ")
teacher = input("Please enter your teacher: ")
if course=='done' or techer=='done':
break
d[course]=teacher

The user can't input a tuple directly; you'll have to accept each input separately and assemble them into a tuple yourself:
course = input('enter course: ')
teacher = input('enter teacher:' )
mytuple = course, teacher

lst = []
while True:
course = input("Please enter the courses you are taking this semester: ")
if course == 'done':
break
professor = input("Please enter the professor's name for the course: ")
if professor == 'done':
break
lst.append((course, professor))
def convert(lst):
return tuple(lst)
print(convert(lst))
this is what i came up with, thank you

Related

I can't let the data to remain in the dictionary, it keeps updating instead

I got myself a python book. Currently, in the book, I am learning about dictionaries. The book gave me an exercise about dictionaries. This is the question.
"Create a program that pairs student's name to his class grade. The user should be able to enter as many students as needed and then get a printout of all students' names and grades. The output should look like this:
Please give me the name of the student (q to quit): [input]
Please give me their grade: [input]
[And so on...]
Please give me the name of the student (q to quit): [input]: q
Okay, printing grades!
Student Grade
Student1 A
Student2 B
[And so on...] "
def student():
studentmarks = {}
while True:
name = raw_input("Please give me the name of the student ('q' to quit):")
if name == "q":
break
elif name.isalpha() == True:
grade = raw_input("Please give me their grade ('q' to quit):")
if grade == "q":
break
elif grade.isalpha() == True:
print "Grade is a number! Please try again"
continue
elif grade.isdigit() == True:
studentmarks = {name: grade}
else:
print "Error, please try again"
continue
else:
print "Please try again. {} is not the right input".format(name)
continue
print studentmarks
continue
student()
I modified the code a bit to test the dictionary. I also use python 2
you made only one mistake witch is when you append the data to dictionary:
studentmarks = {name: grade}
it should be like this :
studentmarks[name] = grade
You're overwriting the dictionary every time you get to this line:
studentmarks = {name: grade}
It should be like this:
studentmarks[name] = grade

New to Python, need some direction on checking user input against a list

I was messing around and wanted to see if I could get this simple program to work. I want to check the user input against my list and output whether or not it is in the list. How I have it setup up currently it will return for the 0 index but not the other two. What am I doing wrong?
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
if name == check_name[1]:
print("Welcome jim")
elif name == check_name[2]:
print("Welcome betty")
pass
else:
print("Sorry, Looks like you are not in the system")
pass
Your last two if statements are only evaluating nested inside of the first one. You need to unindent them so that they'll evaluate if the first does not.
Another solution:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name not in check_name:
print("Sorry, Looks like you are not in the system")
You have an indentation problem.
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name == check_name[0]:
print("Welcome lisa")
elif name == check_name[1]:
print("Welcome Jim")
elif name == check_name[2]:
print("Welcome Betty")
else:
print("Sorry, Looks like you are not in the system")
You already got your answer above. Here is an alternate solution negating the need of multiple if statements making your code concise:
print("Check to See if You are Registered:")
name = input("Please Enter Your Name:")
check_name = ["lisa", "jim", "betty"]
if name in check_name:
print("Welcome %s" %name)
else:
print("Sorry, Looks like you are not in the system")
The command if name in check_name: checks if the input name exists in the name list and welcomes the corresponding person. If the input name doesn't exist, it throws the Sorry... statement

How to update a dictionary with a user's input

I'm trying to take information from the user and then take that info to update a dictionary. It's a part of an exercise I'm doing. I've tried to use .format(var1, var2) with the way you update a dictionary, but when ends up happening is only one part of the dictionary gets updated.
name_grade = {}
while True:
name = raw_input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = raw_input("Give me their grade: ")
name_grade['{}'] = '{}'.format(name, grade)
name_grades = {}
while True:
name = input("Please give me the name of the student [q to quit]:")
if name == 'q':
break
else:
grade = input("Give me their grade: ")
name_grades[name]=grade
print(name_grades)
Are you looking for this or something else?
You can update the dictionary by saying
name_grade[name] = grade

validate user input by length in Python

I have some code:
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
How can I keep asking for the player's name until they enter a name that is more than one character long, and tell them they must enter a valid name if they leave the field blank?
I tried
def GetPlayerName():
print()
PlayerName = input('Please enter your name: ')
print()
return PlayerName
while len(PlayerName) < 1:
print("You must enter a name!")
but have been unsuccessful.
Use a while loop to get the input repetitively:
def get_player_name():
print()
player_name = ""
while len(player_name) <= 1:
player_name = input('Please enter your name: ')
print()
return player_name
The way you are currently using it, you use the while statement to only print the error message.
PS: I've converted your variable names etc to small_caps_format because that is what PEP recommends.
def GetPlayerName():
print()
while True:
PlayerName = input('Please enter your name: ')
if len(PlayerName) > 1:
break
print("Your name is too short! :c")
print()
return PlayerName
One solution amongst others, and doesn't require any variables outside of the while loop. As mentioned by #jme, the error message is rather easy to print with this solution. The issue with your code is that:
Your while loop is after the return statement is called, so it's affectively rendered mute.
Your while loop is infinite-- it doesn't give the user a chance to re-try!

Python Phonebook program

I have this program, and it is almost perfect but I need the dictionary to print on separate lines like so:
Please enter a name (or just press enter to end the input): Tom
Please enter Tom's phone: 555-5555
Please enter a name (or just press enter to end the input): Sue
Please enter Sue's phone: 333-3333
Please enter a name (or just press enter to end the input): Ann
Please enter Ann's phone: 222-2222
Please enter a name (or just press enter to end the input):
Thank you.
Your phonebook contains the following entries:
Sue 333-3333
Tom 555-5555
Ann 222-2222
Here is my code:
def main():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
number = input("Please enter number: ")
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name == '':
print("Thank You!")
print("Your phonebook contains the following entries:\n",phoneBook)
main()
Loop through the entries in your phonebook and print them one at a time:
for name, number in phoneBook.items():
print ("%s %s" % (name, number))
something like this:
strs = "\n".join( " ".join((name,num)) for name,num in phoneBook.items() )
print("Your phonebook contains the following entries:\n",strs)
if you dont want to write codes yourself, pprint could be an option:
import pprint
....
print("Your phonebook contains the following entries:\n")
pprint.pprint(phoneBook)
You can use format() to make your life easy:
for i in phoneBook.iteritems():
print("{0} {1}".format(*i))
my_dictionary = {}
while True:
name = str(input("Enter a name: "))
if name == "":
break
elif name in my_dictionary:
print "Phone Number: " + my_dictionary[name]
else:
phone_number = input("Enter this person's number: ")
my_dictionary[name] = phone_number
print my_dictionary

Categories

Resources