简体   繁体   English

如何使用'def'获取输入值

[英]How to use 'def' to get an input value

If I use global variables. 如果我使用全局变量。 I can write like this way. 我可以这样写。

while True:
    name_str = input('Please give me the file name:')
    if name_str == 'table.csv':
        break
    else:
        print('Bad file name, please try again.')

How to def a function and get input from this function? 如何定义函数并从此函数获取输入? Get users' input in the beginning function and call main function to get users' input. 在开始函数中获取用户输入并调用main函数以获取用户的输入。

def get_name(n):
    x = input('Please give me the file name:')
    ...
    ...

def main():
    ...
    ...

You want to have this in a file (test.py): 你想把它放在一个文件(test.py)中:

def get_input():
    return raw_input('get file: ')

if __name__ == '__main__':
    print get_input()

And then call it: 然后叫它:

$ python test.py $ python test.py

Note two things: 注意两件事:

  1. input() vs raw_input() -- input() is not safe input()vs raw_input() - input() 不安全
  2. using idiom 'if name ...' for script environment instead of having main() function. 对于脚本环境使用成语'if name ...'而不是使用main()函数。

Kind of depends on what you're trying to accomplish. 有点取决于你想要完成的事情。

If your method is gathering the information from the user, you can write it this way: 如果您的方法是从用户收集信息,您可以这样写:

def get_name():
    return input('Please give me the file name. ')

If your method is parsing information from the user, it would accept the file name as an argument and be written something like this: 如果您的方法是从用户解析信息,它将接受文件名作为参数,并写成如下所示:

def check_file_name(fname):
    if fname == 'table.csv':
        return True
    return False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM