我是python新手。这是我想在代码中做什么的一个小例子。我想保存正方形和圆形的值。 所以它会问“你想改变数值吗…”你按1表示平方,它从0变为1,然后它再问,你按2,然后它又上升到2。 我不想在我的程序中使用全局变量。 我在读一篇文章,说没有全局变量的答案是将变量传递给函数,然后进行更改,然后返回它们。我不认为这对我的while循环有效。在
loopcounter = 0
square = 0
circle = 0
def varibleChanges(circle, square):
#global circle, square
print 'Would you like to change circle or square?'
print '1. circle' '\n' '2. square'
choice = raw_input('>>')
if choice == '1':
square = square + 1
elif choice == '2':
circle = circle + 1
print 'square: ', square
print 'circle: ', circle
while loopcounter <=2:
print 'this is the begining of the loop'
varibleChanges(circle, square)
loopcounter +=1
print "this is the end of the loop\n"
将变量存储在代码之外是否有效,例如写入文件(无论如何,我都会有一个保存功能) 或者最好重新考虑一下代码吗?在
如果
variableChanges
返回了一个元组:它要修改的形状的名称和新值,那么shapes
就不需要是全局的,甚至可以在variableChanges中使用。在虽然对于您这样大的程序来说这不是必需的,但是您可以考虑使用类。在
当你处理更大的程序时,类会更有用。例如,如果有多个圆,则可以从该圆类创建许多圆对象。然后你可以分别处理每个圆。在
你现在最好选择一个更简单的答案,但你最终肯定会使用类。在
请参见here以了解Python中的类。在
返回变量,然后再将它们传入,对您的代码来说就可以了。如果将代码修改为:
然后你应该看到你想要的行为。在
作为旁注,您可以写下以下内容:
^{2}$作为
在Python中。编码快乐!在
相关问题 更多 >
编程相关推荐