知行编程网知行编程网  2022-08-18 20:30 知行编程网 隐藏边栏  1 
文章评分 0 次,平均分 0.0
导语: 本文主要介绍了关于python的input函数如何运行的相关知识,包括python中range()函数,以及python3 input函数这些编程知识,希望对大家有参考作用。

python的输入功能是如何工作的?

input()以字符串的方式获取用户输入:

>>> x = input()
4.5
>>> type(x)
<class 'str'>
>>> y = input()
Do you love python?
>>> type(y)
<class 'str'>

输入字符串可以通过运算符进行连接、复制等操作:

>>> x = input()
abc
>>> x * 3
'abcabcabc'
>>> y = input()
123
>>> x + y
'abc123'

但无法直接参与算术运算,如:

>>> x = input()
5
>>> x + 5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> x * 5
'55555'
>>> y = input()
6
>>> x * y
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

此时可以使用转换,方法有多种:

1.指定类型转换

1 >>> y = int(input())
2 10
3 >>> type(y)
4 <class 'int'>

2.自动转换

函数 eval() 用于执行字符串表达式并返回表达式的值

eval(expression, globals[ ], locals[ ])

global 和 locals 分别相当于全局和局部变量,eval函数会优先在局部变量存储空间中检索

1  >>> y = eval(input())
2  4.5
3  >>> type(y)
4 <class 'float'>

3.切割转换

利用函数split()通过指定分隔符对字符串进行切片。

str.split(str="", num=string.count(str))

str为分割符,包括空格、\n,\t 等 ,num是分割次数。

本文为原创文章,版权归所有,欢迎分享本文,转载请保留出处!

知行编程网
知行编程网 关注:1    粉丝:1
这个人很懒,什么都没写
扫一扫二维码分享