这是我的代码:
change = 0
count = 0
value = 0
answer = 0
def numberTest():
if change == 0:
skip()
else:
value = change
def skip():
count + 1
number = value
# Check if the input is valid
if value != number:
print('PLEASE ENTER A VALID NUMBER!!!')
else:
Even = number % 2
if Even == 0:
print('Substituting even number in: x / 2')
print('%s/2=' % number)
answer = number / 2
else:
print('Substituting odd number in: 3x + 1')
print('3' + number + ' + 1=')
answer = number * 3
answer = answer + 1
answer = str(answer)
print(''+ answer +'')
if answer == 1:
finalValue()
else:
check()
def check():
value = answer
skip()
def loop():
value = int(input('Input a number: '))
change = value
skip()
loop()
def finalValue():
print('The number (' + change + ') returned as 1.')
print('A total of (' + count + ') commands were executed.')
change = change + 1
count = 0
print('')
print('')
print('')
numberTest()
每当我启动代码时,都会要求我输入一个数字(如预期的那样),但之后会发生这种情况:
Input a number: 1
Substituting even number in: x / 2
0/2=
0.0
我真的不明白为什么程序没有像我预期的那样工作,但我怀疑有一部分代码:
value = int(input('Input a number: '))
我自己也写了这篇文章,我是Python的新手,我之前只使用过批处理,所以过渡非常简单,虽然我对某些命令不太熟悉......
修改 我期待程序要做的是询问一个数字,存储该数字,然后通过一系列测试运行它,但当数字进入实际测试时,它将“x”替换为“0”,即使我输入诸如“54656”之类的数字。也许,当它询问数字时,当我输入数字时,它只是没有正确存储,或者我的代码有问题......
答案 0 :(得分:1)
如果你想改变一个全局变量,你需要在你的函数中声明它前面有global
,即:
value = 0
def changeValue():
global value
value += 1
如果您不需要更改变量,则不需要global
。
答案 1 :(得分:1)
您正在尝试更改全局变量而不声明它们:
a = 'bad'
def bad_fn():
a = 'good'
bad_fn()
print('bad_fn() is'+a)
def good_fn():
global a
a = 'good'
good_fn()
print('good_fn() is'+a)
结果
bad_fn() is bad
good_fn() is good
通常,在不良实践中使用全局变量。显式传递参数使得调试和代码重用更加令人头疼。以下是您的代码的重写版本,应该更容易理解:
# Test the Collatz conjecture:
# http://en.wikipedia.org/wiki/Collatz_conjecture
import profile
# Python 2/3 compatibility shim
import sys
if sys.hexversion >= 0x3000000:
# Python 3.x
inp = input
rng = range
else:
# Python 2.x
inp = raw_input
rng = xrange
# cache of already-seen values
seen = set([1])
def test(n):
visited = set()
while True:
if n in seen: # Ran into an already-seen chain that goes to 1
seen.update(visited)
return len(visited)
elif n in visited: # Closed loop! this should never happen
print('Loop found at n = {}'.format(n))
return None
else:
visited.add(n)
if n % 2: # n is odd?
n = 3*n + 1
else:
n //= 2
def do_profile(upto=1000000):
prof = profile.Profile()
prof.run('for n in rng(2, {}): test(n)'.format(upto))
prof.print_stats()
def main():
while True:
try:
n = int(inp('Enter a number to test (or x to exit): '))
except ValueError:
break
res = test(n)
if res is None:
print("Well, that's odd...")
else:
print("Chain terminated after {} values were tested".format(res))
if __name__=="__main__":
main()
我的机器上花了17.7秒来运行do_profile(1000000)
。它共查看了2,168,611个数字,其中最高的是56,991,483,520。没有发现循环。
编辑:我添加了一个inp()shim函数;代码现在应该在Python 2或Python 3中运行。
Edit2 :将分析代码移到主代码清单中,并将范围/ xrange添加到Python 2/3填充程序中。