我是Python的新手,我现在正在使用Python 3.3.3以防你想知道。下面是我的代码,我将其从Batch Script编写的任何语言翻译成Python。 Here是批处理脚本代码。我不知道我做错了什么,但是当我跑这个时,我得到NameError: global name 'change' is not defined
。我使用http://pych.atomidata.com/code来检查语法,如果你输入我的Python代码来检查它,你得到的只是一些代码错误和一些Pep-8错误。我想不出还有什么不对。我甚至不知道大多数代码错误是什么,Pep-8错误都是Line: __ Column: __ E302 expected 2 blank lines, found 1
。
import subprocess as sp
global change
global count
def numberInput():
while True:
try:
number = int(input("Input a number, please: "))
sp.call('cls', shell=True)
break
except ValueError:
print('Please enter a valid input...')
sp.call('pause', shell=True)
numberInput()
change = number
numberVerify()
def numberVerify():
if change == 0:
numberCorrectIsTrue()
else:
number = change
def numberCorrectIsTrue():
count = count + 1
integer = number
# checks to see if the input
# is valid or not.
if number != integer:
sp.call('cls', shell=True)
print("Please enter a valid number!")
loop()
else:
even = number % 2
if even == 0:
print("Substituting x in 'x / 2' with {}".format(number))
answer = number / 2
else:
print("Substitiuting x in '(3 * x) + 1' with {}".format(number))
answer = number * 3
answer = answerOdd + 1
print(answer)
if answer == 1:
returnStats()
else:
numberCorrectIsTrue()
def returnStats():
print("Your original input of {} returned as 1.".format(change))
print("A total of {} operations were executed.".format(count))
change = change + 1
count = 0
sp.call('pause', shell=True)
numberVerify()
def check():
number = answer
numberCorrectIsTrue()
numberInput()
答案 0 :(得分:2)
这些行:
global change
global count
应该只是
change = 0
count = 0
当您想引用全局变量时使用global
关键字,因此使用这些值的函数应该是这样的:
def func():
global count
count = count + 1
答案 1 :(得分:1)
global
不会被该代码块内的函数继承。需要分配给全局变量的每个函数都需要为该变量设置自己的global
声明。
答案 2 :(得分:0)
在每个函数的开头添加“全局更改”,指定要更改或计数的值。
因此,例如,numberInput()应该看起来像
def numberInput():
global change
while True:
...
来源:Using global variables in a function other than the one that created them