[英]Python : If statement within a while loop
我寫了一個程序,它不斷滾動一個“num”面骰子,直到它達到最大滾動數,即您寫為“num”的數字。 但是,如果碰巧第一個滾動是數字,程序不會說“你登陸了你的數字”。 正如它應該。 這是代碼
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!")
同樣,如果擲骰數等於選擇的數字,我會得到“進程以退出代碼 0 完成”,而不是我想要的文本。 我該如何解決?
將最終打印件放在while
循環之外,因為您總是在那里
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!")
如果是這樣的話怎么辦?
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)
你可以這樣做:
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")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.