Error working with defining and receiving values - python

Hello here is my code:
def main():
#Define Variables
HomesSold = [0]
Amount = 0
HomePrice = [0]
Amount = GetAmount(Amount)
HomesSold = AmountHomesSold(Amount)
#print(HomesSold)
def GetAmount (Amount):
global amount
ConvertAmount = float()
ErrorFlag = False
Amount = input("Enter the amount of homes sold this year:")
while not Amount.isdigit():
Amount = input("Please try again, make sure you are entering a positive number (No commas needed): ")
print("The amount of houses sold were: ",Amount)
ConvertAmount = float(Amount)
return ConvertAmount
def AmountHomesSold(HomePrice):
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
def GetHomePrice():
HomePrice = input("How much did the homes sell for?")
while not HomePrice.isdigit():
HomePrice = input("Please try again, make sure you are entering a positive number (No commas needed): ")
return HomePrice
main()
So when I try to set my while statement for index < amount, I keep getting an error saying amount is not defined when it is earlier on in my code. Is there a way I can receive that number?

You have to declare "Amount" as a global variable in "AmountHomesSold()" in order to use its value. Otherwise, it will look for a local variable named "Amount" in "AmountHomesSold()" (and there isn't one defined in that function).
Note: I added "global Amount" on the second line to allow the function to use "Amount" as a global variable.
def AmountHomesSold():
global Amount
HomePrice = 0
index = 0
while (index < Amount):
HomePrice = GetHomePrice()
HomesSold[index] = HomePrice
index = index + 1
print(HomePrice)
return HomePrice
For more information, see Use of "global" keyword in Python.

Related

Slot Machine generator in python , two functions are'nt working ( def get_slot_,machine_spin , def print_slot_machine )

import random
MIN_LINES = 1
MAX_LINES = 3
MAX_BET = 100
MIN_BET = 1
ROW = 3
COL = 3
symbol_count = {
"A":2,
"B":4,
"C":6,
"D": 8,
}
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = [[],[],[]]
for _ in range(cols):
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
columns.append(value)
columns.append(columns)
return columns
def print_slot_machine(colmuns):
for row in range(len(colmuns[0])):
for i , colmun in enumerate(colmuns):
if i != len(colmun) - 1:
print(colmun[row], end="|")
else:
print(colmun[row], end="")
print()
def deposit():
amount = input("inter the amount of deposit you'd like to add ")
if amount.isdigit():
amount = int(amount)
while amount > 0:
break
else: print("amount must be more than 0")
else: print("Please enter a number ")
return amount
def get_number_of_lines():
lines = input("inter the amount of lines you'd like to add ")
if lines.isdigit():
lines = int(lines)
while MIN_LINES <= lines <= MAX_LINES:
break
else: print("amount must be between 1~3")
else: print("Please enter a number ")
return lines
def get_bet():
while True:
amount = input("Inter the amount of deposit you'd like to bet \n")
if amount.isdigit():
amount = int(amount)
while MIN_BET <= amount <= MAX_BET:
break
else:
print(f"The amount must be between ${MIN_BET}and ${MAX_BET}\n ")
else:
print("Please enter a number ")
return amount
def main():
balance = deposit()
lines = get_number_of_lines()
while True:
bet = get_bet()
total_bet = bet *lines
if total_bet> balance:
print(f"you dont have enough to bet on that amount , your current balance is {balance}")
else:
break
print(f"you're betting {bet},on {lines} lines . total bet is = ${total_bet}")
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
main()
I tried changing the two lines in many different ways but it didnt work plz help
slots = get_slot_machine_spin(ROW, COL,symbol_count)
print_slot_machine(slots)
i got this code from a utube video called (Learn Python With This ONE Project!) i wrote the same code as but when he excute the code it shows him the Slot machine results ( abcd ) while am not getting it , i hope my question was clear ,,, all i want is to make the functions work and show the results of the random choices
Your problems are all in the get_slot_machine_spin function. Did you ever do a basic debug print of what it returns? You would have immediately seen that it was wrong.
Look at what you're asking. You're creating columns with three empty lists. You then generate a random thing and add it to THAT list, So, after three runs, you'd have [[], [], [], 'A', 'C', 'D']. Then you append THAT list to ITSELF, and repeat. When you see something like columns.append(columns), that's an immediate indication that something is wrong.
You need to create a separate list to hold the individual column values, then you append that list to your master column list, which should start out empty. Like this:
def get_slot_machine_spin(rows,cols,symbols):
all_symbols = []
for symbol , symbol_count in symbols.items():
for _ in range(symbol_count):
all_symbols.append(symbol)
columns = []
for _ in range(cols):
row = []
current_symbols = all_symbols[:]
for _ in range(rows):
value = random.choice(current_symbols)
current_symbols.remove(value)
row.append(value)
columns.append(row)
print(columns)
return columns

Solving a purchasing algorithm program

So, I'm stuck at the moment.
I'm creating a program to calculate the complete sale if multiple, or singular, items are purchased. The program is also supposed to calculate a discount threshold and a state-sale's tax with the purchase. I can get the program to function, however, my end result is 0.0 dollars despite entries made. At this point, I can identify it is multiplying SOMETHING by 0, which I assume is the tax input, but I am at a total loss on how to correct this issue. Below is the code used.
#declarations
A_STATE_TAX = float(.056)
C_STATE_TAX = float(.029)
N_STATE_TAX = float(.05125)
U_STATE_TAX = float(.047)
state = ''
tax = float()
completeSale = ()
sockPrice = int(5)
sandalPrice = int(10)
shoePrice = int(20)
bootPrice = int(30)
quantityShoes = int()
quantitySocks = int()
quantityBoots = int()
quantitySandals = int()
quantityTotal = int()
quantityTotal = int(quantityTotal)
basePriceSocks = (quantitySocks * sockPrice)
basePriceShoes = (quantityShoes * shoePrice)
basePriceBoots = (quantityBoots * bootPrice)
basePriceSandals = (quantitySandals * sandalPrice)
baseTotal = int(basePriceSocks + basePriceShoes + basePriceBoots +basePriceSandals)
discount = float()
discountAnswer = (baseTotal * discount)
purchaseWithoutTax = baseTotal - (baseTotal * discount)
taxAnswer = purchaseWithoutTax * tax
#mainbody
print("This algorithm will calculate your purchase.")
#housekeeping()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
print("How many socks?")
input(quantitySocks)
print("Boots?")
input(quantityBoots)
print("And sandals?")
input(quantitySandals)
#purchaseinfo()
quantityTotal = (quantityShoes + quantityShoes + quantityBoots + quantitySandals)
if quantityTotal < 6:
discount = 0
elif quantityTotal > 6 and quanityTotal < 10:
discount = .10
else:
discount = .20
purchaseWithoutTax = baseTotal - (baseTotal * discount)
#stateTax()
print("Please choose the following state: Arizona, New Mexico, Colorado or Utah.")
input(str(state))
if state == "arizona":
tax = A_STATE_TAX
elif state == "new mexico":
tax = N_STATE_TAX
elif state == "colorado":
tax = C_STATE_TAX
else:
tax = U_STATE_TAX
completeSale = (purchaseWithoutTax * tax) - taxAnswer
#endOfJob()
print(format(completeSale, '.2f'))
print("Your total is ", format(completeSale, '.2f'), " dollars.")
print("Thank you for your patronage.")
The main issue is that your baseTotal = 0 initially. And baseTotal = 0 because your quantities (e.g., quantityShoes) are initially 0. You shouldn't initialize values with int(), you should use 0 instead because it is more explicit. You multiply values with baseTotal so in the end you will get 0.
And as another answer mentions, you are using input incorrectly. For numeric quantities, you should convert the result of input to float or int, because input returns strings. You should also save the output to a variable name.
quantityShoes = int(input("How many shoes?"))
You can clean up your code by using dictionaries. That might help with debugging. Instead of having multiple quantity___ variables, you can use a dictionary that stores quantities (and prices, taxes, etc.).
state_taxes = {
"arizona": 0.056,
"colorado": 0.029,
"new mexico": 0.05125,
"utah": 0.047,
}
prices = {
"sock": 5,
"sandal": 10,
"shoe": 20,
"boot": 30,
}
input() doesn't work the way you used it. The argument that goes in input()
is printed before the user gives input. You did the equivalent of:
quantityShoes = int()
print("How many shoes do you wish to purchase?")
input(quantityShoes)
The first line sets quantityShoes equal to the default integer, which is 0. The second line prints that text. The third line line prints that number and waits for user input. You want to do something like:
quantityShoes = int(input("How many shoes do you wish to purchase?"))

Python splitting code into functions [duplicate]

This question already has answers here:
Using global variables in a function
(25 answers)
Parameter vs Argument Python [duplicate]
(4 answers)
Closed 5 years ago.
Sorry about the length of this but I figured more info is better than not enough!!
I'm trying to split the (working) piece of Python code into functions to make it clearer / easier to use but am coming unstuck as soon as i move stuff into functions. It's basically a password generator which tries to only output a password to the user once the password qualifies as having a character from all 4 categories in it. (Lowercase, uppercase, numbers and symbols).
import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!#$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))
while True:
lowerasscii_score = 0
upperascii_score = 0
numberedstring_score = 0
symbol_score = 0
password_as_list = []
while len(password_as_list) < password_length:
char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
password_as_list.append(char)
for x in password_as_list:
if x in lowerasciis:
lowerasscii_score +=1
elif x in upperasciis:
upperascii_score +=1
elif x in numberedstrings:
numberedstring_score +=1
elif x in symbols:
symbol_score +=1
# a check for the screen. Each cycle of the loop should display a new score:
print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score
if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
password = "".join(password_as_list)
print password
break
And here is my attempt at splitting it. When i try to run the below it complains of "UnboundLocalError: local variable 'upperascii_score' referenced before assignment" in the scorepassword_as_a_list() function
import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!#$%^&*()[]"
password_length = int(raw_input("Please enter a password length: "))
lowerasscii_score = 0
upperascii_score = 0
numberedstring_score = 0
symbol_score = 0
password_as_list = []
def genpassword_as_a_list():
while len(password_as_list) < password_length:
char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
password_as_list.append(char)
def scorepassword_as_a_list():
for x in password_as_list:
if x in lowerasciis:
lowerasscii_score +=1
elif x in upperasciis:
upperascii_score +=1
elif x in numberedstrings:
numberedstring_score +=1
elif x in symbols:
symbol_score +=1
# give user feedback about password's score in 4 categories
print lowerasscii_score, upperascii_score, numberedstring_score, symbol_score
def checkscore():
if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
return 1
else:
return 0
def join_and_printpassword():
password = "".join(password_as_list)
print password
while True:
genpassword_as_a_list()
scorepassword_as_a_list()
if checkscore() == 1:
join_and_printpassword()
break
The primary issue here is that you need to keep track of the scope of the various variables that you're using. In general, one of the advantages of splitting your code into functions (if done properly) is that you can reuse code without worrying about whether any initial states have been modified somewhere else. To be concrete, in your particular example, even if you got things working right (using global variables), every time you called one of your functions, you'd have to worry that e.g. lowerassci_score was not getting reset to 0.
Instead, you should accept anything that your function needs to run as parameters and output some return value, without manipulating global variables. In general, this idea is known as "avoiding side-effects." Here is your example re-written with this in mind:
import random
import string
lowerasciis = string.ascii_letters[0:26]
upperasciis = string.ascii_letters[26:]
numberedstrings = str(1234567809)
symbols = "!#$%^&*()[]"
def genpassword_as_a_list(password_length):
password_as_list = []
while len(password_as_list) < password_length:
char = random.choice(lowerasciis+upperasciis+numberedstrings+symbols)
password_as_list.append(char)
return password_as_list
def scorepassword_as_a_list(password_as_list):
lowerasscii_score = 0
upperascii_score = 0
numberedstring_score = 0
symbol_score = 0
for x in password_as_list:
if x in lowerasciis:
lowerasscii_score +=1
elif x in upperasciis:
upperascii_score +=1
elif x in numberedstrings:
numberedstring_score +=1
elif x in symbols:
symbol_score +=1
# give user feedback about password's score in 4 categories
return (
lowerasscii_score, upperascii_score, numberedstring_score,
symbol_score
)
def checkscore(
lowerasscii_score, upperascii_score, numberedstring_score,
symbol_score):
if lowerasscii_score >= 1 and upperascii_score >= 1 and numberedstring_score >= 1 and symbol_score >=1:
return 1
else:
return 0
def join_and_printpassword(password_as_list):
password = "".join(password_as_list)
print password
password_length = int(raw_input("Please enter a password length: "))
while True:
password_list = genpassword_as_a_list(password_length)
current_score = scorepassword_as_a_list(password_list)
if checkscore(*current_score) == 1:
join_and_printpassword(password_list)
break
A few notes on this:
Notice that the "score" variables are introduced inside the scorepassword_as_list function and (based on the scoping rules) are local to that function. We get them out of the function by passing them out as a return value.
I've used just a bit of magic near the end with *current_score. Here, the asterisk is used as the "splat" or "unpack" operator. I could just as easily have written checkscore(current_score[0], current_score[1], current_score[2], current_score[3]); they mean the same thing.
It would probably be useful to read up a bit more on variable scoping and namespaces in Python. Here's one guide, but there may be better ones out there.

How I get a variable defined in for loop outside in the loop? -Python

When I run this Python code I get a NameError. But in this code I'm trying to get a variable defined in a for loop (get) to use in outside of the loop. How can I use this variable (get) outside in for loop?
file = open("f:/py/price.txt", "r")
valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
idNumber = int(input("Enter Id number: "))
for line in file:
if line.startswith(str(idNumber)):
get = line.split("=")[1]
break
quantity = int(input("Enter qantity: "))
cal = quantity * int(get)
totalCst += cal
itmCnt += quantity
print (totalCst)
Just initialize the variable before the loop. Also the break command was out of the if.
Try:
file = open("f:/py/price.txt", "r")
valRange = 0
cal = 0
totalCst = 0
itmCnt = 0
while (valRange < 10):
idNumber = int(input("Enter Id number: "))
get = 0
for line in file:
if line.startswith(str(idNumber)):
get = line.split("=")[1]
break
quantity = int(input("Enter qantity: "))
cal = quantity * int(get)
totalCst += cal
itmCnt += quantity
print (totalCst)
Indent the break more.
for line in file:
if line.startswith(str(idNumber)):
get = line.split("=")[1]
break
Also what if there are no matching lines? get won't have a value then. Make sure you skip the subsequent code if no lines matched.

why am I getting this python syntax indexerror

I am new to python and programming in general. I have received many syntax errors in my program. most have been Index errors. When I run it now what I get is:
"Traceback (most recent call last):
File "C:\Python33\HW3 playing around.py", line 133, in <module>
Main()
File "C:\Python33\HW3 playing around.py", line 32, in Main
EmployeeNumbers()
File "C:\Python33\HW3 playing around.py", line 69, in EmployeeNumbers
Sal[Index] = float(input("Enter Employee salary here: "))
IndexError: list assignment index out of range"
I have no idea how to solve both this error and many others that this program has, any help would be appreciated.
-Jacob
# Description: This program will Calculate the Average, Maximum, and Minimum Salaries of employees
#Declare Variables
EmpNum = 0
SalAVG = 0
Index = 0
SalTot = 0
# Start Main
def Main():
# Get Number of employees
EmpNum = int(input("Enter the number of employee's here: "))
if EmpNum <=0:
print("Please enter positive number")
while Index < EmpNum:
# Call EmployeeNames
global Name
global Index
global SalTot
Name = [Index]
EmployeeNames()
# Call EmployeeNumbers
global Sal
Sal = [Index]
EmployeeNumbers()
# Calculate SalTot
SalTot = SalTot + Sal[Index]
# Increase Index
Index = Index + 1
# Calculate and output AVG
SalAVG = SalTot / Index
print("The average salary is $", SalAVG)
# Call and output Maximum
Maximum()
print("The highest paid employee is ", EmpName, " With a salary of $")
# Call and output Minimum
global Temp
global Switch
Minimum
print("The Lowest paid employee is ", EmpName, " With a salary of $")
# Arrays
# EmployeeNames array
def EmployeeNames():
# Bind global parts
global Name
global Index
# Run EmployeeNames
Name[EmpNum] = str(input("Enter employee name here: "))
# EmployeeNumbers Array
def EmployeeNumbers():
#Bind Global parts
global Sal
#Run EmployeeNumbers
Sal[Index] = float(input("Enter Employee salary here: "))
if Sal[EmpNum] > 200000:
print("Please enter lower salary")
Sal[EmpNum] = float(input("Enter Employee salary here: "))
if Sal[EmpNum] < 0:
print("Please enter positive number")
Sal[EmpNum] = float(input("Enter Employee salary here: "))
# Maximum array
def Maximum():
# Bind global parts
global Temp
global Switch
global Name
Index = 1
Temp = 0
Switch = 1
while Switch > 0:
Index = 1
if Sal[Index] > Sal[Index + 1]:
# Call NameSwitch
global TempName
global Name
NameSwitch()
Temp = Sal[Index]
Sal[Index] = Sal[Index + 1]
Sal[Index + 1] = Temp
Switch = Switch + 1
Index = Index + 1
Switch = 1
# Minimum array
def Minimum():
# Bind global parts
global Temp
global Switch
global Name
Index = 1
Temp = 0
Switch = 1
while Switch > 0:
Index = 1
if Sal[Index] < Sal[Index + 1]:
# Call NameSwitch
global TempName
global Name
NameSwitch()
Temp = Sal[Index]
Sal[Index] = Sal[Index + 1]
Sal[Index + 1] = Temp
Switch = Switch + 1
Index = Index + 1
Switch = 1
# NameSwitch array
def NameSwitch():
#Bind global parts
global TempName
global Name
TempName = ""
TempName = Name[Index]
Name[Index] = Name[Index + 1]
Name[Index + 1] = TempName
Main()
I'm not going to fix your code, but your problem can be simplified to:
>>> some_list = []
>>> some_list[0] = "Hello World"
IndexError: list assignment index out of range
To fix it, you need to either start the list with an initial size:
>>> some_list = [None]
>>> some_list[0] = "Hello World"
Or append to the empty list:
>>> some_list = []
>>> some_list.append("Hello World")
Your major problem stems from the use of global variables. Instead of creating global variables, define your function with the variables as arguments like this:
def Maximum(Temp,Switch,Name):
Then call the function like this
Maximum(Temp,Switch,Name)
That way you can keep track of everything your function will need when defining it.
Back to your error, the problem is that Index is not defined in the function. recreate the function header like so:
def EmployeeNumbers(sal,index):
and in main, call it like this:
EmployeeNumbers(sal, index)
Last, define all of your variables inside main, so you do not need to pass them into main when you call it.

Categories

Resources