在while循环上保存变量

时间:2014-04-03 00:05:30

标签: python variables while-loop

我是python的新手。这是我在代码中想要做的一个小例子。我想保存正方形和圆形的值。 所以它会要求"确实要改变价值......"按一个为正方形,它从0变为1,然后再次询问,按两次,然后再次上升到2。 我不想在我的程序中使用全局变量。 我正在阅读帖子,说无全局的答案是将varibles传递给函数并进行更改然后返回它们。我认为这不会适用于我的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"

将varibles存储在代码之外工作,比如写入文件,(无论如何我都会有一个保存功能) 或者最好再次重新考虑代码?

3 个答案:

答案 0 :(得分:3)

虽然对于你这么大的程序来说没有必要,但你可以考虑使用类。

class Circle(object):
    def __init__(self, value):
        self.value = value
    def getValue(self):
        return self.value
    def incValue(self, add):
        self.value += add

circle = Circle(0) #Create circle object
circle.incValue(1)
print(circle.getValue())

当你处理更大的程序时,类会更有用。例如,如果您有多个圆圈,则可以从此圆圈类创建许多圆形对象。然后,您可以单独处理每个圆圈。

你现在可能最好使用一个更简单的答案,但你最终肯定会使用这些类。

请参阅here以了解Python中的类。

答案 1 :(得分:2)

返回变量,然后将它们传回,将对您的代码运行良好。如果您将代码修改为以下内容:

def varibleChanges(circle, square):
    #skip to the end..
    return circle, square

while loopcounter <=2:
    print 'this is the begining of the loop'
    circle, square = varibleChanges(circle, square)
    loopcounter +=1
    print "this is the end of the loop\n"

然后你应该看到你想要的行为。

作为旁注,您可以编写如下内容:

circle = circle + 1

as

circle += 1
在Python中

。快乐的编码!

答案 2 :(得分:1)

如果variableChanges返回了一个元组:它想要修改的形状的名称和新值,则shapes不需要是全局的,甚至可以在variableChanges中使用。< / p>

 def variableChanges(circle, square):
    print 'Would you like to change circle or square?'
    print '1. circle' '\n' '2. square'
    choice = raw_input('>>')
    if choice == '1':
        return ('square', square + 1)
    elif choice == '2':
        return ('circle', circle + 1)

loopcounter = 0
shapes = {
    'square' = 0,
    'circle' = 0
}

while loopcounter <= 2:
    print 'this is the begining of the loop'
    shape, value = variableChanges(shapes['circle'], shapes['square'])
    shapes[shape] = value
    print (shape, value)
    loopcounter += 1
    print "this is the end of the loop\n"