简体   繁体   English

无论如何我可以简化我的 Python 程序吗? 它运行但我觉得实现可能更简单

[英]Is there anyway I can simplify my Python program? it runs but I feel like the implementation could be simpler

This program asks a user at a bank for 3 inputs their bank id number, first name, and last name.该程序要求银行的用户输入他们的银行 ID 号、名字和姓氏 3 次。 If the user input is not the same as the default user (Ryan) then, the user is blocked from continuing, else they are welcomed.如果用户输入与默认用户 (Ryan) 不同,则阻止用户继续,否则欢迎他们。

Can I have a simpler implementation for this我可以为此提供一个更简单的实现吗

f_name = input("What is your first name: ") 
print("You entered:" + f_name)
f_name = f_name

l_name = input("What is your last name: ") 
print("You entered:" + l_name)
l_name = l_name

bid = int(input("What is your bid: "))
print(f"You entered: {bid}")
bid = bid

if f_name == "Ryan" and l_name == "Monaghan" and bid == 12345:
    print("Welcome, Ryan")
else:
    print("Access Denied")

I am a big fan of loops and comparison on data objects instead of values specifically.我非常喜欢循环和数据对象的比较,而不是具体的值。

print('Please enter the following information:')
questions = [
    'First name',
    'Last name',
    'Bid'
]

answers = []

for q in questions:
    answers.append(input(q + ': '))

if answers == ['Ryan', 'Monaghan', '12345']:
    print('Welcome, Ryan')
else:
    print('Access Denied')

output: output:

Please enter the following information:
First name: Ryan
Last name: Monaghan
Bid: 12345
Welcome, Ryan

This is in response to a follow-up question as to how to provide a retry loop if the user input is rejected.这是对后续问题的回应,即如果用户输入被拒绝,如何提供重试循环。

print('Please enter the following information:')
questions = [
    'First name',
    'Last name',
    'Bid'
]

answers = []

while(True): # Loop indefinately
    for q in questions:
        answers.append(input(q + ': '))

    if answers == ['Ryan', 'Monaghan', '12345']:
        print('Welcome, Ryan')
        break # Got a valid response, break out of the loop, note you may want to set a variable here as well to denote a successful response.
    else:
        print('Access Denied')
        r = input('Would you like to retry? (y/n):').lower().strip()
        if r != 'y' and r != 'yes':
            break # user does not want to try again, break out of loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM