[英]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".我写了一个程序,它不断滚动一个“num”面骰子,直到它达到最大滚动数,即您写为“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.同样,如果掷骰数等于选择的数字,我会得到“进程以退出代码 0 完成”,而不是我想要的文本。 How do I fix this?我该如何解决?
Put the final print, outside of the while
loop, as you're always land there将最终打印件放在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!")
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.