博客
关于我
python字符串input输入_Python input()函数:获取用户输入的字符串
阅读量:798 次
发布时间:2023-03-07

本文共 1737 字,大约阅读时间需要 5 分钟。

Python input函数教程

input() 是 Python 的内置函数,用于从控制台读取用户输入的内容。该函数返回的是字符串类型,因此用户输入的内容可以包含任意字符。

input函数的用法

input() 的基本使用语法如下:

str = input(tipmsg)

其中:

  • str 表示一个字符串类型的变量,用于存储用户输入的内容。
  • tipmsg 是一个提示信息,会在控制台显示,告诉用户输入的内容类型;如果不提供 tipmsg,则不会显示任何提示信息。

实例:input函数的简单使用

以下是一个简单的示例:

a = input("Enter a number: ")
b = input("Enter another number: ")

运行结果示例:

Enter a number: 100↙
Enter another number: 45↙

解释:

  • 表示按下回车键,按下回车键后 input() 函数读取输入就会结束。

问题与解决方法

在上述示例中,我们输入了两个整数,期望通过相加得到结果。然而,Python 将它们当作字符串处理,并通过 + 运算符进行拼接,而不是进行数学运算。

为了实现期望的功能,我们需要将字符串转换为数字类型。Python 提供了以下内置函数可以实现这一点:

  • int(string):将字符串转换为整数类型。
  • float(string):将字符串转换为浮点数类型。
  • bool(string):将字符串转换为布尔值类型。

修改代码如下:

a = input("Enter a number: ")
b = input("Enter another number: ")
a = float(a)
b = int(b)
result = a + b
print("resultValue: ", result)
print("resultType: ", type(result))

运行结果示例:

Enter a number: 12.5↙
Enter another number: 64↙

解释:

  • a 被转换为浮点数类型,b 被转换为整数类型。
  • 结果 result12.5 + 64 = 76.5
  • 最终输出结果为 resultValue: 76.5resultType: float

Python 2.x 的特殊注意事项

在 Python 2.x 中,input() 函数与 Python 3.x 中的 input() 函数有所不同。Python 2.x 提供了两个输入函数:

  • input():要求用户输入的内容必须符合 Python 的语法规范,通常只能是整数、小数、复数、字符串等。
  • raw_input():与 Python 3.x 中的 input() 函数功能相同,只能以字符串形式读取用户输入。
  • 相比之下,Python 3.x 的 input() 函数更加简洁易用,不再要求用户在输入字符串时使用引号包围。

    代码改写示例

    以下是代码中去掉 print 后括号的改写示例:

    a = input("Enter a number: ")
    b = input("Enter another number: ")
    a = float(a)
    b = int(b)
    print("aType: ", type(a))
    print("bType: ", type(b))
    result = a + b
    print("resultValue: ", result)
    print("resultType: ", type(result))

    运行验证

    在 Python 2.x 下运行该代码:

    Enter a number: 45↙
    Enter another number: 100↙

    解释:

    • a 被转换为整数类型,b 被转换为整数类型。
    • 结果 result45 + 100 = 145
    • 最终输出结果为 resultValue: 145resultType: int

    通过上述内容,可以清晰地理解如何使用 Python 的 input() 函数,并通过将输入的字符串转换为所需类型来实现具体的功能。

    转载地址:http://osofk.baihongyu.com/

    你可能感兴趣的文章
    python | black,一个神奇的 代码格式化工具 Python 库!
    查看>>
    python | bleach,一个超强的 Python 库!
    查看>>
    python | cartopy,一个有趣的 Python 库!
    查看>>
    python | cloud-init,一个实用的 云计算 Python 库!
    查看>>
    python | code2flow,一个神奇的 Python 库!
    查看>>
    python | cudf,一个超实用的 Python 库!
    查看>>
    python | daphne,一个非常nice的 Python 库!
    查看>>
    python调用halcon
    查看>>
    python | doit,一个非常实用的 Python 库!
    查看>>
    python | easyocr,一个超厉害的 关于OCR的 Python 库!
    查看>>
    python | fastFM,一个高级的 Python 库!
    查看>>
    python | feature_engine,一个实用的 Python 库!
    查看>>
    python | filelock,一个超酷的 Python 库!
    查看>>
    python | fire,一个强大的 Python 库!
    查看>>
    python | flanker,一个神奇的 Python 库!
    查看>>
    python | flower,一个强大的 Python 库!
    查看>>
    python | funcy,一个超强的 提供函数式编程工具 Python 库!
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | grab,一个强大的 Python 库!
    查看>>
    python | gunicorn,一个非常实用的 Python 库!
    查看>>