为什么while循环在成功时不会中断?

时间:2019-07-12 23:25:54

标签: python loops while-loop

我正在迈出第一步,正在开发一个生成随机数的小程序,用户必须猜测数字,直到所选数字与生成的数字匹配为止。

由于某些原因,即使我给出了正确的数字,while循环也不会中断。

import random
secretnumber = random.randint(1,10)
chosennumber = 0

while secretnumber != chosennumber:
    print("Number selected. Please select a number between 1 and 10")
    print ("hint! The number is " + str(secretnumber))
    chosennumber = input()
    if secretnumber!= chosennumber:
        continue
    print("please try again, think about the hint")
    chosennumber = input()
    if chosennumber == secretnumber:
        break
print("you've guessed the correct number " + str(secretnumber))

1 个答案:

答案 0 :(得分:2)

input()的返回值是一个字符串。将字符串与整数进行比较将始终产生False。您需要将字符串强制转换为int或将int强制转换为字符串以进行比较,以确保要比较的是相同类型的变量。

import random
secretnumber = random.randint(1,10)
chosennumber = 0

while secretnumber != chosennumber:
    print("Number selected. Please select a number between 1 and 10")
    print ("hint! The number is " + str(secretnumber))
    chosennumber = int(input().strip())
    if secretnumber!= chosennumber:
        continue
    print("please try again, think about the hint")
    chosennumber = int(input().strip())
    if chosennumber == secretnumber:
        break
print("you've guessed the correct number " + str(secretnumber))