Python - 使用函数创建 "if"语句并获得返回而不重复

标签 python

这很可能是一个非常基本的问题,因为我前几天刚刚开始使用 Python,但我找不到任何文档。我正在练习一个基本的文本冒险程序。

这就是我所设置的:该程序会处理一系列特定问题。当用户提供输入时,该输入将通过一个函数来查看它是否包含关键字 inv(库存)。如果是这样,程序将显示库存字典。如果没有,该函数将返回原始输入值以便程序继续。

这是我当前的“信息”功能

def info(s):
inputinventory = s
if inputinventory == 'inv':
    print ('\n###INVENTORY###')  

        #here it would print my dictionary - don't worry about this

    #asks user to input again to continue question if 'inv' has been typed
    info(input())
else:
    #script will return the original input value if 'inv' is not typed
    return inputinventory

该功能的实现:

print ('How old are you? ')
if info(input()) == '12':   #just an example
    print ('some example text')
elif info(input()) == '13':  #the troublesome line
    print ('more example text')

我遇到的问题是 elif 语句无法正常工作,因为它需要输入。这是我研究测试返回值的方法 - 如果不一遍又一遍地编写函数来获取它的返回值,我无法找出如何获取它。有没有办法解决这个问题,还是我让事情变得困难?

编辑: 等等 - 我打赌我可以只运行该函数一次并将其分配给一个变量...让我们快速尝试...但是如果用户输入“inv”可能就行不通

最佳答案

您希望将 info() 的返回值存储为变量。

print ('How old are you? ')
user_value = info(input()) # store it is a variable
if user_value == '12':
    print ('some example text')
elif user_value == '13':
    print ('more example text') # it works!

关于Python - 使用函数创建 "if"语句并获得返回而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259390/

相关文章:

python - Pylint 消息 : Invalid constant name (invalid-name)

python - 由于缺少 CSRF,表单验证失败

Python 查找问题

python - 为什么 django ORM 比原始 SQL 慢得多

python - 为什么 `bin` 目录在 Windows 上的名称不同 (`Scripts` )?

python - 交换由分隔符分隔的最后 2 个列字符串

python - matplotlib动画内存泄漏

python - ProcessPoolExecutor 传递多个参数

python - SA : can I have a 'year' column_property for a Date column?

python - 使用 Django 存储数据库设置的最佳方式是什么?