首页 > 解决方案 > 我在定义变量时收到变量未定义错误

问题描述

我是 python 新手,并且一直有这个错误。我在定义变量时收到“变量未定义”错误。c 和 d 是这个特定代码中的问题:

    m = 1
while m == 1:
    studentname = input("What is the student's name?")
    testnumber = int(input("How many tests have they completed? (up to 10)"))
    while testnumber <= 0:
        print("Invalid.")
        testnumber = int(input("How many tests have they completed? (up to 10)"))
    while testnumber >= 10:
        print("Invalid.")
        testnumber = int(input("How many tests have they completed? (up to 10)"))
        while testnumber <= 0:
           print("Invalid.")
           testnumber = int(input("How many tests have they completed? (up to 10)"))
    if testnumber >= 1:
            a = int(input("What is their mark?"))
            b = int(input("Out of?"))
            c == a / b
            d == c * 100
            print("Their mark is", d, "percent.")

我希望 c 等于 a 除以 b,但程序声称 c 是未定义的,即使“c == a / b”定义了我希望 c 是什么。我尝试过“a / b == c”和“a/b == int(c)”,但没有任何效果。

标签: pythonvariablesmathundefined

解决方案


这是因为您有双 = 符号,它比较两个变量而不是分配它们。

如果你想分配一个值,那么你只需要一个'='

尝试这个:

m = 1
while m == 1:
studentname = input("What is the student's name?")
testnumber = int(input("How many tests have they completed? (up to 10)"))
while testnumber <= 0:
    print("Invalid.")
    testnumber = int(input("How many tests have they completed? (up to 10)"))
while testnumber >= 10:
    print("Invalid.")
    testnumber = int(input("How many tests have they completed? (up to 10)"))
    while testnumber <= 0:
       print("Invalid.")
       testnumber = int(input("How many tests have they completed? (up to 10)"))
if testnumber >= 1:
        a = int(input("What is their mark?"))
        b = int(input("Out of?"))
        c = a / b
        d = c * 100
        print("Their mark is", d, "percent.")

推荐阅读