[英]Invalid syntax by using else statement
如果有人能解釋為什么我在 else 語句中遇到語法錯誤,我將不勝感激。
x = 0
digits = 0
while(x != 0):
x = x // 10
digits += 1
print(digits)
else(x == 0):
print(1)
我必須創建一個使用 while 循環和條件語句的代碼,它在其中評估 integer 包含的位數。 否則需要else循環,否則如果我有x = 0,它將打印0作為否。 數字當然是錯誤的。
我們想知道是否x == 0
first ,並專門處理這種情況。 如果不是,那就是我們使用while
循環的時候,所以將所有這些都縮進到else
中。 因此:
if x == 0:
print(1)
else:
while(x != 0):
x = x // 10
digits += 1
print(digits)
x = 10000
digits = 0
while x != 0:
x = x // 10
digits += 1
if x == 0: # you only want to print once when you have digits correct so check here
print(digits) # print your digits
break # break your loop
else: # remove the expression here for the else (not elif)
print(1)
好像:
>>> x = 10000
>>> digits = 0
>>>
>>> while x != 0:
... x = x // 10
... digits += 1
... if x == 0:
... print(digits)
... break
... else:
... print(1)
...
5
編輯:
正如 Karl 在評論中指出的那樣,這不是 Python 中的常規做法。 這個答案是這樣的,因為您似乎特別想使用while/else
,這就是這樣做的方法。 將其重新組織為他在回答中的方式更為常見,但如果這是您的要求,則不滿足執行while/else
的任何要求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.