[英]In python I have a print statement after my else: yet it does not seem to actually print it after running the code
pin1 = int(input("Please set a pin: "))
print("Welcome to Satan's Soul Bank, Enter ya pin!")
attempt = int(input("Please enter your pin number first"))
if attempt == pin1:
print("Select operation.")
print("1.Deposit Souls")
print("2.Withdraw Souls")
print("3.Check Soul balance")
choice = int(input("Enter choice(1/2/3):"))
elif attempt != pin1:
for i in range(2):
attempt = int(input("Invalid Attempt Please enter your pin
number again"))
else:
print ("Card Swallowed Contact SATAN")
代碼本身在其他情況下與print語句分開工作:似乎無法識別它,只是錯過了它,基本上我需要它打印卡已被吞咽3次,但是當我將其放入elif區域時,它只是每次我弄錯引腳時都會打印該卡片,是否還有其他方法可以解決該問題,從而導致打印第三遍后卡被吞下
如其他答案所述, elif
塊覆蓋了if
塊不滿足的條件。 為了確保在else
塊中打印該語句,可以使用一個flag
變量,該flag
變量將在最大錯誤嘗試次數之前被設置為false
。 一旦達到最大嘗試次數 ,將flag
設置為true
。
如果該flag
被設置為true
, print
“卡吞。 聯系撒旦...'
您需要重組代碼以獲取所需的內容。
pin1 = int(input("Please set a pin: "))
print("Welcome to Satan's Soul Bank, Enter ya pin!")
correct_pin = False
for i in range(3):
attempt = int(input("Please enter your pin number first"))
if attempt == pin1:
correct_pin = True
break
else:
print("Invalid PIN. {} attempts remain.".format(2 - i))
if correct_pin:
print("Select operation.")
print("1.Deposit Souls")
print("2.Withdraw Souls")
print("3.Check Soul balance")
choice = int(input("Enter choice(1/2/3):"))
else:
print ("Card Swallowed Contact SATAN")
我們循環播放3次,如果用戶獲得了正確的密碼,則退出,僅在密碼正確的情況下才提供其他選項。
在您的代碼中
if attempt == pin1:
...
elif attempt != pin1:
...
由於其中一個條件始終成立( attempt
等於或不等於pin1
),因此程序將永遠不會到達else
部分。
在你的代碼中的“其他”塊只有在運行if
和elif
塊都是假的。 發生這種情況的唯一方法是,如果(attempt == pin1)
為false 並且 (attempt != pin1)
為false。
如您所見,這是不可能的,因為它們相等或不相等-兩者都不可以。 這就是為什么print ("Card Swallowed Contact SATAN")
永遠不會運行的原因。
看來,您希望該程序的行為類似於以下內容:
pin1 = int(input("Please set a pin: "))
print("Welcome to Satan's Soul Bank, Enter ya pin!")
attempt = int(input("Please enter your pin number first"))
if attempt == pin1:
print("Select operation.")
print("1.Deposit Souls")
print("2.Withdraw Souls")
print("3.Check Soul balance")
choice = int(input("Enter choice(1/2/3):"))
elif attempt != pin1:
for i in range(2):
attempt = int(input("Invalid Attempt Please enter your pin number again"))
print ("Card Swallowed Contact SATAN")
兩次錯誤嘗試后,您想告訴用戶聯系SA **
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.