在Python中比较两个变量不起作用?
我正在写一个比较两个变量的简单程序在Python中比较两个变量不起作用?,python,Python,我正在写一个比较两个变量的简单程序 from random import randint result = (randint(1, 6)) guess = input('Guess the number: ') if guess == result: print('You got it right') else: print('Wrong') print(result) 程序将变量result设置为随机数,然后用户输入他们猜测的数字。然而,即使他们得到了正确的数字,也
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if guess == result:
print('You got it right')
else:
print('Wrong')
print(result)
程序将变量result
设置为随机数,然后用户输入他们猜测的数字。然而,即使他们得到了正确的数字,也表明他们错了
我怎样才能得到它,当他们得到正确的数字时,它会说他们是对的
提前谢谢 由于
input()
的返回类型为string
,因此您正在将int
与string
进行比较。这将始终给出False
将您的输入guess
更改为:
guess = int(input())
所以
将guess=input('guess the number:')
更改为guess=int(input(guess the number:'))
因为
input()
将字符串作为用户输入。要么将整型设置为字符串,要么将整型设置为字符串,以便进行比较。无法比较两种不同的类型(INT和STR)
e、 g.代码01[两个比较变量均为字符串]
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if guess == str(result):
print('You got it right')
else:
print('Wrong')
print(result)
e、 g.代码02[两个比较的变量都是整数]
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if int(guess) == result:
print('You got it right')
else:
print('Wrong')
print(result)
更改
guess=int(输入(猜测数字:'))
我见过一些类似的问题,它们在变量比较和猜数游戏方面也有问题。嗯……太奇怪了,为什么有这么多人想做猜数游戏?可能是真棒的复制品,非常感谢!不记得你能做到,这很好。非常感谢!很高兴听到这个消息。你进一步添加错误处理,因为现在如果用户输入字符而不是数字,程序将崩溃。
from random import randint
result = (randint(1, 6))
guess = input('Guess the number: ')
if int(guess) == result:
print('You got it right')
else:
print('Wrong')
print(result)