【问题标题】:issues importing a script导入脚本的问题
【发布时间】:2016-10-01 20:24:40
【问题描述】:

您好,我一直在编写这个简单的脚本,但遇到了一些相当烦人的问题,我无法用 def 修复自己。和导入功能它只是行不通。这是主要脚本

import time         # This part import the time module
import script2      # This part imports the second script

def main():
    print("This program is a calaulater have fun using it")
    name = input("What is your name? ")
    print("Hello",name)
    q1 = input("Would you like to some maths today? ")

if q1 == "yes":
    script2 test()

if q1 == "no":
    print("That is fine",name,"Hope to see you soon bye")
    time.sleep(2)



if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        time.sleep(10)      

然后第二个脚本被称为 script2 这里也是那个脚本 进口时间

def test():
    print("You would like to do some maths i hear.")
    print("you have some truely wonderfull option please chooice form the list below.")

这是我目前的脚本,但它不起作用,请帮助我。

【问题讨论】:

  • 你遇到了什么错误?
  • 尝试script2.test() 而不是script2 test()

标签: python function python-import


【解决方案1】:

首先,您的缩进似乎不正确。正如zvone所说。其次,您应该使用 script2.test() 而不是 script2 test()。一个功能代码是

import time         # This part import the time module
import script2      # This part imports the second script

def main():
    print("This program is a calaulater have fun using it")
    name = input("What is your name? ")
    print("Hello",name)
    q1 = input("Would you like to some maths today? ")

    if q1 == "yes":
        script2.test()

    if q1 == "no":
        print("That is fine",name,"Hope to see you soon bye")
        time.sleep(2)



if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        time.sleep(10) 

【讨论】:

    【解决方案2】:

    这是一个错误:

    def main():
        #...
        q1 = input("Would you like to some maths today? ")
    
    if q1 == "yes":
        # ...
    

    首先,main() 中的q1 和外部的q1 不是同一个变量。

    其次,if q1 == "yes":q1 = input(...) 之前执行,因为尚未调用 main()

    解决方案是从 main 返回 q1 值,然后才使用它:

    def main():
        # ...
        return q1
    
    if __name__ == '__main__':
        # ...
        result_from_main = main()    
        if result_from_main == "yes":
           # ...
    

    当然,现在所有的名字都乱七八糟了,但那是另一个问题……

    【讨论】:

      猜你喜欢
      • 2018-02-08
      • 1970-01-01
      • 2020-08-09
      • 2017-06-18
      • 2019-07-31
      • 2018-12-07
      • 1970-01-01
      • 2015-07-07
      • 2020-12-31
      相关资源
      最近更新 更多