在循环中保存变量

0 投票
3 回答
6737 浏览
提问于 2025-04-18 01:06

我刚开始学Python。这是我想在代码中实现的一个小例子。我想保存平方和圆的值。程序会问“你想要改变这些值吗...”,你按1代表平方,它的值从0变成1,然后再问一次,你按2,它的值又变成2。我不想在我的程序里使用全局变量。

我看到一些帖子说,解决不使用全局变量的方法是把变量传递给函数,进行修改后再返回。我觉得这在我的循环里可能不太适用。

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"

那么,把变量存储在代码外面,比如写入文件,这样可行吗?(反正我会有一个保存功能)或者说,最好还是重新考虑一下代码呢?

3 个回答

1

如果 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"
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())

当你处理更大的程序时,类会变得非常有用。比如说,如果你有多个圆形对象,你可以从这个圆形类中创建很多圆形对象。这样你就可以单独处理每一个圆形。

现在你可能还是用一些简单的方法比较好,但将来你肯定会用到类。

想了解Python中的类,可以看看 这里

2
circle += 1

把变量返回,然后再把它们传回去,这样做在你的代码里是完全没问题的。如果你把代码改成下面这样:

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

在 Python 里。祝你编码愉快!

撰写回答