python基础1:变量赋值的4种方法及类型转换

变量赋值方法:
法一:普通赋值

a = 1
b = 2

法二:连续赋值,多个变量赋值为同一个值

a = b = c = 3

法三:多个变量多个值

a, b, c = 1, 2, 3

法四:*号,一个变量赋多个值

>>>*a,b,c=1,2,3,4,5,6,7,8,9
>>>print(>>>a)
[1, 2, 3, 4, 5, 6, 7]
>>>print(b)
8
>>>print(c)
9
>>>a,*b,c=1,2,3,4,5,6,7,8,9
>>>print(>>>a)
1
>>>print(b)
[2, 3, 4, 5, 6, 7, 8]
>>>print(c)
9
>>>a,b,*c=1,2,3,4,5,6,7,8,9
>>>print(>>>a)
1
>>>print(b)
2
>>>print(c)
[3, 4, 5, 6, 7, 8, 9]
>>>*a,*b,c=1,2,3,4,5,6,7,8,9
  File "<input>", line 1
Synt>>>axError: two st>>>arred ex>>>pressions in >>>assignment

**注意:**不能多个变量赋多个值,即*a,*b,c =1,2,3,4,5,6,7,8,9会报错

类型转换方法:
一、字符串转换为整数:字符串一定得是数字
int(“字符串”)

>>>str1 = "100"
>>>print(type(str1))
<class 'str'>
>>>a = int(str1)
>>>print(a)
100
>>>print(type(a))
<class 'int'>

二、字符串转换为浮点数
float()

>>>str1 = "100"
>>>b = float(str1)
>>>print(b)
100.0
>>>print(type(b))
<class 'float'>

>>>str2 = "3.1415926535897932"
d = float(str2)
>>>print(d)
3.141592653589793
>>>print(type(d))
<class 'float'>

三、字符串转换为布尔值
bool()

>>>str1 = "100"
>>>c = bool(str1)
>>>print(c)
True
>>>print(type(c))
<class 'bool'>

四、字符串内容为小数,转整数—要先转成float,再转int

>>>str2 = "3.1415926535897932"
d = float(str2)
>>>print(d)
3.141592653589793
>>>print(type(d))
<class 'float'>
>>>d = int(str2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.1415926535897932'
>>>d = float(str2)
>>>d1 = int(d)
>>>print(d1)
3
>>>print(type(d1))
<class 'int'>

六、浮点数转整数—只取整数,即使小数第一位是大于5,整数也不进一位

>>>f1 = 3.14159265358
>>>e = int(f1)
>>>print(e)
3
>>>print(type(e))
<class 'int'>
>>>f1 = 3.99999999
>>>e = int(f1)
>>>print(e)
3
>>>print(type(e))
<class 'int'>

五、整数/布尔值转换为字符串
str()

>>>f1 = 3.99999999
>>>e = int(f1)
>>>print(e)
3
>>>print(type(e))
<class 'int'>
>>>f = str(e)
>>>print(f)
3
>>>print(type(f))
<class 'str'>
>>>bol = True
>>>print(str(bol))
True
>>>bol1 = str(bol)
>>>print(type(bol1))
<class 'str'>
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sophiasofia

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值