Phython grammar - to determine statements and loops (Detailed)

This article is the second chapter phython basis of grammar determine statements and loops knowledge summary, Welcome learning and common progress



The basic format of a judgment statement describes .if

  • if statement is used to judge, using the following format:
if 要判断的条件:
      条件成立时,要做的事情
  • Demo
age = 30

print("------if判断开始------")

if age >= 18:
    print("我已经成年了")

print("------if判断结束------")
------if判断开始------
我已经成年了
------if判断结束------
  • It is that when certain conditions are met will execute the code block statement, or do not execute the code block statement.
  • Note: The code indentation is a tab key, or 4 spaces

II. Comparison (i.e. relationship condition) operator

  • (1) python comparison operator in the following table

Here Insert Picture Description

num1 = 15
num2 = 20
# == 等于:表示左右两个操作数是否相等,如果相等则整个表达式的值为 True;不相等则为False
print(num1 == num2)

# != 不等于
print(num1 != num2)
False
True

  • (2) logical operators
    Here Insert Picture Description
# and : 左右表达式都为True,整个表达式结果才为 True
if (1 == 1) and (10 > 3):
    print("条件成立!")

# or : 左右表达式有一个为True,整个表达式结果就为 True
if (1 == 2) or (10 > 3):
    print("条件成立!")

# not:将右边表达式的逻辑结果取反,Ture变为False,False变为True
if not (1 == 2):
     print("条件成立!")
条件成立!
条件成立!
条件成立!

三.if-else

Think about it: if at the time of use, it can only do do things when the condition is satisfied. What if you need when the conditions are not satisfied, do something, how to do it?


  • format using if-else
if 条件:
    满足条件时要做的事情1
    满足条件时要做的事情2
    满足条件时要做的事情3
    ...(省略)...
else:
    不满足条件时要做的事情1
    不满足条件时要做的事情2
    不满足条件时要做的事情3
    ...(省略)...
  • Demo
chePiao = 1  # 用1代表有车票,0代表没有车票
if chePiao == 1:
    print("有车票,可以上火车")
    print("终于可以见到Ta了,美滋滋~~~")
else:
    print("没有车票,不能上车")
    print("亲爱的,那就下次见了"
  • Result 1: There are circumstances ticket
有车票,可以上火车
终于可以见到Ta了,美滋滋~~~
  • Results: No ticket situation
没有车票,不能上车
亲爱的,那就下次见了

Four .if ... elif ... else ... statement format

  • elif function
#elif的使用格式如下:
if xxx1:
    事情1
elif xxx2:
    事情2
elif xxx3:
    事情3
  • Description:
  • When xxx1 meet, do 1 thing, then end the whole if
  • When xxx1 not met, the judge xxx2, if xxx2 met, the implementation of 2 things, then the end of the whole if
  • When xxx1 not satisfied, xxx2 not be satisfied if xxx3 met, then execute 3 things, then the end of the whole if

  • demo
score = 77

if score >= 90 and score <= 100:
    print('本次考试,等级为A')
elif score >= 80 and score < 90:
    print('本次考试,等级为B')
elif score >= 70 and score < 80:
    print('本次考试,等级为C')
elif score >= 60 and score < 70:
    print('本次考试,等级为D')
elif score >= 0 and score < 60:
    print('本次考试,等级为E')
本次考试,等级为C

  • important point
  • Can be used with else
if 性别为男性:
       输出男性的体重
       ...
   elif 性别为女性:
       输出女性的体重
       ...
   else:
       第三种性别的体重
       ...
  • elif must be used together and if, otherwise an error
  • Else use is generally used in the final, i.e. all the conditions are not met

  • if an arithmetic operation implemented trinocular
  • a if a > b else b
  • If a> b condition is satisfied, the operation is the result of three head a, b otherwise
# 求a和b两个数字中的较大值.
a = 10
b = 20
# 使用三目运算符求较大值
max = a if a > b else b
print("较大值为:%d" % max)
较大值为:20

Five .if nesting

  • if nested format
if 条件1:

        满足条件1 做的事情1
        满足条件1 做的事情2

        if 条件2:
            满足条件2 做的事情1
            满足条件2 做的事情2
说明
外层的if判断,也可以是if-else
内层的if判断,也可以是if-else
根据实际开发的情况,进行选择
  • demo
chePiao = 1     # 用1代表有车票,0代表没有车票
daoLenght = 9     # 刀子的长度,单位为cm

if chePiao == 1:
    print("有车票,可以进站")
    if daoLenght < 10:
        print("通过安检")
        print("终于可以见到Ta了,美滋滋~~~")
    else:
        print("没有通过安检")
        print("刀子的长度超过规定,等待警察处理...")
else:
    print("没有车票,不能进站")
    print("亲爱的,那就下次见了")
有车票,可以进站
通过安检
终于可以见到Ta了,美滋滋~~~
  • chePiao = 0; daoLenght = 9
没有车票,不能进站
亲爱的,那就下次见了

Six .While loop

  • while loop format
while 条件:
    条件满足时,做的事情1
    条件满足时,做的事情2
    条件满足时,做的事情3
    ...(省略)...
  • Software development cycle usage scenarios
  • Admit mistakes with his wife, he said a thousand times, "young married woman, I was wrong."
print("媳妇儿,我错了")
print("媳妇儿,我错了")
print("媳妇儿,我错了")
...(还有99997)...
  • Use loop to get a word
i = 0
while i < 10000:
    print("媳妇儿,我错了")
    i += 1
  • But in order to not have to use a loop 提高代码的重复使用率, so experienced developers will adopt cycle

Case: calculate the cumulative and (100 and comprising a) from 1 to 100

#encoding=utf-8

i = 1
sum = 0
while i <= 100:
    sum = sum + i
    i += 1

print("1~100的累积和为:%d" % sum)

And calculating the even accumulated (100 and comprising a) between 1 and 100

#encoding=utf-8

i = 1
sum = 0
while i <= 100:
    if i % 2 == 0:
        sum = sum + i
    i+=1

print("1~100的累积和为:%d" % sum)
1~100的累积和为:2550

Seven .while loop nest

while 条件1:

    条件1满足时,做的事情1
    条件1满足时,做的事情2
    条件1满足时,做的事情3
    ...(省略)...

    while 条件2:
        条件2满足时,做的事情1
        条件2满足时,做的事情2
        条件2满足时,做的事情3
        ...(省略)...

Exercise: Print triangle

  • Requirements: Graphic prints as follows:
 * 
 * * 
 * * * 
 * * * *  
 * * * * *
  • Reference Code
i = 1
while i <= 5:
    j = 1
    while j <= i:
        print("*", end=" ")
        j += 1
    print()

    i += 1

Eight .for cycle

  • Like the while loop, for possible completion cycle.
  • In Python for loop can iterate any sequence of items, such as a list or a string and so on.
  • The format for loop
for 临时变量 in 列表或者字符串等可迭代对象:
    循环满足条件时执行的代码
name = 'hello'

for x in name:
        print(x)
        if x == 'l':
            print("Hello world!")
h
e
l
Hello world!
l
Hello world!
o

Nine .break and continue

  • break
  • <1> for循环
name = 'hello'

for x in name:
    print('----')
    print(x)
else:
    print("==for循环过程中,如果没有执行break退出,则执行本语句==")
----
h
----
e
----
l
----
l
----
o
==for循环过程中,如果没有执行break退出,则执行本语句==
  • Break cycles with the following example:
name = 'hello'

for x in name:
    print('----')
    if x == 'e':
        break
    print(x)
else:
    print("==for循环过程中,如果没有执行break退出,则执行本语句==")
----
h
----
  • <2> while循环
i = 0

while i<5:
    i = i+1
    print('----')
    print(i)
else:
    print("==while循环过程中,如果没有执行break退出,则执行本语句==")
----
1
----
2
----
3
----
4
----
5
==while循环过程中,如果没有执行break退出,则执行本语句==
  • Break cycles with the following example:
i = 0

while i<5:
    i = i+1
    print('----')
    if i==3:
        break
    print(i)
else:
    print("==while循环过程中,如果没有执行break退出,则执行本语句==")
----
1
----
2
----
  • Summary: The role of the break: an immediate end to break the cycle where

  • continue
  • <1> for循环
name = 'hello'

for x in name:
    print('----')
    if x == 'e':
        continue
    print(x)
else:
    print("==while循环过程中,如果没有break则执行==")
----
h
----
----
l
----
l
----
o
==while循环过程中,如果没有break则执行==
  • <2> while循环
i = 0

while i<5:
    i = i+1
    print('----')
    if i==3:
        continue
    print(i)
----
1
----
2
----
----
4
----
5
  • Summary : The effect continue: for the end of the cycle, followed by one cycle of execution of the

  • important point
  • break/continue只能用在循环中,除此以外不能单独使用
  • break/continue在嵌套循环中,只对最近的一层循环起作用

  • The best investment is in yourself
    Here Insert Picture Description
  • 2020.03.30 记录辰兮的第41篇博客
Published 45 original articles · won praise 236 · views 40000 +

Guess you like

Origin blog.csdn.net/weixin_45393094/article/details/105182053