Python重置变量 - While循环

时间:2018-05-08 09:54:09

标签: python loops while-loop reset

我刚开始学习编码。

我试图写这个简单的计数器。它适用于第一次运行,但是当循环调用" while()"它会重置" r"和列表" we_list" " you_list&#34 ;.即使在循环之后,我也无法确定如何存储它们的值。

def begin():
    r = 1
    print("This is a counter for the game Belote")
    print("Round " + str(r))

    we_list = []

    you_list = []

    we = int(input("Enter score for 'We' "))
    we_list.append(we)
    we_sum = sum(we_list)

    you = int(input("Enter score for 'you' "))
    you_list.append(you)
    you_sum = sum(you_list)

    print("WE " + str(we_sum))
    print("YOU " + str(you_sum))
    r += 1
    while we_sum or you_sum < 151:
        begin()
    else:
        print("End of game ")
        exit()
begin()

编辑:

我使用建议编辑了代码,并设法修复了r和列表,但是现在我遇到的问题是它在151之后没有突破循环。

we_list = []
you_list = []

def begin(r):
    print("This is a counter for the game Belote")
    print("Round " + str(r))

    we = int(input("Enter score for 'We' "))
    we_list.append(we)
    we_sum = sum(we_list)

    you = int(input("Enter score for 'you' "))
    you_list.append(you)
    you_sum = sum(you_list)

    print("WE " + str(we_sum))
    print("YOU " + str(you_sum))
    r += 1
    while we_sum or you_sum < 151:
        begin(r)
    else:
        print("End of game ")
        exit()
r=1
begin(r)

4 个答案:

答案 0 :(得分:0)

您正在初始化r,we_list and you_list内部的开始函数,因此当每次将它们初始化为r=1, you_list=[] and we_list = []时调用begin时。在开始功能之外初始化它们。

答案 1 :(得分:0)

您的设计有点混乱,您应该将“圆形”逻辑隔离为专用函数,并返回这些值。

此外,如果您不需要跟踪每个添加的值,您不需要保留列表,您可以直接将其加总。

def round(we, you):
    we_in = int(input("Enter score for 'We' "))
    we = we + we_in

    you_in = int(input("Enter score for 'you' "))
    you = you + you_in
    print("WE " + str(we))
    print("YOU " + str(you))

    return [we, you]

def begin():
    r = 1
    print("This is a counter for the game Belote")

    we_sum = 0  
    you_sum = 0  

    while we_sum or you_sum < 151:
        print("Round " + str(r))    
        r += 1
        [we_sum, you_sum] = round(we_sum, you_sum)
    else:
        print("End of game ")
        exit

答案 2 :(得分:0)

r是一个局部变量,因此每次begin()调用自身时,新的begin()都会获得新的r

您可以制作rwe_listyou_list全局变量(在begin()之外或使用global关键字声明它们)并保存值。

答案 3 :(得分:0)

修复代码发送r作为参数

def begin(r):
    print("This is a counter for the game Belote")
    print("Round " + str(r))

    we_list = []

    you_list = []

    we = int(input("Enter score for 'We' "))
    we_list.append(we)
    we_sum = sum(we_list)

    you = int(input("Enter score for 'you' "))
    you_list.append(you)
    you_sum = sum(you_list)

    print("WE " + str(we_sum))
    print("YOU " + str(you_sum))
    r += 1
    while we_sum or you_sum < 151:
        begin(r)
    else:
        print("End of game ")
        exit()
r=1
begin(r)