Python中的输入函数:概念和示例(Python的input函数的基础知识)

在这篇文章中,我将通过一些通俗易懂的例子来解释 Python 的 input 函数的基础知识。

图片[1]-Python中的输入函数:概念和示例(Python的input函数的基础知识)-不念博客

Python 是世界上最流行的编程语言之一,广泛应用于各种应用程序中。Python 中的一个基本概念是 input函数,它允许用户通过提供输入值与程序进行交互。

让我们看看 input函数是如何工作的,以及如何在 Python 程序中有效地使用它。

在开始之前,我希望你已经安装了 Python 并设置了一个基本的编辑器。如果没有,请参考我的以下指南:

  • 如何在 Ubuntu 等 Linux 上安装 Python 3.11
  • 如何在 Windows 上安装 Python
  • 如何为 Python 设置 IDLE 编辑器

Python Input 函数

Python 中的 input函数用于接受用户输入的字符串。它提示用户输入一个值并等待用户提供输入。然后将用户的输入作为字符串存储在变量中,稍后可以在程序中使用。

句法

input("your message to user")

当你运行 input函数时,它会向用户显示消息并等待输入。显示光标等待。当用户输入并按下回车键,input函数就会读取用户的输入。该值存储在你指定的变量中。

让我们看几个例子。

示例 1:简单的 input 函数用法

以下代码片段接受输入并显示带有附加字符串的输出:

your_name = input("Enter your name:")
print("Hello " + your_name)

输出:

Enter your name:arindamHello arindam
图片[2]-Python中的输入函数:概念和示例(Python的input函数的基础知识)-不念博客

示例 2:以整数和浮点数作为输入

在使用 input函数时,你还可以在运行时使用intfloat将输入转换。这是一个例子:

no_of_books = int(input("Enter total books ordered:"))
print ("Total number of books:", no_of_books)

price_of_each_book = float(input("Enter unit price:"))
print ("Total price:", no_of_books * price_of_each_book)

输出:

Enter total books ordered:5
Total number of books: 5
Enter unit price:10.1
Total price: 50.5

示例 3:连接列表

你还可以使用其他函数(例如列表)来接受一组值并将它们转换为 Python 中的 列表。这是一个接受输入并将其转换为列表的示例。然后使用另一组值并附加到第一个列表:

# 获取第一个列表的输入
list_1 = list(input("Enter numbers for list 1:"))

# 获取第二个列表的输入
list_2 = list(input("Enter some letters for list 2:"))

# 循环遍历第二个列表并添加到第一个列表
for j in list_2:
    list_1.append(j)

# 打印修改后的第一个列表
print(list_1)

输出:

Enter numbers for list 1:1234
Enter some letters for list 2:ABCD
['1', '2', '3', '4', 'A', 'B', 'C', 'D']

总结

我希望这个简单的指南通过几个示例阐明了 input函数。对于简单的场景,它是一个强大的功能,可以从标准输入中接受值。

© 版权声明
THE END
喜欢就支持一下吧
点赞138赞赏 分享
评论 抢沙发
头像
欢迎光临不念博客,留下您的想法和建议,祝您有愉快的一天~
提交
头像

昵称

取消
昵称

    暂无评论内容