Python Phonebook program - python

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

Related

Writing Python functions

This code executes well, but I don't think this the best way to do it.
def bank_account(Name, number, username, passwrod):
Output = Name, number, username, passwrod
return Output
new_name = input ("Please Enter Your Name: ")
new_number = input ("What's your number please: ")
new_username = input ("Enter your UserName: ")
new_passwrod = input ("(Integers Only!) Enter your Passwrod Sir: ")
print("Your Data has been saved!", bank_account(new_name, new_number, new_username, new_passwrod))
Is there any other way to do it?
As the comments suggest, what you're trying to do is unclear!
Maybe something the bank_account function can do is validate the input?
For example you specify that the password must be numeric. For arguments sake let's say the same is true for the number. Also just assume that the name must only consist only of alphabetic letters.
def bank_account(name, number, username, password):
if not name.isalpha():
print('Your name must only contain letters!')
return 'Invalid'
try:
number = int(number)
password = int(password)
except ValueError:
print('Your number and password must be numeric!')
return 'Invalid'
return name, number, username, password
new_name = input("(alphas) Please Enter Your Name: ")
new_number = input("(ints) What's your number please: ")
new_username = input("Enter your UserName: ")
new_password = input("(ints) Enter your Password: ")
print("Your details:", bank_account(new_name,
new_number,
new_username,
new_password))
Hope this gives you an idea of something you can do with your bank_account function!

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

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

Dictionary phonebook with userInput, but with a twist

I have been working on this for too long. It should be simple and I've ran through many different combinations, however, I keep getting the code wrong and have no idea why. It works fine when I have manual input, but when I submit there is an error.
question prompt:
Write a program that keeps a dictionary of names and their corresponding phone numbers.
Repeatedly ask the user for a name. Then, do one of the following three things, depending on what they enter:
If they enter nothing, exit the program.
If they enter a name that exists as a key in your dictionary, simply print the corresponding phone number.
If they enter a name that is NOT in your dictionary as a key, ask the user for a phone number, and then put the name and phone number in your dictionary.
Print out the final dictionary.
my code:
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook:
number = input("Please enter number: ")
print "Phone number: " + number
phoneBook[name] = number
name = input("Please enter a name(or press enter to end input): ")
if name in phoneBook:
print phoneBook[name]
if name == '':
break
print phoneBook
Expected result:
Phone number: 1234
Phone number: 5678
{'Tracy': '5678', 'Karel': '1234', 'Steve': '9999'}
My result:
Phone number: 1234
Phone number: 5678
Phone number: 9999
1234
Phone number: 9999
5678
Phone number: 9999
{'Tracy': '9999', 'Karel': '9999', 'Steve': '9999'}
you must also access the dictionary keys for checking the existence of a name:
if not name in phoneBook.keys():
phoneBook = {}
name = input("Please enter a name(or press enter to end input): ")
while name != '':
if not name in phoneBook.keys():
number = input("Please enter number: ")
phoneBook[name] = number
print "Phone number: " + number
name = input("Please enter a name(or press enter to end input): ")
else:
print phoneBook[name]
print phoneBook
Try the above code.
When a name is not in the phoneBook, then assign the name a number, so phoneBook[name] = number should be in the if not name in phoneBook.keys(): block. And then enter another name in the same if block.

How to remove the parenthesis and a comma in the output

I am writing a program in python for a banking application using arrays and functions. Here's my code:
NamesArray=[]
AccountNumbersArray=[]
BalanceArray=[]
def PopulateAccounts():
for position in range(5):
name = input("Please enter a name: ")
account = input("Please enter an account number: ")
balance = input("Please enter a balance: ")
NamesArray.append(name)
AccountNumbersArray.append(account)
BalanceArray.append(balance)
def SearchAccounts():
accounttosearch = input("Please enter the account number to search: ")
for position in range(5):
if (accounttosearch==AccountNumbersArray[position]):
print("Name is: " +NamesArray[position])
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
break
if position>4:
print("The account number not found!")
while True:
print("**** MENU OPTIONS ****")
print("Type P to populate accounts")
print("Type S to search for account")
print("Type E to exit")
choice = input("Please enter your choice: ")
if (choice=="P"):
PopulateAccounts()
elif (choice=="S"):
SearchAccounts()
elif (choice=="E"):
print("Thank you for using the program.")
print("Bye")
break
else:
print("Invalid choice. Please try again!")
Everything is fine now, but when I run the program and search for an account. For example, when I search an account the output shows ('name', 'account has the balance of: ', 312) instead of name account has the balance of: 312 How do I fix this?
In the line
print(NamesArray[position],"account has the balance of: ",(BalanceArray[position]))
you should use string concatenation to add the different strings. One way to do this would be like this:
print(NamesArray[position] + " account has the balance of: " + str(BalanceArray[position]))
u are using old python version,
replace your line with this :
print(NamesArray[position] + "account has the balance of: " + (BalanceArray[position]))
use ' + ' instead of comma

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!

Categories

Resources