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.
Related
I was wondering if there was a way to input 2 items into an array (2 dimensional) at least. One part of the array to hold the name of the person that was golfing, and the other part of the array to hold the score of the person that was playing.
scores = []
playerName = "Cynthia"
playerScore = "72"
scoreEntry = [playerName, playerScore]
The code above shows it being hard coded into it so the resulting would be [Cynthia, 72], but I am trying to figure out how to grab the input from the user and tried applying directly to the array, but it ends up coming out to this below.
How many players: 1
Enter a name: Cynthia
Enter a score: 72
Data written out is: C : y
Data written out is: 7 : 2
This is the output im currently getting
Code below for what I used to get this
def main():
golfFile = open ("golf.dat", 'w')
scores = []
SIZE = getSize()
playerName = getName(scores, SIZE)
playerScore = getScore(scores, SIZE)
scoreEntry = [playerName, playerScore]
scores.append(scoreEntry)
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
golfFile.close()
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName(scores, SIZE):
index = 0
while (index <= SIZE - 1):
nameInput = input("Enter a name: ")
scores.append(nameInput)
index = index + 1
return scores
def getScore(scores, SIZE):
index = 0
while(index <= SIZE - 1):
scoreInput = input("Enter a score: ")
scores.append(scoreInput)
index = index + 1
return scores
main()
Expected output is
[Cynthia, 72]
There is an error that comes up as well
Traceback (most recent call last):
File "d:\Programs\test.py", line 35, in <module>
main()
File "d:\Programs\test.py", line 11, in main
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
TypeError: can only concatenate list (not "str") to list
Also, I do not want to use any libraries at all for this
You're appending to scores in the getName() and getScore() functions, and each of them return the whole scores list. Then you're putting those two references to scores in the scoreEntry list, and then appending that list to scores again. So you've got the lists nested several levels deep, and you never have each name in the same list as the corresponding score.
Instead, you should just read one name and score each time through a single loop. Put those in a scoreEntry tuple, and append that to the scores list.
def main():
scores = []
SIZE = getSize()
for _ in range(SIZE):
playerName = getName()
playerScore = getScore()
scoreEntry = (playerName, playerScore)
scores.append(scoreEntry)
with open ("golf.dat", 'w') as golfFile:
for scoreEntry in scores:
fileLine = scoreEntry [0] + " : " + str(scoreEntry [1]) + "\n"
golfFile.write (fileLine)
print("Data written out is: ", fileLine)
def getSize():
SIZE = int(input("How many players: "))
return SIZE
def getName():
nameInput = input("Enter a name: ")
return nameInput
def getScore():
scoreInput = int(input("Enter a score: "))
return scoreInput
main()
I'm trying to run this code:
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
But I get this error:
Traceback (most recent call last):
File "credit.py", line 15, in <module>
validation(number)
File "credit.py", line 8, in validation
sumOfOdd += i
UnboundLocalError: local variable 'sumOfOdd' referenced before assignment
I'm able to run, but when I input any number it gives me this error
This error occurs because the variable sumOfOdd is not accessible from within the function. You could declare the variable global in the function, but you should be careful using the global statement.
In my opinion, a better way to do this is to supply sumOfOdd as an argument to the function and return the updated variable:
def validation(credit_num, sumOfOdd):
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
validation(number, 0)
# Returns the correct sum.
Or, if you know that the sumOfOdd should always be initialized by zero, you could define the variable locally:
def validation(credit_num):
sumOfOdd = 0
for i in range(len(credit_num)):
if i % 2 != 0:
sumOfOdd += i
return sumOfOdd
Here's a working version of your code.
Note that it now iterates through credit_num as for num in credit_num. If you use for i in range(len(credit_num)) you are iterating through a list of indexes and would need to use if int(credit_num[i]) % 2 != 0, reason being that range(N) returns a list [0, 1, 2... N-1] where for num in credit_num iterates through [1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4] if your input string was 1111222233334444
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
global sumOfOdd
for num in credit_num:
if int(num) % 2 != 0:
sumOfOdd += 1
def main():
print(f"Your credit card number is {number}, it's third digit is {number[2]}")
print(f'sum of odds: {sumOfOdd}')
validation(number)
main()
Note that validation(number) is called in global scope along with main(), hence the global sumOfOdd declaration inside to allow def validation to gain access to that variable.
A different way to write this code to make it more readable would be:
if __name__ == "__main__":
number = input("Number: ")
valid = False
sumOfOdd = 0
def validation(credit_num):
sumOfOddToReturn = 0
for num in credit_num:
if int(num) % 2 != 0:
sumOfOddToReturn += 1
return sumOfOddToReturn
sumOfOdd = validation(number)
print(f"Your credit card number is `{number}`, its third digit is `{number[2]}`.")
print(f'sum of odds: {sumOfOdd}')
The following is my code
n = int(input("please enter a value: "))
board = []
def make_board(n):
global board
max = n * n #the number of tiles in the board
count = 1 #a counter to change the value assigned to each tile
for i in range(n):
board.append([]) #appends a list inside the list of board. Essentially creates a row which is of type list.
for j in range(n):
num = max - count
if num == 0: #the 0 tile will display like a blank space
tile = ' '
elif num < 10: #adds a space to tile values less than 10 for formatting.
tile = ' ' + str(num)
else:
tile = str(num)
board[i].append(tile) #appends a tile value to each row, n number of times.
count += 1
if n%2 == 0:
tempvara = board[n-1][n-2]
tempvarb = board[n-1][n-3]
board[n-1][n-2]=tempvarb
board[n-1][n-3]=tempvara
#TODO
for row in board:
print(' '.join(row))
def find_blank(board):
global counterUNO
global counterDOS
global counterTRES
counterTRES = 0
#TODO
for i in range(n):
tempvari = board[i]
if ' ' in tempvari:
counterUNO = i
for z in board[counterUNO]:
counterTRES = counterTRES + 1
if ' ' in z:
counterDOS = counterTRES-1
break
tupleone = (counterUNO,counterDOS)
return(tupleone)
def find_tile(f):
counterfour = 0
tiles = str(input("tile BUBBER"))
if int(tiles)<10:
tiles = " "+tiles
counterfive = 0
countersixe = 0
countersixe = 0
for i in range(n):
chopstick = board[i]
if tiles in chopstick:
counterfour = i
for z in board[counterfour]:
countersixe = countersixe + 1
if tiles in z:
counterfive = countersixe-1
break
tupleDOS = (counterfour,counterfive)
return(tupleDOS)
def find_next_to_blank(board):
#print("here is the shit")
#print(find_tile(board))
vara = find_tile(board) #sets tile numb tuple to vara
varb = find_blank(board) #yeah
varc = int(tiles)
varaa = int(tiles[0])
varab = int(tiles[1])
varba = board[varaa+1][varab]
varbb = board[varaa][varab+1]
varbc = board[varaa-1][varab]
varbd = board[varaa][varab-1]
varbe = board[varaa+1][varab+1]
varbf = board[varaa-1][varab-1]
make_board(n)
#find_blank(board)
#find_tile(board)
find_next_to_blank(board)
Problem:
Right now I am trying to make a python Tile game where I can shift the numbers. the make board function obviously creates a board, i did it so that there are three lists in a big list and in the three list there are elements
and the find blank function identifies the coordinate of the non existing section of the board
and the find tile function is the function that the user inputs a value and the code identifies what is the coordinate of the tile that we want
So currently I am getting an error because when i am running the find next to blank function (the function is supposed to identify whether or not there is a blank spot next to the value which the user wants to input) i get the following error
Traceback (most recent call last):
File "python", line 149, in <module>
File "python", line 122, in find_next_to_blank
NameError: name 'tiles' is not defined
and i tried making "tiles" variable into a global one but it didn't work at all
The variable tiles is not defined in find_next_to_blank(board). I'd be remiss if I don't say this: consider restructuring your program to avoid using global variables.
Now that's out of the way, if you make tiles global, it ought to work.
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.
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.