[英](python) How to check the validity of a while loop before letting the user to input things?
import random
numberList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'jack', 'queen', 'king']
total = 0
while total <= 21:
output = random.choice(numberList)
if output == 'jack' or output == 'queen' or output == 'king':
print(f'({output})')
output = 10
print(f'you got {output} points')
total += output
ask_cont = input(f'you now have {total} points, continue? [y/n]: ').lower()
if ask_cont == 'y':
continue
else:
print(f'game finished. You gain {total} points!')
break
else:
print(f'you lost! points exceeded = {total - 21} points!')
我正在編寫二十一點游戲。 但是,在 while 循環中(條件:手頭總量 <= 21),當它超過21 個點時,它仍然要求我在代碼完成之前是否繼續( ask_cont變量)或不繼續 [y/n] 如果我輸入'n',它只是給我當前點數(>21)和'游戲結束'聲明。 我怎樣才能解決這個問題? 非常感謝
(另外,如果有任何方法可以修剪代碼,請發表評論,非常感謝!)
首先,不要擔心您的代碼過於冗長。 擁有長而易讀的代碼比短而難破譯的代碼要好。 你的代碼看起來很好。
至於如果total > 21
阻止用戶繼續,這是因為您在達到while total <= 21
之前要添加到total += output
。 要解決此問題,您只有兩個選擇。
第一個是讓它在 while 循環開始時詢問,然后再添加點。 如果你這樣做,你也會讓它在 while 循環開始之前詢問一次。 通常您會使用do..while
循環來執行此操作,但 python 沒有這些。
第二個選項是只添加一個額外的 if 語句,它只要求您繼續 if total <= 21
,否則它會執行一些以超出消息結束游戲的操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.