Traceback error for variable not assigned - python

I am getting an error that I don't understand in this short program. The errors read
Traceback (most recent call last):
line 40, in <module>
main()
line 35, in main
totalCost = cleanCost * sizeFactor
UnboundLocalError: local variable 'cleanCost' referenced before assignment
It says that cleanCost is not assigned, but I believe I did assign it in the set price based on cleaning type area unless I am mistaken. If that is not properly assigned how do I assign it so that the variable can change based on input?
def main():
#Display welcome message
print ("Hello, welcome to Hannah’s Cleaning Service!")
#prompt user for house size
houseSize = int(input("How many bedrooms is your home?"))
#prompt user for type of cleaning
cleanType = str(input("What type of cleaning would you like \n 1=floors, \n 2=windows, \n 3=bathrooms, or \n 4=dusting?"))
#set price based on cleaning type
if (cleanType == 1):
cleanCost = 60
elif (cleanType == 2):
cleanCost = 50
elif (cleanType == 3):
cleanCost = 40
elif (cleanType == 4):
cleanCost = 30
#set multiplication factor based on house size
if (houseSize <= 2):
sizeFactor = 1
elif (houseSize == 3):
sizeFactor = 2
elif (houseSize >= 4):
sizeFactor = 3
#Calculate total price
totalCost = cleanCost * sizeFactor
#Display total cost
print ("Your total is $totalCost")
main()

You are running into an issue of scope/visibility. Since in your initial iteration of the code, "cleaningCost" is going in and out of scope within the various "if" tests". Following, is a tweaked version of your code with the two work variables initialized.
def main():
#Display welcome message
print ("Hello, welcome to Hannah’s Cleaning Service!")
#prompt user for house size
houseSize = int(input("How many bedrooms is your home?"))
#prompt user for type of cleaning
cleanType = str(input("What type of cleaning would you like \n 1=floors, \n 2=windows, \n 3=bathrooms, or \n 4=dusting?"))
cleanCost = 0 # Need to be initialized at this scope level
sizeFactor = 1
#set price based on cleaning type
if (cleanType == "1"): # Need to be checked as alphanumeric values
cleanCost = 60
elif (cleanType == "2"):
cleanCost = 50
elif (cleanType == "3"):
cleanCost = 40
elif (cleanType == "4"):
cleanCost = 30
#set multiplication factor based on house size
if (houseSize <= 2):
sizeFactor = 1
elif (houseSize == 3):
sizeFactor = 2
elif (houseSize >= 4):
sizeFactor = 3
#Calculate total price
totalCost = cleanCost * sizeFactor
#Display total cost
print ("Your total is", totalCost)
main()
Also, note that I tweaked the "cleanType" tests to be alphanumeric tests since your input statement sets up variable "cleanType" as a string.
With those tweaks, following was some sample output on my terminal.
#Una:~/Python_Programs/Cleaning$ python3 Cleaning.py
Hello, welcome to Hannah’s Cleaning Service!
How many bedrooms is your home?4
What type of cleaning would you like
1=floors,
2=windows,
3=bathrooms, or
4=dusting?1
Your total is 180
The big take-away is the scope of variables. Give those tweaks a try.

Related

python vending machine program- I have two questions

I'm creating a vending machine program that simulates the action through a loop that ends when the user enters 0 but it doesn't print "0 to cancel" in the output. I tried putting it at the top before the if statements but, I want to be able to enter an input after the if statements are printed. So how could I fix that?
It says that user_val is undefined when I equal it to 0 but I did define it at the bottom.
If someone could help please!
print("*********************************")
print("Welcome to Vending Machine Bravo!")
print("*********************************")
print("If you would like to make a selection, please insert the appropriate currency into the machine.")
# Currency deposit [tag:tag-name]
num_5Dollars = 5.00
num_Dollars = 1.00
num_Quarters = .25
num_Dimes = .10
num_Nickels = .05
num_Pennies = .01
currency = [num_5Dollars, num_Dollars, num_Quarters, num_Dimes, num_Nickels, num_Pennies]
if num_5Dollars == 5.00:
print("5.00 for $5 bills")
if num_Dollars == 1.00:
print("1.00 for $1 bills")
if num_Quarters == .25:
print(".25 for Quarters")
if num_Dimes == .10:
print(".10 for dimes")
if num_Nickels == .05:
print(".05 for nickels")
if num_Pennies == .01:
print(".01 for pennies")
if int(float(user_val)) == 0:
print("0 to cancel")
user_val = float(input())
Your user_val defined under the line if int(float(user_val)) == 0.
And if you want to say to user 0 to cancel, you don't need to check int(float(user_val)) == 0, because while this doesn't happened, it won't print this instruction.
So basically, you need to remove if int(float(user_val)) == 0: line

Luhn's algorithm works for all credit cards except for AMEX cards (Python3) (cs50/pset6/credit)

I'm trying to create a program that checks whether the credit card number the user inputed is either invalid, or from AMEX, MASTERCARD, or VISA. I'm using Luhn's formula. Here is a site that contains the explanation to the formula I'm using: https://www.geeksforgeeks.org/luhn-algorithm/
It works with all credit card numbers, except credit cards from AMEX. Could someone help me?
Here is my code:
number = input("Number: ")
valid = False
sumOfOdd = 0
sumOfEven = 0
def validation(credit_num):
global sumOfOdd
global sumOfEven
position = 0
for i in credit_num:
if position % 2 != 0:
sumOfOdd += int(i)
else:
product_greater = str(int(i) * 2)
if len(product_greater) > 1:
sumOfEven += (int(product_greater[0]) + int(product_greater[1]))
else:
sumOfEven += int(product_greater)
position += 1
def main():
if (sumOfOdd + sumOfEven) % 10 == 0:
if number[0] == "3":
print("AMEX")
elif number[0] == "5":
print("MASTERCARD")
else:
print("VISA")
else:
print("INVALID")
print(f"{sumOfOdd + sumOfEven}")
validation(number)
main()
Here are some credit card numbers:
VISA: 4111111111111111
MASTERCARD: 5555555555554444
AMEX: 371449635398431
I've found many different ways to calculate this formula, but I'm not sure if mine is correct.

Loop to add more input

I have 3 more cars that I have but I need to know how to loop things like the car input so it will allow you to input it again if you do the wrong input same thing with the extras so they have to be either 1 or 0.
print("===================================================")
print("==============Car Finance Calculations=============")
print(" Choose your veicle: ")
print(" SUV type 1 ")
print(" Hatch type 2 ")
print(" Sedan type 3 ")
print("===================================================")
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
if caaaaaaaar == 1:
carsvalue = int(input("Please enter you cars value: "))
residual = carsvalue * 0.30
financing = carsvalue - residual
print(" financing value for the car is: ", round(financing,2))
print(" Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r*((r+1)**n))/(((r+1)**n)-1))
print(" Your Montly financing rate is: ", round(Financingcost,2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
print(" If you would like fuel type 1 if not type 0")
print(" If you would like insurance type 1 if not type 0")
print(" if you would like Maintenance type 1 if not type 0")
print("======================================================")
if caaaaaaaar == 1:
x, y, z = [int(x) for x in input("Enter Your extras with spaces:").split()]
print("=======================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost,2))
if x == 0:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost,2))
if y ==0:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ",insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost,2))
if z == 0:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ",maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras,2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING,2))
You want to use a while loop.
Like this:
carsEntered = 0
while (carsEntered <= 4):
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
carsEntered += 1
You could also use a for loop instead but that depends on what you want to do.
As per my understanding of the question you want to run an iteration until the user gives the right answer.
In that case, you can use flag variable in while.
flag = False
while(flag is False):
if(condition_statisfied):
flag = True
I suggest that you put your vehicle types in a dictionary:
vehicle_type_dict = {
1: "SUV type",
2: "Hatch type",
3: "Sedan type"
}
and do a while-loop to check if your input is in the dictionary:
while True:
caaaaaaaar = int(input(" Please enter Which car you want to finance: "))
if caaaaaaaar not in vehicle_type_dict:
continue #loop again if input not in the dictionary
#read next line of code if input is in the dictionary
#do something below if input is correct
years = int(input(" enter years of loan either 3 or 4 or 5 Years: "))
break #end loop
My recommendation is to take a functional approach to this problem. You are calling int(input()) multiple times and want to validate the user input before proceeding on to the next lines each time. You can do this in a function that will continue to loop until the input is confirmed as valid. Once the input is validated, you can exit the function's frame by returning the value using the return key word.
# This is the function definition.
# The code in this function does not execute until the function is called.
def prompt_int(
text,
minimum=0,
maximum=1,
error="The value you entered is not valid try again."
):
# when the function is called it will start a second while loop that will keep looping
# until valid input is entered
while True:
try:
val = int(input(text))
if minimum <= val <= maximum:
return val
raise ValueError
except ValueError:
print(error)
# This is the outer while loop. It will keep looping forever if the user so chooses.
while True:
# instead of calling print() a bunch one option is to assign a docstring to a variable
car_prompt = '''
===================================================
==============Car Finance Calculations=============
Choose your veicle:
SUV: 1
Hatch: 2
Sedan: 3
===================================================
Please enter the number for the car you want to finance or 0 to exit:\n
'''
# This is where we first call the function.
# Our docstring will be passed into the function to be used as a prompt.
# We also pass in some args for maximum and minimum params
caaaaaaaar = prompt_int(car_prompt, 0, 3)
# 0 is false so we can exit the while loop if the user enters 0
if not caaaaaaaar:
break
year_prompt = "Enter years of the car loan (3, 4 or 5):\n"
years = prompt_int(year_prompt, 3, 5)
if caaaaaaaar == 1:
val_prompt = "Please enter you cars value:\n"
carsvalue = prompt_int(val_prompt, 0, 2147483647)
residual = carsvalue * 0.30
financing = carsvalue - residual
print("Financing value for the car is: ", round(financing, 2))
print("Intrest rate is 9% ")
n = years * 12
r = 9 / (100 * 12)
Financingcost = financing * ((r * ((r + 1) ** n)) / (((r + 1) ** n) - 1))
print(" Your Montly financing rate is: ", round(Financingcost, 2))
print("================================================================================")
print("Please Choose extras: ")
print("======================================================")
x = prompt_int("If you would like fuel type 1 else type 0:\n")
y = prompt_int("If you would like insurance type 1 else type 0:\n")
z = prompt_int("If you would like Maintenance type 1 else type 0:\n")
print("======================================================")
if x == 1:
print("Yes you want fuel")
fuelcost = 80 * 4.33
print("fuel cost is", round(fuelcost, 2))
else:
print("you dont want fuel as an extra")
fuelcost = 0
print("Fuel cost is: ", fuelcost)
print("=======================================")
if y == 1:
print("yes you want insurance")
insurancecost = (1200 / 12)
print("Insurance cost is: ", round(insurancecost, 2))
else:
print("you dont want insurance")
insurancecost = 0
print("insurance cost is: ", insurancecost)
print("=======================================")
if z == 1:
print("yes you want maintenance")
maintenancecost = (100 * 1)
print("Maintenance cost is: ", round(maintenancecost, 2))
else:
print("you dont want maintenance")
maintenancecost = 0
print("maintenance cost is: ", maintenancecost)
print("=======================================")
total_cost_for_extras = fuelcost + maintenancecost + insurancecost
print("Total cost for the selected extras is: ", round(total_cost_for_extras, 2))
TOTALFOREVERYTHING = total_cost_for_extras + Financingcost
print("Total monthly financing rate is: ", round(TOTALFOREVERYTHING, 2))
elif caaaaaaaar == 2:
# Put your code for car 2 in this block.
# If it is like car 1 code except the value of a few variables
# then make another func
pass
else:
# Car 3 code...
pass

Quit while len(int) < 1

I'm new in python, and I'm trying to make a simple quit, if the Input is empty or less then One int.
I'm getting an error which says - ValueError: invalid literal for int() with base 10: '', when entering nothing, just a enter on launch.
import sys
import os
import getpass
def clear(): return os.system('clear')
ballance = 500.00
# Garage Stockas
Wood_InStock = 600
Weed_InStock = 300
Gun_InStock = 15
Gun_Ammo_InStock = 500 * 30 # X30 Total 15000
# Kainos
Gun_Ammo_Price = 15.50
Wood_Price = 3.50
Weed_Price = 9.50
Gun_Price = 250.50
# Produktai
medis = '~ Elemental Wood ~'
weed = '~ Indoor Kush ~'
gun = '~ Shotgun ~'
gun_ammo = '~ Shotgun ammo 30x ~'
# Inventory
Wood_Inventory = 0
Weed_Inventory = 0
Gun_Inventory = 0
Gun_Ammo_Inventory = 0
# No Money
Not_Enough_Money = '~ Sorry you dont have enough money'
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
Let's look at only this part of the code:
while True:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
The empty user input will be passed to int(), but an empty string cannot be converted to an int! So an error is raised.
What you should instead is to not convert the input to int first, and treat it as a string:
while True:
Shop_Pasirinkimas = input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun))
if len(Shop_Pasirinkimas) < 1:
sys.exit("SOrry")
elif int(Shop_Pasirinkimas) == 1: # convert to int here
clear()
...
int(x,base) function will return the integer object from any number or string. Base defaults to 10. If x is the string, its respective numbers should be within possible values with respect to that base.
As, nothing is entered, it's considered as invalid literal.
Hence, Please use the input as string which can solve the issue easily.
If user doesn't input an integer you will encounter an exception in Shop_Pasirinkimas = int(input(...)). Besides int has no len() so this will also cause error len(Shop_Pasirinkimas). You can do the following to accomplish what you are trying
while True:
try:
Shop_Pasirinkimas = int(input("~ What would you like to buy?\n1. {medis}\n2. {weed}\n3. {gun}\n".format(medis=medis,weed=weed,gun=gun)))
if Shop_Pasirinkimas < 1:
sys.exit("SOrry")
elif Shop_Pasirinkimas == 1:
clear()
WoodPirkimo_Skaic = int(input("How much {medis} would you like to buy? ".format(medis=medis) + "Wood Now in Stock - {woodins}\n".format(woodins=Wood_InStock)))
# Price per wood - 3.50
ballance -= ( Wood_Price * WoodPirkimo_Skaic)
Wood_Inventory += WoodPirkimo_Skaic
Wood_InStock -= WoodPirkimo_Skaic
print("~ In stock of {}, left {}".format(medis,Wood_InStock))
print("~ Successfully bought {}, Your Ballance is {}\n".format(medis,ballance))
print('Inventory:')
print("~ You have {}, of {}\n".format(Wood_Inventory,medis))
Buymore = input("Would you like to buy anything more?... Yes/No\n")
if "Yes" in Buymore or "yes" in Buymore:
continue
elif "No" in Buymore or "no" in Buymore:
break
else:
break
except ValueError:
sys.exit("SOrry")

TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'

I am having trouble with feeding a value into a function, and not having that values type be an int, instead it is a NoneType, which I cannot operate with. Here's the error message I am thrown:
Traceback (most recent call last):
File "NumberGame1.py", line 140, in <module>
main()
File "NumberGame1.py", line 29, in main
result = guessinggame(number)
File "NumberGame1.py", line 92, in guessinggame
if guess - number <= level * 0.1:
TypeError: unsupported operand type(s) for -: 'int' and 'NoneType'
Here is all of the code:
import random
import timeit
def main():
print "\nWelcome to Ethan's Number Guessing Game!"
print "What would you like to do?: \n1. Play game\n2. View High Scores\n3. View Credits"
menuchoice = input()
## choice is Menu Decision
if menuchoice == 1:
difficulty = input("Pick a difficulty!: \n1: Easy\n2: Medium\n3: Hard\n4: Insane\n5. Out of control!\n6. Custom\n")
leveldif = difcalc(difficulty)
## Exits program if you don't choose a difficulty
global level
level = leveldif[0]
difmod = leveldif[1]
number = numbergenerator(level)
result = guessinggame(number)
totalTime = result[0]
tries = result[1]
scorer(tries, totalTime)
elif menuchoice == 2:
## Figure out how to access high scores
print "This feature is currently under development.\n"
elif menuchoice == 3:
print "\nDeveloped by Ethan Houston"
raw_input()
print "\nDeveloped in Python 2.7.9 using Sublime Text 2"
raw_input()
print "\nThanks for playing :)"
raw_input()
## Simple credits reel. Go me
def difcalc(difficulty):
if difficulty == 1:
leveldif = [10, 1]
elif difficulty == 2:
leveldif = [50, 1.5]
elif difficulty == 3:
leveldif = [100, 2]
elif difficulty == 4:
leveldif = [1000, 10]
elif difficulty == 5:
leveldif = [10000, 20]
elif difficulty == 0:
leveldif = [1, 1]
return leveldif
def guessinggame(number):
tries = 1
## Counter for number of attempts at guessing
guess = input("Guess a number between 1 and " + str(level) + "!: ")
## Takes input from user
while guess > level:
guess = input("Above range!\nMake sure to guess between 1 and " + str(level) + "!: ")
## If the user chooses a number above the range, makes you try again until within range
startTime = timeit.default_timer()
## Starts a timer once first valid number is selected
while guess != number:
## While loop that runs as long as guess isn't correct
if guess > number:
if guess - number <= level * 0.1:
guess = input("Too high, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too high, guess again: ")
tries += 1
## Normal behavior
elif guess < number:
if guess - number <= level * 0.1:
guess = input("Too low, close!: ")
tries += 1
## If difference between guess and answer is less than or equal to 10% of level,
## prints different prompt
else:
guess = input("Too low, guess again: ")
tries += 1
## Normal behavior
endTime = timeit.default_timer()
## Takes the time after the correct number is chosen
totalTime = endTime - startTime
## Calculates time difference between start and finish
result = [totalTime, tries]
return result
def numbergenerator(level):
global number
number = random.randint(1, level)
def scorer(tries, totalTime):
print "\nCorrect! It took you " + str(round(totalTime, 2)) + " seconds and " \
+ str(tries) + " tries to guess.\n"
## Once user guesses correct number, program tells how many tries it took, and how long
score = 1/(1+(tries * round(totalTime, 2))) * 1000 * difmod
## Calcualtes score, making lower times and fewer tries yield a higher score
## Difmod takes into account the difficulty
## Multiply by 1000 to make number more readable
print "Score: " + str(round(score, 2)) + "\n"
## Printsthe score, rounded to 1 decimal place
main()
When a python function does not explicitly return anything , it returns None . In your case, you have a function -
def numbergenerator(level):
global number
number = random.randint(1, level)
This does not return anything, instead you set a global variable number .
But when you are calling this function in main() , you do -
number = numbergenerator(level)
And here number is not a global variable (Even if it was a global it wouldn't matter) , so after calling numbergenerator() , since it does not return anything, it returns None , which gets set to number variable, and hence number is None, causing the issue you are having.
I believe you do not need to use global variable there, you should just return the number from numbergenerator() function , example -
def numbergenerator(level):
return random.randint(1, level)

Categories

Resources