100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Python的输入指令 格式化输出 基本运算符

Python的输入指令 格式化输出 基本运算符

时间:2019-02-28 23:58:43

相关推荐

Python的输入指令 格式化输出 基本运算符

Python的输入指令、格式化输出、基本运算符

Python的输入指令input

name = input('Could I know your name please?')

在Python3版本下,输入的所有内容都视为字符串,所以此时name的类型是字符串。如果输入年龄,需要进行转换

age = int(input('Could I know your age please?'))

在Python2版本下,使用input()输入的内容不会被自动转成字符串,所以需要在输入时指定数据类型。

而Python2下的raw_input()等于Python3下的input()

Python的格式化输出

我们先定义3个变量

name = '李隆基'height = 175weight = 80

使用占位符输出信息

print('My name is %s, height is %d cm, weight is %d kg' % (name, height, weight))

使用format输出

print('My name is {0}, height is {1} cm, weight is {2} kg'.format(name, height, weight))

使用f-string输出

print(f'My name is {name}, height is {height} cm, weight is {weight} kg')

仔细观察下列代码,看看3句print的差别(虽然他们的输出结果是一样的)

name = '李隆基'height = 1.75weight = 80.5print('My name is %s, height is %.2f m, weight is %.2f kg' % (name, height, weight))print('My name is {0}, height is {1:.2f} m, weight is {2:.2f} kg'.format(name, height, weight))print(f'My name is {name}, height is {height:.2f} m, weight is {weight:.2f} kg')

Python的基本运算类型

算术运算符

关于算术运算符,下面的代码就能说明一切了

x = 11y = 7plus = x + yminute = x - ymultiply = x * ydivide = x / ydivide_exactly = x // ymod = x % yexponent = x ** yprint(f'plus is {plus}')print(f'minute is {minute}')print(f'multiply is {multiply}')print(f'divide is {divide}')print(f'divide_exactly is {divide_exactly}')print(f'mod is {mod}\nexponent is {exponent}')

比较运算符

代码的执行结果说明了一切

x = 10y = 11print(x == y)print(x > y)print(x < y)print(x >= y)print(x <= y)print(x != y)

赋值运算符

运算后直接赋值的缩写法

# x = x + yx += y# x = x - yx -= y# x = x * yx *= y# x = x / yx /= y# x = x // yx //= y# x = x % yx %= y

逻辑运算符

老样子,通过代码来学习

# and 与运算,所有条件都为True,结果才是True。相当于一串布尔值分别做乘法print(True and False)print(False and False)print(True and True)# or 或运算,有一个条件为True,结果即True。相当于一串布尔值分别做加法print(True or False)print(False or False)print(True or True)# not 把True转成False,把False 转成Trueprint(not True)print(not False)

身份运算符

通过两个值的存储单元(即内存地址)进行比较

is 如果相同则返回True

is not 如果不同则返回True

== 用来判断值相等,is 是内存地址

换言之,

== 是True,is 不一定是True

== 是False,is 一定也是False

is 是True,== 一定是True

is 是False,== 不一定是False

逻辑有点饶,关键是理解

运算符的优先级

平时多用括号,方便别人,方便自己

链式赋值

# 若数字一样时,可以如此a = b = c = 10print(a, b, c)# 若数字不同时,可以如此x, y, z = (10, 11, 12)print(x, y, z)

交叉赋值

变量直接互换,就是这么任性

num_a = 100num_b = 200print(num_a,num_b)num_a,num_b = num_b,num_aprint(num_a,num_b)

解压缩

可以快速取出列表中的值,可以使用占位符_ 和 *_

执行一下下面的代码,效果很棒

boy_list = ['apple', 'banana', 'pear', 'gripe', 'cherry']a, b, c, d, e = boy_listprint(a, b, c, d, e)a, _, _, b, c = boy_listprint(a, b, c)a, *_, b = boy_listprint(a, b)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。