【问题标题】:if statement and printing in pythonif语句和python中的打印
【发布时间】:2023-10-07 19:47:01
【问题描述】:

我不知道为什么这段代码没有打印“得到它” 当我运行它时,它只会显示打印的 else 语句,即使答案是正确的。

import random as rand
print('Welcome to the guessing game!')
print('type a number between 1 to 9')
running = True
while running:
    value = rand.randint(1, 9)
    user_guess = input()

    if user_guess == value:
        print('got it')
    else:
        print('not at all')

我什至尝试打印该值以确保我的答案是正确的。

【问题讨论】:

  • 试试print(type(user_guess), type(value))
  • 不明白
  • str != int,它永远不会...您需要将user_guess 转换为int
  • 谢谢老哥知道了!

标签: python loops while-loop boolean


【解决方案1】:

因为之后

user_guess = input()

user_guess 将是 strvalueint
在声明 if user_guess == value: 时,您试图将 strint 进行比较。
试试

user_guess = int(input())

【讨论】: