所以我有一個游戲,你必須猜測代碼隨機選擇的數字(我在看專案想法),然后再看答案,我想知道是否有更有效的存盤 if 的方法?我確實認為可能有一種方法可以將它們合并到一個塊中并洗掉其他塊。
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
attempt_num = 4
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(attempt_num)))
attempt_num -= 1
if attempt_num < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
if guess == ran_num:
print("success")
guess(5)
uj5u.com熱心網友回復:
只需詢問回圈內的猜測即可。您可以使用for回圈迭代 4 次。
def guess(x): # this is a number generator
ran_num = random.randint(1, x)
for attempt_num in range(4, 0, -1):
guess = int(input('type number guess from 1 to {}, you gots {} attempts left '.format(x, attempt_num)))
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
else:
print("success")
break
else:
print('game over')
guess(5)
uj5u.com熱心網友回復:
您有一些重復的代碼,因此最好將if-else塊放入一個函式中,這將簡化您的代碼。
我添加了一個check_guess函式,并將其設為ATTEMPT_NUM全域,以便我們可以參考它并在兩個函式中更新它。
import random
ATTEMPT_NUM = 4
def guess(x): # this is a number generator
global ATTEMPT_NUM
ran_num = random.randint(1, x)
guess = int(input('type number guess from 1 to {} '.format(x)))
check_guess(ran_num, guess)
while guess != ran_num:
guess = int(input('oh no, your number is incorrect, please type that again, you gots {} attempts left '.format(ATTEMPT_NUM)))
ATTEMPT_NUM -= 1
check_guess(ran_num, guess)
if guess == ran_num:
print("success")
def check_guess(ran_num, guess):
global ATTEMPT_NUM
if ATTEMPT_NUM < 1:
print('game over')
exit()
elif guess < ran_num:
(print('your guess was a bit low'))
elif guess > ran_num:
print('your guess was all too high')
guess(5)
uj5u.com熱心網友回復:
我做了這個嘗試。x 是你能得到的最大亂數,對吧?將所有內容組合在一個無限回圈中,只有在您獲勝或輸入錯誤所有數字后才會中斷。
def guess(x):
attempt_num = 5
ran_num = random.randint(1, x)
while True:
guess = int(input('type number guess from 1 to {} '.format(x)))
if guess == ran_num:
print ("congrats")
break
elif guess < ran_num:
(print('your guess was a bit low'))
attempt_num = attempt_num -1
elif guess > ran_num:
print('your guess was all too high')
attempt_num = attempt_num -1
print (attempt_num)
if attempt_num == 0:
print ("game over")
break
不過,如果您在輸入中做一個小檢查以避免用戶輸入除數字之外的任何其他內容,這不會有什么壞處。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/492023.html
下一篇:排序保留2個專案在頂部
