variable not defined and function doesn't work - python

Before asking my question, I'll explain what this short piece of code exactly does: first you get a menu where you can make a choice, if you choose 1, it should ask for the watch time (W) views (V) then for the duration of the video (h),(m) and (s). But now when you choose 1 it gives me this error:
Traceback (most recent call last):
File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 72, in <module>
main()
File "C:/Users/Arcky/Desktop/youtube-avarage-watch-time-v2 help.py", line 65, in main
getchoice(Choice)
NameError: name 'Choice' is not defined
so far I can see is Choice defined in the function called choice()
maybe I should use a different name?
If you can help to fix this and let it work, I would be really grateful
here's the full code
def menu():
print('make your choice')
print('1. calculate Av. view duration')
print('2. end this shit')
def choice():
Choice = 0
Choice = (int(input('make a choice... ')))
while Choice <= 0 or Choice >= 3:
print('Error!')
Choice = (int(input('make a choice... ')))
return Choice
def getchoice(Choice):
if Choice == 1:
print(Choice)
getwatchtimeandviews()
def getwatchtimeandviews():
W =int(input("Enter Watch Time: "))
V =int(input("Enter Views: "))
return W, V
def gettimeofvideo():
h =int(input("Enter hours:"))
m =int(input("Enter minutes:"))
if m >=60:
m = m-60
h = h + 1
s =int(input("Enter seconds:"))
if s >=60:
s = s-60
m = m + 1
if m >=60:
m = m-60
h = h + 1
return h, m, s
def calculateviewduration(W,V,h,m,s):
A = W / V
As = A*60
T = (h*3600) + (m*60) + s
P = (As/T)*100
Am = 0
return
def checkinput(As, P, Am):
if As <= 59:
print('Av. view duration:',round(As),'sec','(',round(P,2),'%)')
while As > 59:
Am = Am + 1
As = As - 60
print('Av. view duration:',round(Am),'min', round(As),'sec','(',round(P,2),'%)')
if P > 100:
print('error! value cannot be higher then 100%!')
def stop():
print()
def main():
menu()
choice()
getchoice(Choice)
print ("Enter duration of video:")
gettimeofvideo()
calculateviewduration(W,V,h,m,s)
if __name__ == '__main__':
main()

You should to learn scope of variable.
For example, you defined a choice function, and defined a Choice variable in the choice function, then the Choice variable will effect only in the choice function.
If you want to let some variables effect global, you can define the variable out of funtions, or add global keyword when you define(like global Choice)

The Choice variable you declared is limited to choice function only. If you want to use it globally make it global or define at the top most indentation level

Related

UnboundLocalError: local variable 'sumOfOdd' referenced before assignment in Python3

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}')

While loop not terminating when the condition has been satisified

While programming in Python I got stuck in a case where the while loop is not terminating even after the condition is being satisified then also
the code is as follows:
print('--- Alex\'s Calculator ---')
print('1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT')
x = int(input())
command = ' Enter Your Two numbers To Perform The Operation : '
def ini():
a = int(input())
b = int(input())
return a, b
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
while x < 5:
if x == 1:
print(command)
a, b = ini()
c = a + b
resultoo()
elif x < 5:
break
As kuro specified in the comment, x can't be seen by your while loop because it's local to resultoo().
To solve it easily just add :
return x
at the end of resultoo()
and
x = resultoo()
in your while loop
You can use global var to this, change the this:
def resultoo():
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
into:
def resultoo():
global x
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a,b,c))
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
Explnation:
x is a global argument, that will be the same out of the function closure, but not inside of it, the function has it own params, so if you want to change a global argument that is initalizing outside the function, you will need to call the global statement before, that will make x the global x
When option 5 is entered you want to exit.
I added
import sys
and changed
elif x < 5:
to
elif x == 5:
and added
sys.exit(0)
I also added the getMenu() function
This is the complete code that is working in my editor:
import sys
def ini():
command = ' Enter Your Two numbers To Perform The Operation : '
print(command)
a = int(input())
b = int(input())
return a, b
def resultoo(a, b, c):
result = ' Your Result after Performing The Operation from {} and {} is {}'
print(result.format(a, b, c))
def getMenu(x):
if x == 0:
print("Choose menu item")
x = int(input())
elif x != 0:
print(' Want To Continue If Yes then Enter Your Choice else Press any number exept 1 - 4')
x = int(input())
return x
def main():
x = 0
while x < 5:
print('\n\n1. ADDition')
print('2. SUBstraction')
print('3. MULtiply')
print('4. DIVide')
print('5. EXIT\n')
x = getMenu(x)
if x == 1:
a, b = ini()
c = a + b
resultoo(a, b, c)
elif x == 5:
sys.exit(0)
else:
print("No valid menu item")
if __name__ == '__main__':
print('----------------------------------------------------------------------------------------------------------')
print('-------------------------------------------- Alex\'s Calculator -------------------------------------------')
main()
I also formatted your code (alt+Enter in Pycharm) to comply to PEP8 standards ;)

NameError: name 'recPower' is not defined

I am working on a assignment and am encountering this error. NameError: name 'recPower' is not defined
Write a recursive function called pow(base, power) that takes in two numbers. First number is a base and the second number is a power. The function will return the number raised to the power. Thus, if the number is 2 and the power is 4, the function will return 16. (75 points).
Write a main() function that asks for a number and a power. Then calls the recursive function created in step 1 (15 points).
DO NOT use the algorithm on page 432 of your book:
def: recPower (a, n):
if n == 0:
return 1
else:
factor = recPower (a, n//2)
if n%2 == 0:
return factor * factor
else:
return factor * factor * a
My current code is as follows
def main():
a=input("enter base :")
n=input("enter power :")
print ("Total = ",recPower(a,n))
main()
def recPower (a,n):
if n == 0:
return 1
else:
return a*recPower(a,n-1)
`
The error I get when I run it is :
Traceback (most recent call last):
File ".py", line 7, in
main()
File ".py", line 5, in main
print ("Total = ",recPower(a,n))
NameError: name 'recPower' is not defined
Functions are stored in identifiers. You have to define it first. Try this one:
def recPower(a, n):
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = int(input("enter base :"))
n = int(input("enter power :"))
print ("Total = ", recPower(a, n))
main()
Define your 'run' function after 'recPower'.
As also mentioned you need to convert the strings that are returned from input() into integers or floats, using either int() or float(). When you try to operations like division you'll get TypeError exceptions.
write your method above the main code, because if you write at under the main code method is undefinied
functions must be defined before any are used.
try this code
def recPower(a, n):
# or just a, n = int(a), int(n) is fine
if isinstance(a, str):
a = int(a)
if isinstance(n, str):
n = int(n)
if n == 0:
return 1
else:
return a * recPower(a, n - 1)
def main():
a = input("enter base :")
n = input("enter power :")
print ("Total = ", recPower(a, n))
main()

Building a simple operattion type calculator for two digits? stuck at error

print("Welcome to MusCalculator")
print("For adding two no type add")
print("for mutiplying type multiply")
print("for subtraction type subtract")
print("for dividing type divide")
def add_numbers(x, y):
if input == "addition":
addition = x + y
print addition
if input == "multiply":
multiply = x*y
print multiply
if input == "subtract":
if x > y:
sub = x - y
print sub
else:
sub = y - x
print sub
if input == "divide":
div = x / y
print div
else:
print("Use me if you know me")
x = input("First No.")
y = input("Second No.")
addition = x + y
c = input("Type Operation")
add_numbers(x, y)
the error is
Traceback (most recent call last):
File "C:\Users\Aafaq\workspace\python\project 1.py", line 34, in <module>
c = input("Type Operation")
File "C:\Program Files (x86)\eclipse\plugins\org.python.pydev_4.5.5.201603221110\pysrc\pydev_sitecustomize\sitecustomize.py", line 141, in input
return eval(raw_input(prompt))
File "<string>", line 1, in <module>
NameError: name 'addition' is not defined
There are some problems in your code. Some are mentioned below.
Addition variable is used in your main code, you might want to try different name or declare addition as a global variable.
under or above your print statements:
addition = 0
Also you are setting the received operation into variable name c, which is not referred anywhere, that should have been set to variable name input (which is a system define function name, you should not use that name to compare it with a string).
You are probably trying to do something like this:
operation = " "
addition = 0
def add_numbers(x, y):
if operation == "addition":
addition = x + y
print addition
if input == "multiply":
multiply = x*y
print multiply
if operation == "subtract":
if x > y:
sub = x - y
print sub
else:
sub = y - x
print sub
if operation == "divide":
div = x / y
print div
else:
print("Use me if you know me")
x = input("First No.")
y = input("Second No.")
addition = x + y
operation = input("Type Operation")
add_numbers(x, y)

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