变量未定义,功能不起作用

时间:2018-03-11 14:15:04

标签: python

在提出我的问题之前,我将解释这段简短的代码究竟是做什么的:首先你得到一个菜单,你可以做出选择,如果你选择1,它应该要求观看时间(W)视图(V)然后是视频(h),(m)和(s)的持续时间。但是现在当你选择1时它会给我这个错误:

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  

到目前为止,我可以看到在名为choice()

的函数中定义了Choice

也许我应该使用不同的名字?

如果你能帮助解决这个问题并让它发挥作用,我将非常感激

这里是完整的代码

   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()   

2 个答案:

答案 0 :(得分:0)

你应该学习变量的范围。 例如,您定义了一个choice函数,并在choice函数中定义了一个Choice变量,那么Choice变量只会影响choice函数。 如果你想让一些变量影响全局,可以用函数定义变量,或者在定义时添加全局关键字(如全局选择)

答案 1 :(得分:-1)

您声明的Choice变量仅限于choice函数。如果要全局使用它,请将其设为global或定义最顶层的缩进级别