I want my code below to ask users to add contacts which i will save in a dictionary.
When user responds N to whether they want to add new contact, the loop is supposed to terminate. When Y, the loop must continue and when they enter something which is neither N nor Y, the question must keep repeating till they enter Y or N.
My code below does not return to beginning of function when i type yes
contactbook = {}
def addcontact():
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
while True:
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
elif qu == 'N':
break
After I reply Y to the question, I do not get the program to repeat
You can achieve that logic more cleanly by sth. like:
def addcontact():
while True: # no variable like keepadding needed
name = ...
# ...
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N").upper()
if qu == 'N':
break
# no need to specify the 'Y' case, the outer loop just continues
This is because you are assigning to a variable named keepadding. The loop tests the value of a variable named keepreading. Because these variables are different the test will always be True and the loop will continue even if you enter N.
Update your code to initialise the variable at the top of the function and test the correct variable:
def addcontact():
keepadding = True
while keepadding:
....
Updated following OP code change:
Move the while loop to the top of the function so that the input() and contact book updates occur within the loop. Change elif to if. Here is a working version:
contactbook = {}
def addcontact():
while True:
name = input("Enter the name of your new contact")
number = int(input("Enter your phone contact"))
contactbook[name] = number
print("Contact book successfully updated with : ", contactbook.items())
qu = 'X'
while qu not in 'YN':
qu = input("Do you want to add a new contact? Y/N: ").upper()
if qu == 'N':
break
Try this:
contactbook = {}
def addcontact():
keepadding = True
while keepadding:
name = input("Enter the name of your new contact: ")
number = int(input("Enter your phone contact: "))
contactbook[name] = number
print("Contact book successfully updated with {}, {}".format(name, number))
while True:
qu = input("Do you want to add a new contact? Y/N ").upper()
if qu in 'YN':
break
print("That's not a valid input. Try again.")
keepadding = qu.upper() == 'Y'
addcontact()
Related
so i have this project that I should make a program to add identify or delete data from an inventory.txt file
but when I ever try to print the inputs in the file I get messy text, what I'm looking for is a table-like structure printed inputs in the .txt file, I've tried to remove and readjust the place of \n and \t but still, I get stuff like this in the file
Samsung ide445 2154SS rams 120.0 14
Logetech Specture lid224 G502 230.0 8
here's my code for a closer look:
#This function is to get the parts information from the user
def input_parts():
#Taking the parts input from the user
try:
make = input("Enter the make: ")
model = input("Enter the model: ")
part_id = input("Enter part_id: ")
part_name = input("Enter part name: ")
price = float(input("Enter price:QR "))
quantity = int(input("Enter quantity: "))
except ValueError:
print("BOTH PRICE AND QUANTITY CAN NOT BE LETTERS, PLEASE RE-ENTER THE RIGHT DATA")
else:
#transferring both price and quantitiy to strings
price = str(price)
quantity = str(quantity)
list = ['\n'+make,model,part_id,part_name,price,quantity]
return list
#This function is to save the parts information to a file
def add_parts():
#Assignning this sentinal to make the loop repeat if the user didn't want to save
sentinal = True
while sentinal is True:
#Assigning the values of the inputs function to a variable
parts = input_parts()
#Validating user's unput
try:
#Asking the user if he wants to save the information to the file
save = input("Save? (Y/N) or Q to quit ")
except TypeError:
print("YOU CANNOT SAVE WRONG DATA IN THE FILE PLEASE RE-ENTER YOUR DATA")
else:
pass
#A boleen function to export the data to the file if the boleen is true
if save.lower() == 'y':
outfile = open('inventory.txt',"a")
#Validating user's input
try:
#Using a for loop to print the information in the file
for i in parts:
outfile.write(i+'\t')
except TypeError:
print("YOU CAN NOT SAVE WRONG DATA FILES!!!")
break
else:
pass
outfile.close
print("....Record saved.")
sentinal = False
#Using an elif statment to enable the user to re input his data
elif save.lower() == 'n':
sentinal = True
#Using an elif statment to quit if the user wants to
elif save.lower() == 'q':
break
#Using else statment to tell the user no input a valid choice
else:
print("PLEASE ENTER (Y/N) IF YOU WANT TO SAVE!!!!")
print("YOUR DATA HAS NOT BEEN SAVED")
print("PLEASE RE-ENTER YOUR DATA AND TRY AGAIN.")
sentinal = True
add_parts()
You can import tabulate module and use it as below example:
from tabulate import tabulate
print(tabulate([['Saeed', 26], ['You', 24]], headers=['Name', 'Age']))
Result:
Name Age
------ -----
Saeed 26
You 24
You may use this module to reach what you want.
I'm currently trying to run a program where the user inputs a word and then after they input the first word, the program will ask if they want to continue putting words. Once the user replies "no", the program will generate the list of words that has been input. I seem to be having trouble calling the array for my code below:
def word():
w1 = input("Please enter a word: ")
group = []
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
How I can make this work properly?
I think you meant to pass the list into the function:
def word(group):
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
return decide == "yes"
group = []
while True:
crit = word(group)
if crit:
continue
else:
print("words are: ", group)
break
The array ‘group’ is defined inside the function word(). This means if the function is returned, the list ‘group’ disappears also.
You can either
Use global variable
Define group outside the function (in this case, at the top) and use that global list inside the function. I.e. add the line
global group in the first line of the function.
However, using global variable when not needed is not so recommandable.
Define group list outside the function and pass it to the function as an argument
Instead of def word(), use def word(group) and pass the list to the function when calling the function.
group = []
def word():
w1 = input("Please enter a word: ")
group.append(w1)
decide = input("Do you want to continue? yes/no: ")
if (decide == "yes"):
return -1
elif (decide == "no"):
return 1
while (True):
crit = word()
if (crit == -1):
continue
elif (crit == 1):
print("words are: ", group)
break
The variable group is not available outside the function.
A variable created outside of a function is global and can be used by anyone.
Hopefully my code and question(s) are clear for understanding. If they are not please provide feed back.
I am fairly new to programing/coding so I decided to develop a program using Python that acts like a pizza ordering system. I eventually would like to use this code to develop a website using Django or Flask.
I have just finished the first step of this program where I am asking the user if this will be for delivery of pickup. Depending on what the user chooses the program will ask for specific information.
The area I feel like I am struggling with the most is developing classes and functions. specifically taking a variables from one function and using that variable in another function. I posted a past example of my code and I was advised that Global variables are not good to use in code. So I am trying really hard to refrain from using them.
Here is the code for reference:
import re
running = True
class PizzaOrderingSys():
"""order a customized pizza for take out or delivery """
def delivery_or_pickup(self): # Is the order for devilery or pickup?
print("\nWill this order be for pickup or delivery?")
self.delivery = input("P - pick up / D - delivery : ")
self.delivery = self.delivery.title()
if self.delivery == "D":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a vaild input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a a contact phone number")
else:
break
while running == True:
house_num = input("\nWhat is your house or unit number: ")
if not re.match("^[0-9 /]*$", house_num):
print("Please use numbers only")
elif len(house_num) == 0:
print("Please enter a valid input ")
else:
break
while running == True:
streetName = input("\nStreet name: ")
if not re.match("^[a-zA-Z ]*$", streetName):
print('Please use letters only.')
elif len(streetName) == 0:
print("Please enter a valid input")
else:
streetName = streetName.title()
break
while running == True:
city = input("\nCity: ")
if not re.match("^[a-zA-Z ]*$", city):
print("Please use letters only")
elif len(city) == 0:
print("Please enter a valid input")
else:
city = city.title()
break
while running == True:
zip_code = input("\nZip Code:")
if not re.match("^[0-9 /]*$", zip_code):
print("Please use numbers only")
elif len(zip_code) == 0 or len(zip_code) > 5:
print("Please enter a valid input")
else:
break
elif self.delivery == "P":
while running == True:
customerName = input("\nName for the order: ")
if not re.match("^[a-zA-Z ]*$", customerName):
print("Please use letters only")
elif len(customerName) == 0:
print("Please enter a valid input")
else:
customerName = customerName.title()
break
while running == True:
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
if not re.match("^[0-9 ]*$", customerPhoneNumber):
print("Please use numbers only")
elif len(customerPhoneNumber) == 0:
print("Please enter a valid input")
else:
break
else:
print("Please enter P or D ")
delivery_or_pickup()
order = PizzaOrderingSys()
order.delivery_or_pickup()
My question is this: How would I use variables found in one function of my class and use it in another future function??
For example if I wanted to retrieve variables the functions customerName, customerPhoneNumber, house_num, streetName, city, Zip_code found in delivery_or_pick() function and use them in a function called:
def customer_receipt():
What would I need to do to my exiting code or to the def customer_receipt() function to obtain that information?
Any help with my questions or advise on any other area that stick out to you would be be greatly appropriated.
This is my second post on Stackoverflow so I apologize if what i am asking is unclear or the format of my question might is off, I am still learning.
Thank you again.
The idea here is that you can use your class variables to save data between method calls. Methods are functions that belong to a class. For example you could use Python's class initialization and create a dict of orders. Here is a simple example of such system, take a note of the usage of self keyword. self refers to the instance of the class and you can use it to access the variables or methods of the instance:
class PizzaOrderingSys:
def __init__(self):
# Initializing some class variables
self.running = True # Now you can use self.running instead of global running variable
self.orders = {}
def delivery_or_pickup(self):
# Somewhere at the end where you have collected the needed info
order = {
"zip_code": zip_code,
"city": city,
# You can enter all of the needed data similarly
}
order_id = "SomeIdHere" # ID could be anything, it just should be unique
self.orders[order_id] = order
return order_id
def customer_receipt(self, id):
# Now you can access all of the order here with self.orders
order = self.orders.get(id) # Select some specific order with id.
# Using get to avoid the situation
# where no orders or invalid id would raise an exception
if order:
receipt = f"Order {id}:\nCustomer city {order['city']}"
else:
receipt = None
return receipt
pizzasystem = PizzaOrderingSys()
order_id = pizzasystem.delivery_or_pickup()
receipt = pizzasystem.customer_receipt(order_id)
print(receipt)
# >>> Order 1235613:
# Customer city Atlantis
I recommend that you read more about classes, for example, python docs have great material about them.
How would I stop my code looping after it has added the amount of names the user has inputted instead of doing this:
Add Name
Show list
Quit
Enter your choice : 1
How many names would you like to enter: 2 # How would I set a max of 10 names here?
Enter name: Bob
Enter name: Jim
How many names would you like to enter: # How would I stop this line from repeating?
Actual code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while choice >5 or choice <1:
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
while True:
number=int(input('How many names would you like to enter: '))
name = [input('Enter name:') for _ in range(number)]
names.append(name)
def displayData():
#name.split(",") how would i correctly user split here
print(names)
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Okay, first off, since you only have three menu options, this line:
while choice >5 or choice <1:
Should look like this:
while 3 < choice < 1:
So your displayMenu function looks like this:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
You also said that your addname function was looping forever, this is because you have an infinite while loop.
What you need, as #ettanany said, is a for loop:
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
What this does is ask the user how many names he wants to enter, and then runs the code inside the loop for that amount of times -- so if the user enters the number 9, it will ask for 9 names.
You also said that there should be a maximum of 10 names. We can use a while loop like you did in the displayMenu function to make sure the user enters a number that is 10 or below:
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Finally, in your displayData function, you want to 'split' the names and print them out.
Just doing print(names) would give us a result like this:
[ 'Spam', 'Eggs', 'Waheed' ]
If we want it to look nice, we need to use a for loop.
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
This will yield a result like this:
Spam
Eggs
Waheed
Which looks much better than just printing out the list.
Complete (fixed) code:
names = []
def displayMenu():
print(" 1. Add Name")
print(" 2. Show list")
print(" 3. Quit")
choice = int(input("Enter your choice : "))
while 3 < choice < 1: # Only accept choices in between 3 and 1
choice = input("Invalid. Re-enter your choice: ")
return choice
def addname():
number = int(input('How many names would you like to enter: '))
while number > 10: # Don't allow any numbers under 10
number = int(input('Please enter a number under 10: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
def displayData():
for name in names:
print( name ) # You can change this line to print( name, end=' ' )
# If you want all the names on one line.
option = displayMenu()
while option != 3:
if option == 1:
addname()
elif option == 2:
displayData()
option = displayMenu()
print("Program terminating")
Instead of while True, you need to use while i < number, so your addname() function should be as follows:
def addname():
i = 0
number = int(input('How many names would you like to enter: '))
while i < number:
name = input('Enter name: ') # We ask user to enter names one by one
names.append(name)
i += 1
In your case, for loop would work also:
def addname():
number = int(input('How many names would you like to enter: '))
for i in range(number):
name = input('Enter name: ')
names.append(name)
Allows the user to submit a pairing
Allows the user to delete a pairing
Allows the user to submit final pairings
How can I edit the program so that the user (after completing 1, 2 or 3) i asked the same question again? (Question = user_selection)
clue_list = {'#':'A', '%':'N', '*':'M'}
user_selection = input('What would you like to do? 1.Submit a letter or symbol pairing, 2.Delete a letter/symbol pairing, 3. Submit Final Answers ')
while user_selection != '3':
if user_selection == '1':
userkey = input('Please enter a symbol to add: ')
uservalue = input('Please enter a letter to add: ')
if userkey in clue_list:
print('This symbol has already been matched. Please try again.')
else:
clue_list[userkey] = uservalue
print(clue_list)
if user_selection == '2':
user_delete_input = input('What letter/symbol would you like to delete? (Please enter symbol to delete the pairing ')
if user_delete_input in clue_list:
del clue_list[user_delete_input]
print('That letter/symbol has been deleted.')
else:
print('Error: That letter/symbol has not been found in file.')
user_submit1 = input('Would you like to submit more pairings? Yes/No ')
if user_submit1 == 'Yes':
function_result2 = submit(clue_list)
else:
if user_submit1 == 'No':
print('...')
The crux of your question is getting the selection process to repeat. You can do so quite easily if you learn to abstract away parts of your code with functions. For example, a possible answer to your question looks like:
while True:
user_selection = input(msg_ask).strip()
if user_selection == '1': add_symbol(clue_list)
elif user_selection == '2': remove_symbol(clue_list)
elif user_selection == '3': break
Where we've defined the functions add_symbol and remove_symbol like so:
clue_list = {'#':'A', '%':'N', '*':'M'}
msg_ask = '''
What would you like to do?
1. Submit a letter or symbol pairing,
2. Delete a letter/symbol pairing,
3. Submit Final Answers
'''
def add_symbol(clue_list):
userkey = input('Please enter a symbol to add: ')
uservalue = input('Please enter a letter to add: ')
if userkey in clue_list:
print('This symbol has already been matched.')
else:
clue_list[userkey] = uservalue
print(clue_list)
def remove_symbol(clue_list):
msg = 'What letter/symbol would you like to delete? (Please enter symbol to delete the pairing) '
user_delete_input = input(msg)
if user_delete_input in clue_list:
del clue_list[user_delete_input]
print('That letter/symbol has been deleted.')
else:
print('Error: That letter/symbol has not been found in file.')
You'll notice how the first code block is much easier to read.