python - 将输入语句连接到python中的函数

标签 python function input

我对堆栈溢出有点陌生,但我正在尝试编写这段代码,以便在用户回答输入问题后,代码返回函数 hammer_time 中概述的答案,我该如何提示用户输入答案以使函数返回我想要的结果?我在用户输入和函数之间的连接哪里出了问题?

hour = input("What time is it?")

def hammer_time(hour):
    if hour  >= 7 and hour <= 9:
        print("It's breakfast time!")

    elif hour >= 12 and hour <= 2:
        print("It's lunch time!")

    elif hour >= 7 and hour <= 9:
        print("It's dinner time!")

    elif hour >= 10 and hour <= 4:
        print("It's hammer time!")
    else:
        print("Nothing is scheduled at this time.")

最佳答案

Where is my connection between the user input and the function going wrong?

好吧,实际上无处可去,因为您从不“连接”它们。在这种情况下,“连接”用户输入和函数是通过调用函数来完成的,将用户输入作为参数传递给它,即:

def hammer_time(hour):
    # your code here

hour = input("What time is it?")
hammer_time(hour)

请注意,最好让您的函数返回 一个值,然后执行 print()在函数之外,即:

def hammer_time(hour):
    if hour  >= 7 and hour <= 9:
        return "It's breakfast time!"

    elif hour >= 12 and hour <= 2:
        return "It's lunch time!"

    elif hour >= 7 and hour <= 9:
        return "It's dinner time!"

    elif hour >= 10 and hour <= 4:
        return "It's hammer time!"
    else:
        return "Nothing is scheduled at this time."

hour = input("What time is it?")
msg = hammer_time(hour)
print(msg)

此外,如果您使用 Python3,input()将返回一个字符串,因此 hammer_time 中的所有测试会失败("3" - string - 不是 3 - int),所以你可能想要制作 hour一个整数:

hour = int(input("What time is it?"))
msg = hammer_time(hour)
print(msg)

如果您使用的是 python 2.x,input()如果他输入一个数字,将自动将用户输入转换为 int,但这实际上是一个非常危险的功能(它转换为 int 的方式是使用 eval() 这是一个巨大的安全漏洞,我让你谷歌这个), 所以你想使用 raw_input()而是自己进行转换:

hour = int(raw_input("What time is it?"))

最后 hammer_time() 中有几个逻辑错误:

    if hour  >= 7 and hour <= 9:
        return "It's breakfast time!"

这里:

    elif hour >= 12 and hour <= 2:
        return "It's lunch time!"

一个数字不能同时大于等于 12 和小于等于 2。您必须在此处使用基于 24 小时的表示法(2pm 是 12+2=14)

这里:

    elif hour >= 7 and hour <= 9:
        return "It's dinner time!"

这种情况永远不会发生,因为它已经被第一个 if hour >= 7 and hour <= 9 捕获了以上测试。同样的问题,您需要基于 14 小时的表示法。

这里:

elif hour >= 10 and hour <= 4:
    return "It's hammer time!"

同上问题:一个数字不能同时是 >= 10 和 <= 4。

关于python - 将输入语句连接到python中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48440057/

相关文章:

php - 输入文本和特殊字符以及MySQL

python - 在 Python 中除以零会导致 Windows 98 等崩溃吗?

python - 操作groupby对象

Azure 函数主机自动停止且不重新启动

function - Excel - 将一列与另一列进行比较并显示结果

html - 问题系统的 CSS 输入字段和按钮位置

python - win32 : simulate a click without simulating mouse movement?

python - 如何使用行数和列名从 CSV 文件调用组件

R从函数调用中获取参数名称

java - 代码仅在我使用断点时才有效 - 可能是线程问题