Python初学者零碎基础笔记(一)

Python初学者零碎基础笔记

一行代码输入多个参数

方法1.) a,b,c=map(类型,input(“请输入”).split())
#默认空格分隔,若要转其他类型,把类型换成需要的
如-----转整型:map(int,input(“请输入”).split())

a,b,c=map(int,input("请输入").split())
print(a+b+c,type(a),type(b),type(c))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1 2 3
>>>>
6 <class 'int'> <class 'int'> <class 'int'>

如-----转字符串:map(str,input(“请输入”).split())

a,b,c=map(str,input("请输入").split())
print(a+b+c,type(a),type(b),type(c))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1 2 3
>>>
123 <class 'str'> <class 'str'> <class 'str'>

方法2.)a,b,c=eval(input(“请输入”))
#默认逗号分隔 ,你输入什么类型就是什么类型,(注:输入字符串需要加英文字母的引号引起来)
优点:方便简洁,缺点:安全性不高,涉及到做项目的不建议使用,单使用input较好

a,b,c=eval(input("请输入"))
print(a,b,c,type(a),type(b),type(c))
print(a+b,c,type(a),type(b),type(c))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1,2,'你好'  #字符串需要加英文字母的引号引起来
>>>
1 2 你好 <class 'int'> <class 'int'> <class 'str'>
>>>
3 你好 <class 'int'> <class 'int'> <class 'str'>

转为字符串str

a,b,c=eval(input("请输入"))
a=str(a)
b=str(b)
print(a+b,c,type(a),type(b),type(c))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1,2,'你好'
>>>
12 你好 <class 'str'> <class 'str'> <class 'str'>

方法3.)a,b,c=input(“请输入”).split(’’,’’)
#split(’’,’’)代表逗号分隔 ,也可换成其他,输出结果默认为字符串,若要转其他类型,则需加要转换的类型在前面

a,b=input('请输入').split(',')
print(a,b,type(a),type(b))
print(a+b,type(a),type(b))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1,2
>>> 
1 2 <class 'str'> <class 'str'>
>>> 
12 <class 'str'> <class 'str'>

转为整型int

a,b=input('请输入').split(',')
a=int(a)
b=int(b)
print(a+b,type(a),type(b))
#扩展:当为字符串时,字符串相加,则‘+’号为拼接作用
#当为整型时,整型相加,则‘+’号为数学中的加法运算作用
>>>请输入1,2
>>> 
3 <class 'int'> <class 'int'>

猜你喜欢

转载自blog.csdn.net/weixin_49757981/article/details/108975980