[英]Fixing a loop to continue with the program instead asking the same thing again in python
我有這個骰子游戲的問題。 當我嘗試使其跳至下一段代碼時,它會返回。 請幫忙:
import random # Importing the module
decision = ('y') # Setting variable 'decision' as y
roll_number = 1 # Setting variable 'rolling_number' as 1
name = input('What is your name?\n') # Setting a variable as a condition so that the User can change the variable. It is an input.
while decision == ('y'): # While loop for the decision
if roll_number > 1: # If loop for roll_number
same_person = input('\nAre you the same person? If so please press y, if not please press n. Pressing anything else ask your name again!\n') #Asking if the User is the same person
if same_person == ('y'): # If it is the same person
print('Okay!') # Outputs 'Okay!'
continue # Skips to the next part of the code
else: # Otherwise
name = input('\nWhat is your name?\n')#Asks name again
number = random.randint(1,6) # Generates random number between 1 and 6
ready = input('\nPress any button to roll the die!\n') # Lets the user know when it's ready
print('Rolling...\n'*4) # Output Rolling... 4 times
print(name,'! Your die shows a ',number,'!\n') # Outputs the name and the number
roll_number = roll_number+1 # Adds 1 to the variable 'roll_number'
decision = input('Do you want to try again? If so please press y, if not please press n. Pressing anything else will stop the program!\n') # Letting the User change the variable so they can use the program
else: # Otherwise
print('Bye!') # Outputs 'Bye!'
謝謝!
continue
僅跳過循環主體的其余部分,它不會退出循環。 這樣,當same_person == 'y'
為true時,您將Python發送回至while decision == 'y'
(注意,此處'y'
的括號完全多余,可以省略)。
使用break
退出循環。 然后,循環末尾的else
語句將不執行,您可能要刪除else:
在該處取消print('Bye!')
行的縮進。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.