Python个人每日学习心得(二)

分支(条件)语句

(一)if 分支

if 判断条件:
    执行语句
elif 判断条件:
    执行语句
else:
    执行语句

if的嵌套

简单的说,就是在if语句中再嵌套一个if语句,效果如下:

语法:

​ if 表达式1:

​ 语句1

​ if 表达式2:

​ 语句2

num = 20
if num > 10:
    if num % 2 == 0:
        print(num)

 

if三目运算

输出结果.result1 if 判断条件 else 输出结果result2

若条件成立则输出结果result1,否则输出结果result2

>>> x = 10
>>> y = 20
>>> x if x > y else y
​
20

 

(二)while循环语句

while 选择条件:
    执行语句
else:
    执行语句

while死循环用法(实用)

while 1:
    if 判断语句:
        执行语句
    else:
        break

while与else

count = 0
while count < 5:
    print("%d is less than 5"%count)
    count += 1
else:
    print("%d  is not less than 5"%count)

while 的简单语句组

如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行

语法:

while 条件: 语句

while True: print("you are a good man")

(三)结束循环语句

break语句的使用

在循环中,使用break语句可以提前退出循环。

n = 1
while n <= 100:
    if n > 10:
    #当n = 11时,条件满足,执行break语句
        break
    print(n)
    n += 1
print("循环结束")

使用break跳出当段while循环

continue语句的使用

for letter in 'Python':  
    if letter == 'h':
        continue
    print('当前字母 :', letter)
 '''
 当前字母 : P
 当前字母 : y
 当前字母 : t
 当前字母 : o
 当前字母 : n
 '''

pass语句的使用

pass 语句是空语句,是为了保持程序结构的完整性

pass 不做任何事情,一般用做占位语句

if True:
    pass
else:
    print("hello")

(四)for循环语句

for i in list/range(n,m)

sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
    sum = sum + x
print(sum)
​
​
sum = 0
for x in range(100):
    sum += x
print(sum)

for 循环使用else语句

for i in range(10):
    print(i)
else:
    print("********")

range函数

range(start, stop, step)

循环嵌套

打印九九乘法表

i = 1
while i <= 9:
    j = 1
    while j <= i:
        sum = j*i
        print("%dx%d=%d"%(j,i,sum),end="    ")
        j += 1
    print("")
    i += 1

String字符串

(一)字符串含义

字符串是以单引号或者双引号括起来的任意文本,一个字符串由若干个任意字符组成

(二)创建字符串

str1 = "hello world"
str2 = 'you are good'

(三)字符串运算

1.使用加号进行连接

2.使用“,”进行连接

3.使用“%”格式化连接

s1 = 'hello'
s2 = 'world'
print("%s %s"%(s1, s2))

4.使用join函数进行连接

s1 = ['hello', 'world']
print("".join(s1))

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值