[英]Do break operators turn while loop conditions from True to False?
[英]How to break while loop when two conditions are true - Calculator
我正在建立我的第一個計算器。 嘗試實現While循環以通過用戶輸入獲取數字。 我希望用戶輸入數字后,While才能中斷。
num1 = raw_input("Add mumber one: " )
try:
input = int(num1)
except ValueError:
print "This is not a number"
attempt = 0
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
print "You are not putting number. So, goodbuy"
operation = raw_input("Add Operator: ")
嘗試這個:
for _ in range(5):
num1 = unicode(raw_input("Add number one: "))
if num1.isnumeric():
break
您可以嘗試的另一種方法是使用num1
並在while
循環中執行以下操作:
if type(num1) is int:
break
這是檢查變量num1
的類型。 如果它是整數int
,則它將退出while
循環。
我希望用戶輸入數字后,While才能中斷。
通過使用type(num) != int
,您已經在while
循環的條件下執行了此操作,因此您的while
循環應在用戶輸入整數后停止。
您在這里有幾個錯誤:
while type(num1) != int and attempt < 5:
num1 = raw_input("Add Number one again: " )
attempt += 1
break
break
語句應位於循環內部,但縮進是錯誤的。 在您編寫時,它在循環之后(因此無用)。 同樣,當您從標准輸入中讀取內容時,即使它是一個數字,也始終會得到一個字符串。 因此,當您檢查type(num1) != int
,始終為false。 每次從標准輸入中讀取時,不僅是第一次,都必須用int()
轉換num1
:
while True:
num1 = raw_input("Add Number one again: " )
try:
input = int(num1)
break
except ValueError:
print "This is not a number"
if attempt == 5:
break
attempt += 1
在這里,我嘗試將從stdin讀取的字符串轉換為整數。 如果有效,我會立即中斷循環。 如果它不起作用(except子句),則檢查已進行了多少次嘗試,如果嘗試次數等於5,則中斷循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.