如何在python中输入输入 [英] how to enter input in python

查看:153
本文介绍了如何在python中输入输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在参加比赛,但不知道如何让python接受输入.这是一个典型的示例.该网站给出了如何输入的示例,但这些示例使用的是C和Java(单击此处 ).请帮助我弄清楚在这种情况下如何使python接受输入.

I am taking part in a competition, but have no idea how to make python take the input. Here's a typical example . The site has given example of how to take input but those are using C and Java ( click here ). Please help me figure out how to make python take the input in this case.

推荐答案

有多种方法可以做到这一点.

There's more than one way to do this.

接受口译员的输入

对于Python 2.x,您可以使用 raw_input() 功能:

For Python 2.x, you can use the raw_input() function:

my_input = raw_input("Please enter an input: ")
#do something with my_input

请注意,输入始终为字符串.要检索数字,可以使用内置的int()函数:

Note that the input is always a string. To retrieve a number, you can use the built-in int() function:

my_input = int(raw_input("Please enter an input: "))
#do something with my_input

作为另一个答案,如果输入为浮点数,则将引发错误.

As one other answer mentioned, this will throw an error if the input is a float.

Python 2.x中还有另一个函数input.但是,在此版本的Python中,input会评估输入,这是一个坏主意.不建议使用它.

There's also another function, input, in Python 2.x. However, in this version of Python, input evaluates the input, which is a bad idea. It's not recommended to use it.

对于Python 3.x,您可以使用 input() 函数没有任何问题,因为它可以替换raw_input:

For Python 3.x, however, you can use the input() function without any problem, since it's a replacement for raw_input:

my_input = input("Please enter an input: ")
#do something with my_input

从命令行参数中获取输入

执行如下脚本时,您还可以从命令行参数中检索输入:

You can also retrieve your input from command line arguments, when executing your script like this:

$ python my_script.py arg1 arg2

参数将存储在列表sys.argv中. sys.argv[0]是第一个参数,sys.argv[1]是第二个参数,依此类推.
示例:

The arguments will be stored in the list sys.argv. sys.argv[0] is the first argument, sys.argv[1] is the second argument, and so on.
Example:

import sys
my_input = sys.argv[0]
#do something with my_input

此处查看详细信息 此方法适用于Python 3.x和2.x两种版本.

See the details of it here This method works for both versions, Python 3.x and 2.x .

希望这会有所帮助!

这篇关于如何在python中输入输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆