检查用户输入是否与(随机)整数的任何数字匹配

random = random.randint(1000, 9999)

guess = int(input("Enter your guess: "))

while guess != random:

    guess = int(input("That was incorrect! Enter your guess: "))

这是一个非常简单的猜谜游戏,但是我想添加一些内容,在每次不成功的尝试之后,它会显示四位数中有多少个数字是正确的。


我还没有尝试过这一点,主要是因为我不确定如何做到这一点。


例如


random = 1234

Enter your guess: 1111

You guessed 1 number correct

Enter your guess: 1222

You guessed 2 numbers correct

...... and so on


慕村225694
浏览 122回答 3
3回答

开心每一天1111

如果你的意思是职位random = random.randint(1000, 9999)guess = int(input("Enter your guess: "))while guess != random:    right = 0    index = 0    for char in str(guess):        if char == str(random)[index]:            index += 1            right += 1    print(f'{right} were right')    guess = int(input("That was incorrect! Enter your guess: "))

胡说叔叔

如果您确实想将这两个数字保留为 int,则可以使用 %(模运算符)来查找整数除以其以 10 为基数的值后的余数。例如。    correctnum = 0    random = 1234    guess = 1111    if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):      correctnum++对 100/10/1 重复的公式应该全部比较该“位置”中的数字,而无需转换数据类型。接下来输出 Correctnum 的值,您应该得到您需要的内容。

神不在的星期二

random = 1234random = str(random)#guess = str(input('enter your guess'))guess = '1222'correct = 0for i in range(len(guess)):    if guess[i] == random[i]:        correct += 1print(correct)ouput: 2或者简单地:correct = sum(guess[i] == random[i] for i in range(len(guess)))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python