Python 3 – 输入()函数
在Python中,我们使用input()函数来获取用户的输入。无论您输入什么作为输入,输入函数都会将其转换为字符串。如果您输入一个整数值,仍然 input()函数将其转换为字符串。
Syntax: input(prompt)
Parameter:
- Prompt: (optional) The string that is written to standard output(usually screen) without newline.
Return: String object
让我们看看例子:
示例 1:接受用户的输入。
Python3
# Taking input from the user
string = input()
# Output
print(string)
Python
# Taking input from the user
name = input("Enter your name")
# Output
print("Hello", name)
Python3
# Taking input from the user as integer
num = int(input("Enter a number:"))
add = num + 1
# Output
print(add)
Python3
# Taking input from the user as float
num =float(input("Enter number "))
add = num + 1
# output
print(add)
Python3
# Taking input from the user as list
li =list(input("Enter number "))
# output
print(li)
Python3
# Taking input from the user as tuple
num =tuple(input("Enter number "))
# output
print(num)
输出:
geeksforgeeks
示例 2:通过消息从用户那里获取输入。
Python
# Taking input from the user
name = input("Enter your name")
# Output
print("Hello", name)
输出:
Enter your name:ankit rai
Hello ankit rai
示例 3:默认情况下, input()函数将用户的输入输入到字符串中。因此,要以 int 的形式获取输入,您需要使用 int() 和输入函数。
Python3
# Taking input from the user as integer
num = int(input("Enter a number:"))
add = num + 1
# Output
print(add)
输出:
Enter a number:15
16
示例 4:让我们将浮点输入与输入函数一起使用。
Python3
# Taking input from the user as float
num =float(input("Enter number "))
add = num + 1
# output
print(add)
输出:
Enter number 5
6.0
示例 5:让我们将列表输入与输入函数一起使用。
Python3
# Taking input from the user as list
li =list(input("Enter number "))
# output
print(li)
输出:
Enter number 12345
['1', '2', '3', '4', '5']
示例 6:让我们使用元组输入和输入函数。
Python3
# Taking input from the user as tuple
num =tuple(input("Enter number "))
# output
print(num)
输出:
Enter number 123
('1', '2', '3')