import random
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
b = randomTwo * 2
while b != randomOne:
print("Your first number is not a multiple of the second number!")
x = input('Press Enter to try again.')
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
if randomTwo * 2 == randomOne:
print("Your first number is a multiple of the second number!")
当第二个数字不是第一个数字的倍数时,我无法循环此代码。另外,如何使程序在条件为真时完成,即第二个数字是第一个数字的倍数。
最佳答案
与大多数其他编程语言不同,Python 中代码缩进很重要。由于缩进已修复,以下内容应该有效。此外,您还需要在 while 循环中重新计算 b
的值,这样循环最终会失败。
import random
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
b = randomTwo * 2
while b != randomOne:
print("Your first number is not a multiple of the second number!")
x = input('Press Enter to try again.')
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
b = randomTwo * 2
# No need to check if it is a multiple since it must be to break the loop
print("Your first number is a multiple of the second number!")
如果您的目标是找到两个数字的组合,其中第一个数字实际上是第二个数字的倍数,您可以尝试如下操作:
import random
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
b = randomOne / randomTwo
# If b is an integer, then it divided evenly
while b != int(b):
print("Your first number is not a multiple of the second number!")
x = input('Press Enter to try again.')
randomOne = random.randint(1,10)
print(randomOne)
randomTwo = random.randint(1,10)
print(randomTwo)
b = randomOne / randomTwo
if randomTwo * 2 == randomOne:
print("Your first number is a multiple of the second number!")
关于python - 如何正确循环这段代码?我无法让它工作。对编码还很陌生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33222992/