python - 如何正确循环这段代码?我无法让它工作。对编码还很陌生

标签 python loops

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/

相关文章:

Python牛奶库: object weights issue

python - 如何在 Python 中声明一个静态属性?

java - 我用什么来跟踪号码?

javascript - 观察 setTimeout 循环,以便一次只有一个在运行

Python( Pandas ): replace value if previous value is same as next value

python - 如何获得元组中的所有最小值?

python - Pandas DataFrame 到控制台格式的 CSV

python: `for i in obj.func()` 每次迭代都会重新运行 `func` 吗?

SQL 迭代列表以对每个项目调用 EXEC

java - 重新排列 int 数组中的 int 值 java