Global variable declaration error in Python - python

I am fairly new to Python/programming, I started about four months ago and since I am a teacher and may possible have a lot more time on my hands.
For my first project I have started to develop a pizza ordering system-- at the moment I am just having the user interact with the program through the terminal. However, I plan to evidentially use Django to create a web page so a user can actually interact with.
I will first share my code:
import re
sizePrice = {
'small': 9.69,
'large': 12.29,
'extra large': 13.79,
'party size': 26.49 }
toppingList = [ 'Anchovies', 'Bacon', 'Bell Peppers', 'Black Olives',
'Chicken', 'Ground Beef', 'Jalapenos', 'Mushrooms',
'Pepperoni','Pineapple', 'Spinach']
pickupCost = 0 deliveryCost = 5.0
running = True
def pick_or_delivery():
global delivery
print('\nWill this be for pick up or delivery?')
delivery = input("P - pick up / D - delivery")
delivery = delivery.title() # changes the letter inputted to an upper case.
print(f'This order will be for {delivery}')
if delivery == "D":
while running == True:
global customerName
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:
global customerPhoneNumber
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:
global streetName
streetName = input("Street 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
elif delivery == "P":
while running == True:
global customerName
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:
print("Please enter P or D")
customerName = customerName.title()
break
while running == True:
global customerPhoneNumber
customerPhoneNumber = input("\nEnter a phone number we can contact you at: ")
customerName = customerName.title()
if not re.match("^[0-9 ]*$", customer_telephone):
print("Please use numbers only")
elif len(customer_telephone) == 0:
print("Please enter a valid input")
else:
break
else:
print("Please enter P or D ")
pick_or_delivery()
pick_or_delivery()
When I run this code I receive the following:
SyntaxError: name 'customerName' is used prior to global declaration
I know the issue is in my global variables, however in my code I am placing the global variable before it is being called. So I am a little confused. Is the placement incorrect? If so, where should it go?

I think it is because you have globalised customerName within your if statements. Try and create a variable called customerName at the start of your function and give it a blank value, then globalise it at the start of your function.

Related

Why does my validation attempt in python accept letters, when I request it to only accept integers and floats? [duplicate]

This question already has answers here:
Checking if a string can be converted to float in Python
(24 answers)
Closed 1 year ago.
I was recently working on some programming challenges to increase my proficiency in python until I came to a dead end with one of the challenges. The challenge is to allow the user to input: the hourly wage of a worker; the bonus pay for each item made; the number of hours worked; the number of items made. I decided to add some validation to my program but ran into an error when checking if the bonus pay was a number or decimal. My code for the program is as follows:
hourly_pay = input("Please enter the rate of pay for 1 hour: ")
if hourly_pay.isnumeric() == False:
while hourly_pay.isnumeric() == False:
print("Invalid input")
hourly_pay = input("Please enter the rate of pay for 1 hour: ")
bonus_pay = input("Please enter the bonus pay for each car made (in £'s): ")
if bonus_pay.isnumeric() == False and bonus_pay.isdecimal == False:
while bonus_pay.isnumeric() == False or bonus_pay.isdecimal() == False:
print("Invalid input")
bonus_pay = input("Please enter the bonus pay for each car made (in £'s): ")
hours_worked = input("Please enter the number of hours worked: ")
if hours_worked.isnumeric() == False or int(hours_worked) > 15:
while hours_worked.isnumeric() == False or int(hours_worked) > 15:
print("Invalid input")
hours_worked = input("Please enter the number of hours worked: ")
cars_made = input(f"Please enter the number of cars made in {hours_worked} hours: ")
if cars_made.isnumeric() == False:
while cars_made.isnumeric() == False:
print("Invalid input")
cars_made = input(f"Please enter the number of cars made in {hours_worked}: ")
total_pay = (int(hourly_pay) * int(hours_worked)) + (float(bonus_pay) * int(cars_made))
print(f"The pay owed is £{total_pay}")
The issue is with the following piece of code:
bonus_pay = input("Please enter the bonus pay for each car made (in £'s): ")
if bonus_pay.isnumeric() == False and bonus_pay.isdecimal == False:
while bonus_pay.isnumeric() == False or bonus_pay.isdecimal() == False:
print("Invalid input")
bonus_pay = input("Please enter the bonus pay for each car made (in £'s): ")
Every time I enter a letter, the if statement accepts it and does not start the loop.
I was wondering if anyone knew what I did wrong and if they could help me fix it?
Your error is because you are not calling the isdecimal() method in this piece of code:
if bonus_pay.isnumeric() == False and bonus_pay.isdecimal == False:
when should it be:
if bonus_pay.isnumeric() == False and bonus_pay.isdecimal() == False:

How to loop same variable with different result

Hi I've got a school project which requires me to code a program that asks a user for their details it will then ask what them what size pizza they want and how many ingredients. It will then ask if they want another pizza. It will repeat this until they say no or they have six pizzas.
I don't really know how to explain my issues but I don't know how to loop the code so it asks for another pizza and each one has a different size and amount of toppings. I also don't know how I would print it.
Sorry if this is asking a lot or its confusing to understand or if the code is just painful to look at ahaha.
Thanks in advance.
CustomerName = input("Please input the customers name: ")
CustomerAddress = input("Please input the customers address: ")
CustomerNumber = input("Please input the customers number: ")
while True:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ")
try:
PizzaSize = str(PizzaSize)
if PizzaSize == "Small" or "Medium" or "Large":
break
else:
print("Size not recognized")
except:
print("Invalid input")
if PizzaSize == "Small":
SizeCost = 3.25
elif PizzaSize == "Medium":
SizeCost = 5.50
elif PizzaSize == "Large":
SizeCost = 7.15
print(SizeCost)
while True:
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
ExtraToppings = float(ExtraToppings)
if ExtraToppings >= 0 and ExtraToppings <= 4:
break
else:
print("Please insert a number over 0")
except:
print("Input not recognised")
if ExtraToppings == 1:
ToppingCost = 0.75
elif ExtraToppings == 2:
ToppingCost = 1.35
elif ExtraToppings == 3:
ToppingCost = 2.00
elif ExtraToppings >= 4:
ToppingCost = 2.50
else:
print("Number not recognized")
print(ToppingCost)
``
First of all, you should put the code from the second while loop in the first. There is no need for two while true loops. Then instead of
while True:
just put
pizza_count = 0 # how many pizzas they have
wantsAnotherPizza = True
while pizza_count < 6 and wantsAnotherPizza: # while they have less than 6 pizzas and they want another one
pizza_count += 1 # increase pizza_count as they order another pizza
# ... your code here from both of the while loops
x = input("Do you want another pizza? (Y/N)")
if x == "N" or x == "n":
global wantsAnotherPizza
wantsAnotherPizza = False:
You can modify your code like this. I thing you can simply your conditionals by using dictionaries. Try this
from collections import defaultdict
customer_order = defaultdict(list)
customer_order['CustomerName'] = input("Please input the customers name: ")
customer_order['CustomerAddress'] = input("Please input the customers address: ")
customer_order['CustomerNumber'] = input("Please input the customers number: ")
pizza_size ={
'small':3.25,
'medium': 5.50,
'large': 7.15
}
toppins= {'1': 0.75,
'2':1.35,
'3':2.00,
'4':2.50,
}
order = int(input("How many orders would you like to make: "))
while order:
PizzaSize = input("Please input pizza size, Small/Medium/Large: ").lower()
ExtraToppings = input("Any extra toppings, 0/1/2/3/4+ ? ")
try:
if PizzaSize in pizza_size:
size_cost= pizza_size[PizzaSize]
if ExtraToppings:
ToppingCost= toppins[ExtraToppings]
else:
print("Number not recognized")
continue
customer_order['order'].extend([{'size':PizzaSize,'toppings': ToppingCost}])
order -= 1
else:
print("Size not recognized")
continue
except Exception as msg:
print("Invalid input", msg)
continue
else:
print('Your order is complete')
print(customer_order)

User options and validation

I am trying to get the user to input either 1, 2, or 3. If none of the numbers are entered an error message will be displayed and the program will ask for input again.
How do i identify if what the user typed is either 1,2, or 3?
This is what i currently have.
while True:
try:
userInput = input("Enter a number: ")
if userInput not in range(1,4):
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
elif userInput.isdigit('1'):
print('1')
elif userInput.isdigit('2'):
print('2')
else:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
If you want your input to be in range(1, 4), it needs to be an int, not a str (which is what's returned by input():
while True:
try:
userInput = int(input("Enter a number: "))
assert userInput in range(1, 4)
except:
print('Sorry, invalid entry. Please enter a choice from 1 to 3.')
if userInput == 1:
print('1')
if userInput == 2:
print('2')
if userInput == 3:
print('Thank you for using the Small Business Delivery Program! Goodbye.')
break
You have to check values of the same type. Your code compares string and int. You also need to work on the syntax of basic statements: if <condition>: except: isn't legal. Keep it simple:
userInput = None
while userInput not in ['1', '2', '3']:
userInput = input("Enter a number: ")

Using Variables From Other Functions

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.

Invalid syntax error on the elif statement

I'm writing this program that lets users choose an option to display, change,add, remove, write or quit
I keep getting invalid syntax error on this elif statement in my program and i dont know why?
DISPLAY = 'D'
CHANGE = 'C'
ADD = 'A'
REMOVE = 'R'
WRITE = 'W'
QUIT = 'Q'
#main function
def main ():
print()
print()
print('\t Wombat Valley Tennis Club')
print('\t Member Register')
print('\t =======================')
main_dic = {}
with open ('wvtc_data.txt','r')as x:
for line in x:
line = line.rstrip ('\n')
items = line.split (':')
key,value = items[0], items[1:]
main_dic[key] = values
choice = input('choice: ')
while choice != QUIT:
choice = get_menu_choice()
if choice==DISPLAY:
display(main_dic)
elif choice==CHANGE:
change(main_dic)
elif choice== REMOVE:
remove (main_dic)
elif choice==WRITE:
write(main_dic)
def get_menu_choice():
print()
print("\t\t Main Menu")
print()
print('\t<D>isplay member details')
print('\t<C>hange member details')
print('\t<A>dd a new member')
print('\t<R>emove a member')
print('\t<W>rite updated details to file')
print('\t<Q>uit')
print()
print('Your choice (D, C, A, R, W OR Q)?\t[Note: Only Uppercase]')
print()
choice = input("Enter your choice: ")
while choice < DISPLAY and choice < CHANGE or choice > QUIT:
choice = input ('Enter your choice: ')
return choice
def display(main_dic):
name = input('Type the name of the member:')
print()
print (main_dic.get(name, 'not found!'))
print()
print()
def change(main_dic):
name=input("Enter the member number")
print()
print(main_dic.get(name,'not found!'))
print()
NAME = 1
EMAIL = 2
PHONE = 3
print('Please select')
print('==============')
print('Change Name<1>')
print('Change E-mail<2>')
print('Change Phone Number<3>')
print()
if choose == NAME:
new_name = input('Enter the name: ')
print()
print("Data has been changed")
main_dic[name][0]=new_name
print (mem_info[name])
print()
elif choose == EMAIL:
new_email=input('Enter the new email address:')
print ('Email address has been changed')
#change the data
main_dic[name][1]=new_email
print(mem_info[name])
print()
elif choose == PHONE:
new_phone = int (input('Enter the new phone number'))
print ("phone number has been changed")
main_dic[name][2]=new_phone
print(main_dic[name])
print
def write(main_dic):
print()
name = input ("Enter the name of a member:")
print()
print (mem_info.get(name,'Not found!'))
print()
main()
main()
Also any help or suggestions in making this code work are appreciated.
It's a formatting problem. The elifs have to start in the same column as the if to which they belong.
Example
if something:
do_somtething()
elif something_else:
do_the_other_thing()

Categories