-
使用continue,我们可以控制循环继续下去,并跳过continue后面的逻辑,比如,对于字符串s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',假如希望输出字符串s中第10个以后的字符,而不是所有字符,这个时候, 我们可以使用continue跳过前面的9个字符。
s = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' num = 1 for ch in s: if num < 10: num = num + 1 continue # 当num < 10时,跳过后续循环代码,继续下一次循环 print(ch) num = num + 1
查看全部 -
for 语句
要list出来而已
s = 1234
for a in s:
print (a)
要sum
s = 1234
sum = 0.0(要赋值给sum先)
for a in s:
sum = sum + a
print (sum) [如果放tab的话means print也在for语句里面]
查看全部 -
if-elif-else 语句
elif的意思是else if
format:
if ... :
print ("")
elif ... :
print ("")
else:
print ("")
查看全部 -
前面我们写了第一个Python程序,向屏幕打印了'Hello World',请通过定义多个变量的方式,把相同的字符串打印出来。
# Enter a code
hello='Hello'#
print(hello)
space=' '#
print(space)
world='World'#
print(world)
查看全部 -
一个长方形的长为3.14cm,宽为1.57cm,请计算这个长方形的面积,保留小数点后两位。
# Enter a code
#
length=3.14
width=1.57
result=round(length*width,2)
print(result)
查看全部 -
地板除//就是保留整数部分
查看全部 -
这一系列条件判断会从上到下依次判断,如果某个判断为 True,执行完对应的代码块,后面的条件判断就直接忽略,不再执行了。
查看全部 -
在if语句的最后,有一个冒号
:,这是条件分支判断的格式,在最后加入冒号:,表示接下来是分支代码块可以看到
print('抱歉,考试不及格')这行代码明显比上一行代码缩进了,这是因为这行代码是if判断的一个子分支,因此需要缩进,在Python规范中,一般使用4个空格作为缩进
查看全部 -
如果模板中
{}比较多,则容易错乱,那么在format的时候也可以指定模板数据内容的顺序。除了使用顺序,还可以指定对应的名字,使得在format过程更加清晰。# 指定{}的名字w,c,b,i template = 'Hello {w}, Hello {c}, Hello {b}, Hello {i}.' world = 'World' china = 'China' beijing = 'Beijing' imooc = 'imooc' # 指定名字对应的模板数据内容 result = template.format(w = world, c = china, b = beijing, i = imooc) print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc
# 指定顺序template = 'Hello {0}, Hello {1}, Hello {2}, Hello {3}.' result = template.format('World', 'China', 'Beijing', 'imooc') print(result) # ==> Hello World, Hello China, Hello Beijing, Hello imooc. # 调整顺序 template = 'Hello {3}, Hello {2}, Hello {1}, Hello {0}.' result = template.format('World', 'China', 'Beijing', 'imooc') print(result) # ==> Hello imooc, Hello Beijing, Hello China, Hello World.查看全部 -
如果一个字符串包含很多需要转义的字符,对每一个字符都进行转义会很麻烦。为了避免这种情况,我们可以在字符串前面加个前缀
r,表示这是一个 raw 字符串,里面的字符就不需要转义了。例如:r'\(~_~)/ \(~_~)/'
但是
r'...'表示法不能表示多行字符串,也不能表示包含'和"的字符串。如果要表示多行字符串,可以用
'''...'''表示:'''Line 1 Line 2 Line 3'''上面这个字符串的表示方法和下面的是完全一样的:
'Line 1\nLine 2\nLine 3'
还可以在多行字符串前面添加
r,把这个多行字符串也变成一个raw字符串:r'''Python is created by "Guido". It is free and easy to learn. Let's start learn Python in imooc!'''查看全部 -
字符串是Python程序重要的数据类型,到目前为止,我们输出的字符串的内容都是固定的, 但有时候通过字符串输出的内容不是固定的,这个时候需要使用format来处理字符串, 输出不固定的内容。
# 字符串模板 late = 'Hello {}'# 模板数据内容 world = 'World' result = template.format(world) print(result) # ==> Hello World查看全部 -
if 语句
sum =
if sum < ??? :
print ("字符串")
查看全部 -
字符串切片
format:
sum = '字符串'
a = sum[0]
b = sum[1]
print (a)
format (切片一个range的字符串):
sum = '字符串'
a = sum[0:2]
print (a)
查看全部 -
如果字符串不固定就要用format来处理字符串
format的formula
template = '字符串 {}'
result = template.format(要填进去{}的字符串)
如果很多不固定的字符串的话
template = '字符串 {}'
result = template.format ('...' , '... , '...')
print (result)
查看全部 -
如果一行字符串里面有太多的"" '' \n \t , 就可以用r''' ....... ''' 来代替转义字符
查看全部
举报