簡體   English   中英

簡單骰子擲骰程序問題

[英]Simple dice roll program issue

我創建了一個程序,用戶可以選擇某個側面的骰子,然后擲骰子並輸出生成的數字,然后詢問用戶是否要擲骰子並使用while循環。 我已經編寫了程序,由於某種原因,它會繼續重復輸入骰子邊號提示,但我不知道為什么,這是代碼

import random

roll_agn='yes'
    while roll_agn=='yes':
        dice=input ('Please choose a 4, 6 or 12 sided dice: ')
        if dice ==4:
                print(random.randint(1,4))
        elif dice ==6:
                print(random.randint(1,6))
        elif dice ==12:
                print(random.randint(1,12))
    else:
        roll_agn=input('that is not 4, 6 or 12, would you like to choose again, please answer yes or no') 
    if roll_agn !='yes':
        print ('ok thanks for playing')

我懷疑這與while循環或縮進有關,但是我一直在擺弄它約3分鍾,而我無法使其正常工作,因此,如果有人可以在這里幫助我,將不勝感激,謝謝!

else: roll_agn=input的縮進僅在退出while循環后才運行-但是while循環永遠不會結束,直到您運行else子句,即無限循環。

這是清理后的結構更好的版本:

# assumes Python 3.x
from random import randint

def get_int(prompt):
    while True:
        try:
            return int(input(prompt))         # if Python 2.x use raw_input instead of input
        except ValueError:
            # not an int
            pass

def get_yn(prompt):
    while True:
        value = input(prompt).strip().lower() # if Python 2.x use raw_input instead of input
        if value in {'y', 'yes'}:
            return True
        elif value in {'n', 'no'}:
            return False

def roll(sides):
    return randint(1, sides)

def main():
    while True:
        sides = get_int("Number of sides on die (4, 6, or 12)? ")

        if sides in {4, 6, 12}:
            print("You rolled a {}".format(roll(sides)))
        else:
            print("U no reed gud?")

        if not get_yn("Play again (y/n)? "):
            print("Thanks for playing!")
            break

if __name__=="__main__":
    main()

看起來if語句存在縮進問題。 嘗試將ifif與elif對齊。

if dice ==4:
    print(random.randint(1,4))
elif dice ==6:
    print(random.randint(1,6))
elif dice ==12:
    print(random.randint(1,12))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM