In the blind
In the blind

Reputation: 113

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?

Upvotes: 0

Views: 2141

Answers (4)

mns
mns

Reputation: 26

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

Upvotes: 0

Malo
Malo

Reputation: 1313

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

Upvotes: 0

Maryna Grushevskaya
Maryna Grushevskaya

Reputation: 51

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)

Upvotes: 0

azro
azro

Reputation: 54148

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

Upvotes: 2

Related Questions