Python Atm程序- if else语句接受错误答案



我是CS的初学者,我想添加一个引脚选择到一个简单的ATM程序。第一次输入错误的pin时,它打印无效的pin消息,但第二次,我尝试的方式,它要么接受错误的pin,要么在输入错误的pin时停止。我的目标是让它一直询问pin,直到输入正确的pin。我试着把它写成if语句和while true语句任何提示都非常感谢

# Constants for choice options
BALANCE = 1
DEPOSIT = 2
WITHDRAW = 3
QUIT = 4
pin = 1234
def main():
print("Welcome to STAR ATM!")
pin = (int(input('nPlease enter your pin number: ')))
while pin == 1234:
showMenu()
else:
print('nWrong pin please try again')
(input('nPlease enter your pin number: '))

这不是整个程序,这只是引脚部分如果我需要发布整个程序请告诉我

而不是让while pin == 1234改变代码说while pin != 1234循环直到引脚等于1234。这样,您就可以按照自己的喜好多次重试pin,直到正确为止。为了改进这一点,您可以创建第二个变量pin_attempt,这是用户将添加的引脚,这样您就可以拥有循环While pin_attempt != pin:,这样您就可以随时更改引脚变量,而无需更改它的所有实例。

同样,你不应该改变变量pin本身,因为它保存着pin。如果您确实更改了变量pin,那么将其声明为1234就没有意义了,因为您在使用变量之前就立即更改了存储的内容。因此,拥有pin = 1234将是无用的。

您还应该将pin存储为string而不是integer。这是因为string是一个可以设置的密码,而不是可以更改的integer

# The credit card's PIN
pin = '1234'
# First attempt at the pin
pin_attempt = input('What is your pin?: ')
# If pin_attempt was incorrect this loop will run
while pin_attempt != pin:
# Enter the new attempt, after the new attempt will be checked
# If the new attempt is not equal to pin, the code will loop
pin_attempt = input('That pin is incorrect, try again: ')
# Any code that you want to run once the pin is entered correctly goes here

您可以更进一步,为每个猜测添加一个计数器减数。如果猜的次数用完,他们就不能再猜了。

# The credit card's PIN
pin = '1234'
# Guess counter
counter = 3
# First attempt at the pin
pin_attempt = input('What is your pin?: ')
# If pin_attempt was incorrect this loop will run
while pin_attempt != pin:
# Enter the new attempt, after the new attempt will be checked
# If the new attempt is not equal to pin, the code will loop
counter -= 1 # Counter decrement by 1
if counter == 0:# break loop if counter is 0
lock_machine() # function to lock the machine if too many wrong guesses
pin_attempt = input('Incorrect, you have ' + str(counter) + ' more guesses: ')
# Any code that you want to run once the pin is entered correctly goes here

试试这个:

while pin != 1234:
print('nWrong pin please try again')
pin = input('nPlease enter your pin number: ')
showMenu()

要增加@stuupid的答案,您可以创建一个函数来处理输入,直到满足一般情况下的标准。

def input_until(prompt, error_msg, predicate, attempts=None, attempts_msg=None):
attempt_no = 1
user_input = input(prompt)
while not predicate(user_input):
attempt_no += 1
if attempts and attempt_no >= attempts:
if attempts_msg:
print(attempts_msg)
return None
print(error_msg)
user_input = input(prompt)
return user_input
此时,您的代码基本上可以是:
user_input = input_until('Please enter your pin number: ', 'Wrong pin please try again', lambda p: p == '1234')

或:

user_input = input_until('Please enter your pin number: ', 'Wrong pin please try again', '1234'.__eq__)

最新更新