简单 Python 快乐之旅之:Python 基础语法之类型转换的使用例子

1. 复数的例子

复数被普遍应用于科学计算。Python 支持复数,你可以这样初始化一个复数:

cn = 5 + 6j

正如复数的定义那样,5 是实部,6 是虚部。
复数的例子:

# Python Complex Number Example
cn = 5 + 6j
print(cn)
print(type(cn))
print('Real part is:', cn.real)
print('Imaginary part is:', cn.imag)

执行和输出:
复数的例子.png

2. 整数转换为浮点数

可以使用 float() 函数将整数或字符串转换为浮点数:

# Python Convert Int to Float
# using function float()
a = 5
print(a, 'is of type:', type(a))
a = float(a)
print(a, 'is of type:', type(a))

执行和输出:
使用 float() 函数将整数或字符串转换为浮点数.png
或者也可以将其与一个 0 浮点数相加同样可以进行转换,Python 会隐式地将其由整数转换为浮点数:

# using add a 0 floating number
a = 5
print(a, 'is of type:', type(a))
a = a + 0.0
print(a, 'is of type:', type(a))

执行和输出:
与一个 0 浮点数相加同样可以进行转换.png

3. 将整数转换为复数

可以使用 complex() 函数将整数或一个字符串转化为复数:

# Python Convert Int to Complex
# using function complex()
a = complex(2, 4)
print(a, 'is of type:', type(a))
a = complex(1)
print(a, 'is of type:', type(a))
a = complex('1')
print(a, 'is of type:', type(a))
a = complex('2+3j')
print(a, 'is of type:', type(a))

执行和输出:
使用 complex() 函数将整数或一个字符串转化为复数.jpg
跟上述整数转浮点的第二种办法一样,可以将整数与一个 0 虚部相加转换为复数:

# using add a 0 imaginary part
a = 5
print(a, 'is of type:', type(a))
a = a + 0j
print(a, 'is of type:', type(a))

执行和输出:
将整数与一个 0 虚部相加转换为复数.png

参考资料

posted @ 2019-03-29 20:08  Defonds  阅读(37)  评论(0编辑  收藏  举报