如何从其他程序中获取输入

时间:2015-03-07 22:27:17

标签: python

第一个程序:

import destinations
import currency

main_function = True
while (main_function):

def main():

    # Determine length of stay
    while True:
        try:
            length_of_stay = int(input("And how many days will you be staying in " + destination + "? "))
            # Check for non-positive input
            if (length_of_stay <= 0):
                print("Please enter a positive number of days.")
                continue
        except ValueError:
            print("The value you entered is invalid. Only numerical values are valid.")
        else:
            break

第二个程序:

def get_choice():
# Get destination choice
while True:
    try:
        choice = int(input("Where would you like to go? "))
        if (choice < 1 or choice > 3):
            print("Please select a choice between 1 and 3.")
            continue
    except ValueError:
        print("The value you entered is invalid. Only numerical values are valid.")
    else:
        return choice

choice = get_choice()

def get_info(choice):
# Use numeric choice to look up destination info
# Rates are listed in euros per day

    # Choice 1: Rome at €45/day
    if (choice == 1):
        return "Rome", 45


    # Choice 2: Berlin at €18/day
    elif (choice == 2):
        return "Berlin", 18

    # Choice 3: Vienna, €34/day
    elif (choice == 3):
        return "Vienna", 34

destination = get_info(choice)

问题:输入后第一个程序运行时出错: “NameError:名称'目的地'未定义”

问题:如何添加destination = get_info(choice)并不算作定义destination? 我该怎么做才能让第一个程序同意第二个程序的输入?

1 个答案:

答案 0 :(得分:0)

import destinations将运行具有该名称的模块,该模块应位于PythonPath上(否则将引发ImportError)。这很好。运行该文件后,可在命名空间destinations下访问其中定义的所有变量,函数和类。

所以在名为destinations.py的文件中,如果有一个名为destination的变量(你在file2的最后一行上创建),那么你可以从内部destinations.destination访问它第一个文件(或任何具有import语句import destinations的文件)。

您可以在effbot上了解从不同模块导入项目的不同方法。它会教你另一个有吸引力的替代方案就是写

from destinations import destination

然后你的第一个文件将正常工作。

请注意,您在此处复制的代码似乎存在一些缩进问题。此外,每次你需要单词(“Rome”,“Berlin”,..)时,你都想写(在第一个文件中)destination[0],因为你的函数get_info来自第二个文件(destinations.py),返回一个元组(例如("Rome", 45)。如果您不考虑这一点,您将获得TypeError

相关问题