sides=int(input("Please enter the amount of sides on the dice: "))
times=int(input("Please enter the number of times you want to repeat: "))
我想重複這兩行,直到用戶輸入每個請求的整數。
感謝如何在python中重複使用
sides=int(input("Please enter the amount of sides on the dice: "))
times=int(input("Please enter the number of times you want to repeat: "))
我想重複這兩行,直到用戶輸入每個請求的整數。
感謝如何在python中重複使用
鬆鬆閱讀,
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError: # wasn't an int
pass
sides = get_int("Please enter the amount of sides on the dice: ")
times = get_int("Please enter the number of times you want to repeat: ")
,但如果你嚴格想重複都語句,直到都得到一個int值,
while True:
s1 = input("Please enter the amount of sides on the dice: ")
s2 = input("Please enter the number of times you want to repeat: ")
try:
sides = int(s1)
times = int(s2)
break
except ValueError:
pass
sides=0;times=0
while(sides == 0 and times == 0):
sides=int(input("Please enter the amount of sides on the dice: "))
times=int(input("Please enter the number of times you want to repeat: "))
它返回錯誤,我必須重新加載代碼。我想重複這兩行,直到用戶輸入每個請求的整數。 – user3358812
它會返回一個錯誤,因爲您將代碼告訴「int()」,無論用戶給它什麼。如果它不是數字會發生什麼? Python會拋出一個錯誤。閱讀['try/catch'](http://docs.python.org/3.2/tutorial/errors.html)語句來捕獲該錯誤並繼續執行 –
的好地方開始將瞭解[while循環](https://wiki.python.org/moin/WhileLoop)。然後,看看http://stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except –
看看一些教程和[文檔](http://docs.python.org/2/tutorial/controlflow.html#for-statements),並在卡住時報告。在學習該語言的基本基礎之前,您不會真正從Stack Overflow中獲得最大收益。 – mhlester
類似於do-while循環的東西 – user3358812