增加一个变量并存储值? Python

Increment a variable and store the value? Python

我是 Python 的新手。 我正在尝试做一个小测验,如果你是正确的,你会得到一分,或者如果错误,你不会得到分数。

total_Points = 0

question_1 = input("What is Sweden's biggest island?")
answer1 = "Gotland"


if question_1 == answer1:
    print("Gj, you are correct")

    print("You got" + str(total_Points+int(+1)) + " points")

else :
    print("Wrong")

    print("You still got " + total_Points + " points")

question_2 = input("What country is west of Sweden?")

answer2 = "Norway"

if question_2 == answer2:

    print("Correct!")

    print("Gj, you now have " + str(total_Points+int(+1))+ " points")
else:
    print("Nope, ur wrong")
    print("You still gott" + total_Points + " points")

如果你在 question_1 和 question_2 中得到一个点,你如何存储值?那么应该是2分。如果您在第 3 个问题上回答错误怎么办?它怎么知道你只有2分?

感谢新手解答

total_Points = 0

question_1 = input("What is Sweden's biggest island?")
answer1 = "Gotland"


if question_1 == answer1:
    print("Gj, you are correct")
    total_Points = total_Points + 1
    print("You got", total_Points, " points")
else :
    print("Wrong")
    print("You still got ", total_Points, " points")

question_2 = input("What country is west of Sweden?")

answer2 = "Norway"

if question_2 == answer2:

    print("Correct!")
    total_Points = total_Points + 1
    print("Gj, you now have ", total_Points, " points")
else:
    print("Nope, ur wrong")
    print("You still gott", total_Points, " points")

由于您已将变量 total_Points 声明为 0,因此您可以添加 1 并像 total_Points = total_Points + 1 一样重新分配给它。所以,现在,total_Points 将具有更新后的值。

简而言之,您也可以像 total_Points+=1 一样增加它的值。

total_Points = 0

question_1 = input("What is Sweden's biggest island?")
answer1 = "Gotland"


if question_1 == answer1:
    print("Gj, you are correct")
    total_Points += 1
    print("You got" + str(total_Points) + " points")

else :
    print("Wrong")

    print("You still got " + total_Points + " points")

question_2 = input("What country is west of Sweden?")

answer2 = "Norway"

if question_2 == answer2:

    print("Correct!")
    total_Points += 1 
    print("Gj, you now have " + str(total_Points)+ " points")
else:
    print("Nope, ur wrong")
    print("You still gott" + total_Points + " points")

您添加到保持计数的变量 total_Points

total_Points = 0

question_1 = input("What is Sweden's biggest island?")
answer1 = "Gotland"

if question_1 == answer1:
    print("Gj, you are correct")
    total_Points+=1;

print("You got " + str(total_Points) + " points")   

会给你指路

只需在所有正确答案的 if 语句下递增 total_Points
例如:

if (correct answer):
    total_Points = total_Points + 1