目录
Python3里面输入函数是input(),该函数将所有的输入都当做string来处理,但是实际运用中,需要各种类型的数据,需要进行转换,且在转换过程中可能会存在各种问题。我针对我最近遇到的几个小习题做了些总结,作为菜鸟,水平一般,如果有不全或错误,望海涵。
一、正常形式
Python3提供了input()函数来接收用户从键盘的输入,input()函数将所有输入都作为string类型来处理。
例如:
num=input("请输入一个整数:")
print(type(num))
'''
执行结果如下:
请输入一个整数:2018
<class 'str'>
'''
亦或是
num=input("请输入一个浮点数:")
print(type(num))
'''
执行结果如下:
请输入一个浮点数:13.14
<class 'str'>
'''
也就是说,不管输入什么类型的数据,都返回一个string类型的数据。
二、运用异常处理结构
但是在实际使用中我们需要各种类型的数据,比如整型,最简单的方式就是用int()来转换。
比如,这题:
#编写程序:从键盘输入某个分钟数,将其转换为用小时和分钟表示
num=int(input("please input a number ")) #这里面就是用int()来转换
hour=num//60 #整除
min=num%60 #求余
print("hour is %.f"%hour)
print("min is %.f"%min)
'''
输出结果
please input a number 366
hour is 6
min is 6
'''
但是,在上题中,你如果输入一个“整数”可以顺利转换,但是如果你输入一个“英文字母串”,就会转换失败,这时候就需要运用Python里面的异常处理结构try……except……,且使用ValueError来接收抛出的错误。
#如果输入“字母”程序将无法执行,产生如下错误
please input a number abcd
Traceback (most recent call last):
File "D:/Python/习题解析/Temp.py", line 1, in <module>
num = int(input("please input a number"))
ValueError: invalid literal for int() with base 10: 'abcd'
运用异常处理后:
try:
num=int(input("please input a number: "))
hour=num//60
min=num%60
print("hour is %.f"%hour)
print("min is %.f"%min)
except ValueError: #由于值错误,而不能顺利转换,会抛出ValueError错误
print("请输入一个整形数据!")
'''
执行结果如下:
please input a number: abcdefg
请输入一个整形数据!
'''
如果加上循环,就可以实现重复输入,直到得到符合要求的数据。例如下面这题:
#输入半径,求圆的面积
PI=3.1415926 #半径
while True:
try:
r=input("Please input a number:")
r=float(r) #如果不能转换成float类型,则抛出异常,执行except 后面的语句,不会执行下面这句break
break #如果上面顺利转换,没有抛出异常,执行break语句,结束循环,转到 area=r*r*PI
except ValueError:
print("请输入一个整数或者小数")
continue #结束本次循环,接着输入数据
area=r*r*PI
print("area is %.4f"%area)
'''
实验结果如下:
Please input a number:abc
请输入一个整数或者小数
Please input a number:123abc
请输入一个整数或者小数
Please input a number:1 2
请输入一个整数或者小数
Please input a number:10
area is 314.1593
'''
三、接收多个数据
实际运用中,我们可能会需要一次输入多个数据,或者说将一个数据当多个用,比如需要统计“一句句子”由多少个“单词”组成,这时候一句input()语句,要接收一整个句子,我们需要使用str.split()函数来处理。该函数具体可参考str.split() ,split()函数运用指定的分隔符对字符串进行分割,返回一个列表,列表里面是分割好的子字符串。
#输入一句英文句子,统计其中包含多少个单词 (假设没有逗号和句号!!!)
s=input("please input a string:") #输入句子
counter=0
for i in s.split(" "): #用字符串s调用split方法,分割符为" "(空格)
#返回列表,将列表里面的子字符串迭代出来。
if i:
counter+=1
print("The counter is:%.f"%counter)
'''
运行结果如下
please input a string:bu po lou lan zhong bu huan
The counter is:7
'''
但是实际的句子是有逗号和句号的,这时候也需要有分割,但是,是多分割。str.split()只能指定单个分隔符,如果需要指定多个分隔符,需要导入re模块,使用re.split()方法。具体可参考:Python中使用多个分隔符分隔字符串re.split
#输入一段英文,统计其中包含多少个单词
import re
s=input("please input a string:")
counter=0
for i in re.split(r'[\s,。]',s): #多分割,分割附分别是 空格 逗号(英文) 句号
if i:
counter+=1
print("The counter is:%.f"%counter)
'''
运行结果如下
please input a string:ni,hao ma。wo hen hao
The counter is:6
'''
上述是只需要分割的情况,有时候即需要分割,又需要转换,这时候需要map()函数,该函数具体可参考:Python map() 函数 例如下题:
#输入平面上的两个点,计算两点的距离
import math
while True:
try:
p1=input("please the start point x1,y1:") #输入第一个点,中间以逗号作为分割
p2=input("please the start point x2,y2:") #第二个点
#map()函数,将p1.split(",")以逗号作为分割后得到的列表中的子字符串,全部转换为float型。
#如果在map()里面转换失败,抛出ValueError错误
x1,y1=map(float,p1.split(",")) #split本质返回一个列表
x2,y2=map(float,p2.split(",")) #split本质返回一个列表
distance = math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
print("distance=", distance)
break
except ValueError:
print("数据类型错误,请重输!")
continue
'''
执行结果如下:
please the start point x1,y1:1,2
please the start point x2,y2:a,b
数据类型错误,请重输!
please the start point x1,y1:1,2
please the start point x2,y2:5,4
distance= 4.47213595499958
'''
四、利用eval()函数
后来,我又遇到了一道题目是这样的:输入“ [[1,2,3],[4,5,6],[7,8,9]] ”,输出矩阵形式,刚开始,我确实想了很多办法,分割和删除各种组合,希望能去掉方括号,但是都失败了。后来突然想到了eval()这个神奇的函数,一步到位。
我们可以先看一下eval()这个函数的用法:
l = '[1,2,3,4,[5,6,7,8,9]]'
d = "{'a':123,'b':456,'c':789}"
t = '([1,3,5],[5,6,7,8,9],[123,456,789])'
print(type(l), type(eval(l)))
print(type(d), type(eval(d)))
print(type(t), type(eval(t)))
'''
执行结果如下:
<class 'str'> <class 'list'>
<class 'str'> <class 'dict'>
<class 'str'> <class 'tuple'>
看出作用了吗?
'''
然后来解决上面这个问题:
#将3行3列的矩阵按其形状输出,例如,输入为[[1,2,3],[4,5,6],[7,8,9]],输出为:
str=input("pleased input a 3*3 array:")
print(str,type(str))
str=eval(str)
print(str,type(str))
'''
[[1,2,3],[4,5,6],[7,8,9]] <class 'str'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] <class 'list'>
虽然两次输出,样式看起来一致,但是类型已经由“字符串”转换成了“列表”
'''
#接下里只需要将列表里面的数迭代输出即可。
for x in str:
s=""
for y in x:
s1="%6d"%y #总共占6位,可忽略,不是这篇的重点
s=s+s1
print(s)
"""
运行结果如下:
pleased input a 3*3 array:[[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3],[4,5,6],[7,8,9]] <class 'str'>
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] <class 'list'>
1 2 3
4 5 6
7 8 9
"""
当然eval()的用法很灵活,但也不是都能用,具体自己把握。
本篇完。
另,如果有错误,或者你有更好的想法,欢迎留言交流。
如果对你有用的话,请点个“喜欢”,谢谢。