简体   繁体   中英

How do I properly loop this code? I can't get it to work. Still very new to coding

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!")

I can't get this code to loop when the second number is not a multiple of the first number. And also, how do I make it so that the program finishes once the condition is true, ie, the second number IS a multiple of the first number.

In Python, unlike most other programming languages, code indentation matters. The following should work since indentations have been fixed. Also, you'll need to recalculate the value of b in the while loop, that way the loop will eventually fail.

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!")

If your goal is to find a combination of two numbers where the first is truly a multiple of the second you could try something like this:

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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM