如何根据用户输入执行不同的打印功能

how to execute different print function based on the users input

提问人:Bama 提问时间:11/12/2023 更新时间:11/13/2023 访问量:146

问:

我是编码和 python 的完全初学者,所以它可能非常简单。所以我的问题是我正在学习如何根据用户输入放置 if 和 else 函数,我不知道如何在两者之间连接。

age = input("enter your age: ")
yes = "welcome"
no = "too bad then"
ans = [yes, no]
if age == "18":
    print(yes)
else: 
    input("you're not old enough, would you like to enter anyways?: {ans} ")
    if yes:
        print(yes)
    else:
        print(no)

这是我根据我到目前为止学到的东西制作的代码,它可能充满了错误。我想将“if”和“else”函数连接到答案是“是”或“否”,这将打印不同的东西。input("you're not old enough, would you like to enter anyways?: {ans} ")

python if 语句 输入

评论

0赞 Reilas 11/12/2023
print(yes if ((age := input(“enter your age: ”)) == 18) else yes if input(f“你还不够大,你还是想输入吗?: {ans} ”) == yes else no).
0赞 OM222O 11/12/2023
@Bama我已经对原始答案进行了相当多的更新,因此请回来查看,如果您有任何问题,请告诉我
0赞 tripleee 11/13/2023
print在两种情况下是相同的功能;你想用不同的参数来调用它。

答:

0赞 Bibhav 11/12/2023 #1

您可以创建函数。我在这里命名了它,它打印 if is passed 和 print
if is passed:
messagewelcomeTruetoo bad thenFalse

# Use int while you ask for an integer
age = int(input("enter your age: "))

def message(msg):
    if msg is True:
        print("welcome")
    elif msg is False:
        print("too bad then")

if age == 18: #It's probably "age >= 18" that you need
    message(True)
else: 
    enter = input("you're not old enough, would you like to enter anyways?: ")
    if enter.strip().lower() in ["yes","y"]:
        message(True)
    elif enter.strip().lower() in ["n","no"]:
        message(False)
    else:
        print("Invalid input exiting...")

评论

1赞 OM222O 11/12/2023
1)你不需要检查,你可以简单地做: 2)年龄大于18岁会怎样?90岁太年轻了吗?3)如果答案不是明确的是,你应该假设它是否定的,以避免更多的边缘情况,例如,输入的消息是什么或“也许”是什么?你不需要那么明确和if boolean is Trueif booleanunsureprint("Invalid input exiting...")
0赞 OM222O 11/12/2023 #2

请注意,当使用 时,只要第一个表达式(按指定的顺序)是 ,下一个表达式就会被忽略,因为结果将无关紧要。使用时也会发生同样的情况;一旦找到 A,下一个表达式就会被忽略,因为结果将是orTrueTrueandFalseFalse

对于您的具体问题,解决方案是:

if int(input("enter your age: ")) >= 18 or input("you're not old enough, would you like to enter anyways? ").lower().startswith('y'):
    print("welcome")  
else: 
    print("too bad then")

对于更通用的任务(编写解释器或类似任务),您需要使用函数指针和查找表(通常是字典)。 下面是一个工作示例:

import math
import time

def add(*args):
    "Adds numbers together"
    if len(args)>0:
        print(sum((float(arg) for arg in args)))

def mult(*args):
    "Multiplies numbers together"
    if len(args)>0:
        print(math.prod((float(arg) for arg in args)))
        
def nothing(*args):
    pass
        
def alias(*args):
    "Creates a new alias for a given action"
    action, alias, *_ = args
    if action not in LUT:
        print("Cannot create an alias for an undefined action!")
    else:
        aliases[alias]=action
        print(f"Successfully created alias '{alias}' for '{action}'")
    
def print_help(*args):
    "Displays valid options and what they do"
    for keyword in LUT:
        doc = LUT[keyword].__doc__
        print(f"{keyword} : {doc if doc is not None else '?'}")
    print(f"To exit the program, type any one of: {', '.join(termination_keywords)}")
    
def print_aliases(*args):
    groupings= {action : [] for action in LUT}
    for alias in aliases:
        groupings[aliases[alias]].append(alias)
    for action, aliases_ in groupings.items():
        if len(aliases_)>0:
            print(f"{action} : {', '.join(aliases_)}")
    
# Look Up Table
LUT = {
    'help':print_help,
    'add':add,
    'mult':mult,
    'nop' : nothing,
    'alias' : alias,
    'print_aliases': print_aliases
    }

aliases = {
    '+':'add',
    'sum':'add',
    'total': 'add',
    '*':'mult',
    'multiply':'mult',
    'prod':'mult',
    'nothing' : 'nop',
    'pass': 'nop'
}
    
termination_keywords = {'end','exit','quit','q'}

print(f"""Enter your the desired action and its arguments as space seperated values.
For example: add 1 2 3 4 5

Defined actions are:""")
print_help()
# Sometimes the input is displayed before the help is done printing, a small delay fixes the issue
time.sleep(0.5)

while True:
    print("#"*20)
    action, *args = input("What do you want to do? ").split(' ')
    action = action.lower()
    if action in termination_keywords:
        break;
    if action in LUT:
        LUT[action](*args)
    elif action in aliases:
        LUT[aliases[action]](*args)
    else:
        print("Undefined action!")

评论

0赞 Emilio Silva 11/13/2023
直接的答案是可以的,但你因为在下一部分太详细而被否决了。请考虑这个问题是由初学者提出的。
0赞 OM222O 11/14/2023
确切地说,最好学习解决问题的最佳实践和正确的方法,而不是仅仅以初学者为借口来学习糟糕的编程。我每天必须修复的大量可笑的糟糕代码源于“初学者”程序员,他们懒得学习如何做某事。您可能还想查看每日WTF thedailywtf.com