Python if judgment and for, while loop (Introduction to Python automated testing 5)

Today’s content will gradually become a bit more difficult, everyone prepare psychologically, but don’t be afraid, maybe it’s just a bit difficult for a novice like me to understand, I believe everyone will find it very simple.

One, if judgment

1.1 Implementation process

Created with Raphaël 2.2.0 开始 条件 条件代码 结束 yes no

1.2 When the judgment condition is two values

The format is as follows:

'''
if 条件1:
    满足条件1(条件为1True),会执行的代码。
else:
    不满足条件1(条件为1False),会执行的代码。
'''

E.g:

score = input("请输入你的考试成绩:")
if int(score) == 100:
    print("大佬")
    print("等你的下一个100分")
else:
    print("辣鸡!!")

operation result:

请输入你的考试成绩:100
大佬
等你的下一个100

1.3 When the judgment condition is multiple values

The format is as follows:

'''
if 条件1 and/or/not:
    满足条件1(条件为1True),会执行的代码。
elif 条件2:
    满足条件2(条件为2True),会执行的代码。
elif 条件3:
    满足条件3(条件为3True),会执行的代码。
else:
    条件123都不满足的情况下,会执行的代码。
'''

E.g:

score = input("请输入你的考试成绩:")
if int(score) == 100:
    print("你太棒了")
elif 80 <= int(score) < 100:
    print("很厉害了,但是可以继续加油!!")
elif 60 <= int(score) < 80:
    print("革命尚未成功,继续努力")
else:
    print("辣鸡!!")

operation result:

请输入你的考试成绩:77
革命尚未成功,继续努力

1.3 Additional notes

  1. Judgment conditions can be expressed by> (greater than), <(less than), == (equal to), >= (greater than or equal to), <= (less than or equal to)
  2. Some values ​​are False:0 , "", () , {} , [] , None, False

Two, for loop

The for loop is suitable for use when the number of loops is known. The for loop can traverse any sequence of items, such as a list or a string.

2.1 Implementation process

Insert picture description here

2.2 Format

Take out each member of the list/dictionary and assign it to a variable

'''
for 变量(随便取) in 列表/字典:
    取到的第一个成员,都会执行的代码。
'''

E.g:

nums = [1,2,3]
names = ["张三", "李四", "王五"]
for num in nums: # item是nums的每一个成员
    print(num)
for name in names: # item是字符串
    print(name)

operation result:

1
2
3
张三
李四
王五

Note: The for variable name is only used inside for

2.3 Traverse

2.3.1 range function

The range function is to generate a list of integers, all integers

  1. Format: range(开始,结束,步长)
    Start: Default is 0.
    End: Required parameter.
    Step: Default is 1, take the head but not the tail
  2. range(结束值) Does not include end value
    range(开始,结束)
    range(开始,结束,步长)

Example 1:

s = range(10)
print(list(s))

operation result:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2: Find the sum of 1+2+…100

sum = 0
for index in range(1,101,1):
    sum += index
print(sum)

operation result:

5050

2.3.2 Traverse Index

Examples:

names = ["张三", "李四", "王五","shanshan","xiaoxiao"]
# [0,1,2,3,4,5]
ll = len(names) # 6
print(list(range(ll)))  # range(6)

for index in range(len(names)):
    print(names[index])

operation result:

[0, 1, 2, 3, 4, 5]
张三
李四
王五
shanshan
xiaoxiao

2.3.3 Traversing the dictionary

Example 1: Traverse the key and value in the dictionary

dict_info = {
    
    "name": "珊珊",
           "age": None,
           "city": "成都",
           "job": "测试工程师",
           "hobby": ["睡觉","学python","看电影"]
        }

for key in dict_info:  # key
    print(key)
    print(dict_info[key])

operation result:

name
珊珊
age
None
city
成都
job
测试工程师
hobby
['睡觉', '学python', '看电影']

Example 2: Traverse the value in the dictionary (similarly, the key can be traversed)

dict_info = {
    
    "name": "珊珊",
           "age": None,
           "city": "成都",
           "job": "测试工程师",
           "hobby": ["睡觉","学python","看电影"]
        }

for value in dict_info.values():
     print(value)

operation result:

珊珊
None
成都
测试工程师
['睡觉', '学python', '看电影']

2.3.4 The difference between braek and continue

  1. break is to jump out of the entire loop
  2. continue is the end of the current cycle, without exiting the entire cycle, and entering the next cycle.
    Example: For example, continue is to ask for leave at work, and break is to resign.

Examples:

dict_info = {
    
    "name": "珊珊",
           "age": None,
           "city": "成都",
           "job": "测试工程师",
           "hobby": ["睡觉","学python","看电影"]
        }

for key,value in dict_info.items():
    if value == "南京":
        continue
    print(key, value)

operation result:

name 珊珊
age None
city 成都
job 测试工程师
hobby ['睡觉', '学python', '看电影']

2.4 Double for

Idea: First select a row and think about how to realize the content of this row.

Example 1:

rows = [1,2,3,4,5,6]

for item in range(1,10):   # for下的代码,每取一个值,里面的代码都会走一遍。
    for sub in range(1,item):
        print(sub,end="  ")  # 调一次print换行一次  修改end参数的值,可以修改换行。
    print()  # 换行

operation result:

1  
1  2  
1  2  3  
1  2  3  4  
1  2  3  4  5  
1  2  3  4  5  6  
1  2  3  4  5  6  7  
1  2  3  4  5  6  7  8  

After understanding this example, you can output the multiplication table by yourself.

Three, while loop

This loop is suitable for when the number of loops is not known; while statement is used to execute the program in a loop, that is, under a certain condition, execute a program in a loop to process the same task that needs to be processed repeatedly.

3.1 Implementation process

Insert picture description here

3.2 Format

'''
while 条件:
    条件成立下,执行代码
'''

Example 1:

work_days = ["周一","周二","周三","周四","周五"]

# 输入N次,每一次是否要上班
count = 0

while count <=3 :

    day = input("今天星期几: ")

    if day == "周四":
        break

    if day in work_days:
        print("上班吧,少年!!")
    count += 1  # 让while的条件会产生变化

operation result:

今天星期几: 周一
上班吧,少年!!
今天星期几: 周四

Example 2: Calculate the sum from 1 to 100

sum = 0
count = 1

while count <= 100:
    sum += count
    count += 1

print(sum)

operation result:

5050

3.3 Infinite loop

When the condition is always true, there will be an infinite loop. How to avoid the infinite loop? We have the following two solutions:

  1. Control when the condition is false in a certain situation. -Let the conditions change during the execution.
  2. Use break-exit the loop directly

Note: Avoid endless loops at all times

Four, summary

When writing loop statements, you can use pycharm breakpoints to debug:

  1. F7: Go one step further (when encountering a function call, you will enter the function)
  2. Go one step further (when encountering a function call, it will not enter the function and directly get the result of the function call)

This is the end of the content of this article. Maybe the content of this article needs to be read several times to understand it well. If you don’t understand anything, you can find me at any time. Although I don’t necessarily understand all of them, we can check them together. Fill up the vacancy and make progress together!

Guess you like

Origin blog.csdn.net/dhl345_/article/details/109380943