【问题标题】:importing functions in python from another script I made从我制作的另一个脚本中导入python中的函数
【发布时间】:2015-10-24 00:52:30
【问题描述】:

我遇到了一个问题,我的老师要我从另一个脚本导入函数

def readint():
    prompt = int(input("Enter an integer: "))
    print(" You entered: ",prompt," and the type is", type(prompt))

然后在另一个程序上我可以像这样导入它

import test 

test.readint()

但是当我试图完全按照她想要的方式得到它时

test.readint(prompt)

我似乎无法让它工作。我试过了,但它似乎不起作用

def readint(prompt):
prompt = int(input("Enter an integer: "))
print(" You entered: ",prompt," and the type is", type(prompt))
return prompt

任何解释将不胜感激!

【问题讨论】:

  • 您是否导入了其他脚本?另外,您似乎没有掌握函数参数的用途。
  • 是的,我导入了另一个脚本,但我正在为函数而苦苦挣扎。我必须为 3 个独立的功能做这件事
  • @Austin。您缺少导入。如果readint() 在名为test.py 的文件中,则在您计划使用test.readint() 的文件中执行from test import *
  • 使用像test.readint() 这样的命名空间实际上需要import test,而不是from test import *
  • @Austin:如果上述建议不起作用,您可能希望显示更多代码以及您的文件结构。

标签: python function import


【解决方案1】:

打印语句中的逗号可能有问题。

当我运行你的初始程序时,我得到了这个:

>>> 
Enter an integer: 3
(' You entered: ', 3, ' and the type is', <type 'int'>)

这似乎不像你想要的(它是一个元组)

你似乎想要打印的是字符串,

You entered: 3 and the type is <type 'int'>

为此,您需要将变量转换为字符串。


test.py

def readint(prompt):
    prompt = int(input("Enter an integer: "))
    print ("You entered: " + str(prompt) + " and the type is " + str(type(prompt)))
    return prompt

ma​​in.py

import temp

prompt = None
temp.readint(prompt)

注意+ 运算符和str 转换


对我来说,这会输出以下内容:

>>> 
Enter an integer: 3
You entered: 3 and the type is <type 'int'>

看起来就是你要找的东西。


附带说明一下,我不确定您为什么要传入 prompt 变量,因为它可以被忽略,并且没有理由将它放在其中。简单地将其从函数定义中删除而不将其传入是完全有效的:

def readint():
    ...

import test
test.readint()

编码愉快!

--艾利泽

【讨论】:

    【解决方案2】:

    首先,当您获得提示的值时,不要将结果打印到屏幕上,而是尝试将其作为字符串返回。这样,您可以将返回值分配给变量并稍后访问它。很整洁吧?你的第二次尝试已经成功了,但是有两个小问题:

    向这个函数传递参数是没有意义的。这是因为input() 已经在变量中存储了一个值,因此传递参数没有意义,您可以创建一个函数变量并将其存储在其中。此外," and the type is",type(prompt)) 也没有任何意义。这样做的原因是因为我们已经知道它是一个整数:你在得到它的字符串值后将prompt 的结果转换为一个整数。如果您向提示传递了一个无法转换为整数的值,您将得到一个ValueError。因此,请尝试使用以下代码:

    def readint():
        prompt = int(input("Enter an integer: "))
        return "You entered " + str(prompt)
    

    这样,在您的其他文件中,您可以这样做:

    >>> import test
    >>> a = test.readint()
    Enter an integer7
    >>> a
    'You entered 7'
    >>> 
    

    (请记住,三个 > 符号不是 python 代码,它来自 shell) 如果您要输入要转换为整数的无效值,则会引发ValueError。我们怎样才能防止这种情况发生?您可以使用tryexcept 语句。基本上,它的作用是尝试做某事,然后,如果在该过程中引发异常,它会做其他事情。

    所以,总而言之。您的代码如下所示:

    def readint():
        try:
            prompt = int(input("Enter an integer: "))
        except ValueError:
            return "Invalid value! It must be a number."
        return "You entered " + str(prompt)
    

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 2018-09-23
      • 2021-12-20
      • 1970-01-01
      • 2020-04-21
      • 2017-07-26
      • 2019-08-03
      • 1970-01-01
      相关资源
      最近更新 更多