检查用户输入是否匹配(随机)整数的任何数字
Check if userinput matches any digits of a (random) integer
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
如果您真的想将两个数字都保留为 int,您可以使用 %(模运算符)除以其以 10 为底的值后的余数。
例如
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
为 100/10/1 重复的公式应该都比较该“点”中的数字,而无需转换数据类型。接着输出 correctnum 的值,你应该有你需要的东西。
random = 1234
random = str(random)
#guess = str(input('enter your guess'))
guess = '1222'
correct = 0
for i in range(len(guess)):
if guess[i] == random[i]:
correct += 1
print(correct)
ouput: 2
或者简单地说:
correct = sum(guess[i] == random[i] for i in range(len(guess)))
如果你指的是位置
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: "))
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
如果您真的想将两个数字都保留为 int,您可以使用 %(模运算符)除以其以 10 为底的值后的余数。
例如
correctnum = 0
random = 1234
guess = 1111
if ((((random-(random % 1000 )) /1000) == (((guess-(guess % 1000 )) /1000)):
correctnum++
为 100/10/1 重复的公式应该都比较该“点”中的数字,而无需转换数据类型。接着输出 correctnum 的值,你应该有你需要的东西。
random = 1234
random = str(random)
#guess = str(input('enter your guess'))
guess = '1222'
correct = 0
for i in range(len(guess)):
if guess[i] == random[i]:
correct += 1
print(correct)
ouput: 2
或者简单地说:
correct = sum(guess[i] == random[i] for i in range(len(guess)))
如果你指的是位置
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: "))