简体   繁体   中英

Python : If statement within a while loop

I wrote a program, which keeps rolling a "num" sided die until it reaches the maximal roll which is the number you write as "num". However, if it happens that the first roll is the number, the program does not say "You landed on your number." as it should. Here is the code

import random

num = () #put the number here#
i = random.randint(1,num)

while i != num:
    print(i)
    print("Not lucky")
    i = random.randint(1,num)
    if i == num:
        print("You landed on your number!")

Again, if the roll equals the number choice, I get "Process finished with exit code 0", not the text I want. How do I fix this?

Put the final print, outside of the while loop, as you're always land there

num = 5  # put the number here#
i = random.randint(1, num)
while i != num:
    print("Not lucky,", i, "isn't the one")
    i = random.randint(1, num)
print("You landed on your number!")

what if something like that?

import random

num = int(input('Put your number: '))
i = random.randint(1, num)

while True:
    if i == num:
        print("You landed on your number!")
        print(num)
        break
    else:
        print(i)
        print("Not lucky")
        i = random.randint(1, num)

You can do it like this:

import random

num = (2) #put the number here#
i = random.randint(1,num)

while i != num:
    i = random.randint(1,num)
    if i != num:
        print(i, "Not lucky")


print(i, "You landed on your number!")
import random

num = #put the number here#

while True:
    i = random.randint(1,num)
    print(i)
    if i == num:
        print("You landed on your number!")
        break
    print("Not lucky")

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