如何在python中进行简单的用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4730949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:14:10  来源:igfitidea点击:

How do I do simple user input in python?

pythoninputuser-input

提问by Zack Shapiro

I'm just playing with input and variables. I'm trying to run a simple function:

我只是在玩输入和变量。我正在尝试运行一个简单的函数:

slope = (y2-y1)/(x2-x1)

I'd like to prompt the user to enter y2, y1, x2and x1. What is the simplest, cleanest way to do this?

我想提示用户输入y2y1x2x1。什么是最简单、最干净的方法来做到这一点?

采纳答案by carl

You can use the input()function to prompt the user for input, and floatto convert the user input from a string to a float:

您可以使用该input()函数来提示用户输入,float并将用户输入从字符串转换为浮点数:

x1 = float(input("x1: "))
y1 = float(input("y1: "))
x2 = float(input("x2: "))
y2 = float(input("y2: "))

If you're using python 2, use raw_input()instead.

如果您使用的是 python 2,请raw_input()改用。

回答by Greg Hewgill

This is the simplest way:

这是最简单的方法:

 x1 = float(raw_input("Enter x1: "))

Note that the raw_input()function returns a string, which is converted to a floating point number with float(). If you type something other than a number, you will get an exception:

请注意,该raw_input()函数返回一个字符串,该字符串通过 转换为浮点数float()。如果您键入的不是数字,则会出现异常:

>>> float(raw_input())
a
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for float(): a

If you're using Python 3 (it sounds like you are), use inputinstead of raw_input.

如果你正在使用Python 3(这听起来像你是),使用input代替raw_input

回答by joshim5

You can use:

您可以使用:

foo=input('Please enter a value:')

Where the string 'Please enter a value:' would be your message, and foo would be your variables.

其中字符串 'Please enter a value:' 将是您的消息,而 foo 将是您的变量。

回答by anjani jha

If the user is entering the inputs in just one line with space as delimiting word between those inputs, you can write:

如果用户仅在一行中输入输入,并在这些输入之间使用空格作为分隔词,您可以这样写:

val1, val2, val3 = raw_input().split(' ')

Now, you can change it to:

现在,您可以将其更改为:

val = float(val1)

The awesome trick is that in this way you don't waste your space creating a new list and storing your values in that and then fetching it.

绝妙的技巧是,通过这种方式,您不会浪费空间来创建新列表并将值存储在其中然后获取它。