在while循环中保存变量

2024-09-27 07:32:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我是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"

将变量存储在代码之外是否有效,例如写入文件(无论如何,我都会有一个保存功能) 或者最好重新考虑一下代码吗?在


Tags: ofthe代码loopisthisprintsquare
3条回答

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

 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"

虽然对于您这样大的程序来说这不是必需的,但是您可以考虑使用类。在

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中的类。在

返回变量,然后再将它们传入,对您的代码来说就可以了。如果将代码修改为:

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"

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

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

^{2}$

作为

circle += 1

在Python中。编码快乐!在

相关问题 更多 >

    热门问题