返回该数字输入的 Python 不正确,但它是正确的
Posted
技术标签:
【中文标题】返回该数字输入的 Python 不正确,但它是正确的【英文标题】:Python returning that number input is incorrect, but it is correct 【发布时间】:2022-01-23 03:41:40 【问题描述】:我制作了一个 python 程序,可以在随机数或字母之间进行选择,然后用户尝试猜测它,但是当程序选择一个数字并正确猜测到确切数字时,它会返回该数字用户输入不正确。
这是我的代码:
import math
import random
import string
count = 0
numberroll = random.randint(1,10)
stringroll = random.choice(string.ascii_letters)
chooseroll = random.choice([numberroll, stringroll.lower()])
# print(chooseroll)
count = 0
if chooseroll == numberroll:
usernumberguess = input("Your guess: ")
if usernumberguess.isdigit():
print("It is a number!")
count += 1
else:
print("That is not a number...")
if usernumberguess.isdigit() == numberroll:
print("Correct number!")
count += 2
else:
print("Better luck next time!")
if chooseroll == stringroll.lower():
userstringguess = input("Your guess: ")
if userstringguess.isalpha():
print("It is a letter!")
count += 1
else:
print("That is not a letter...")
if userstringguess.lower() == stringroll.lower():
print("Correct letter!")
count += 2
else:
print("Incorrect! Better luck next time!")
# print(count)
有没有办法解决这个问题?提前致谢!
【问题讨论】:
你能分享更多你的代码吗?不能运行就很难调试。 【参考方案1】:这部分if usernumberguess.isdigit() == numberroll:
可能有问题:isdigit()
返回True或False,你检查是不是numberroll
。您可以在猜测是数字的情况下检查猜测是否正确。您还需要将输入(字符串)转换为int
。
if chooseroll == numberroll:
usernumberguess = input("Your guess: ")
if usernumberguess.isdigit():
print("It is a number!")
usernumberguess = int(usernumberguess)
count += 1
if usernumberguess == numberroll:
print("Correct number!")
count += 2
else:
print("Better luck next time!")
else:
print("That is not a number...")
我会添加更多代码用于调试目的,以便您查看问题所在:
import random
random.seed(0)
count = 0
numberroll = random.randint(0, 9)
print(f"the user has to guess: numberroll")
usernumberguess = input("your guess: ")
print(f"your guess is usernumberguess")
if usernumberguess.isdigit():
print("your guess is a number")
usernumberguess = int(usernumberguess)
count += 1
if usernumberguess == numberroll:
print("your guess is correct")
count += 2
else:
print("your guess is not correct")
else:
print("your guess is not a number")
【讨论】:
以上是关于返回该数字输入的 Python 不正确,但它是正确的的主要内容,如果未能解决你的问题,请参考以下文章