Conditions and loop statements for python basic learning

1. The if statement

if expression:
    expr_true_suite
  • Remember to indent the code block of the if statement  and execute it expr_true_suite only if  expression the result of the conditional expression is true, otherwise it will continue to execute the statement immediately following the code block.
  • The conditional expression in a single if statement  can expression pass Boolean operators  andand  realize multiple conditional judgments.ornot

【example】

if 2 > 1 and not 2 > 3:
    print('your are right!')  #your are right

2. if-else statement

if expression:
    expr_true_suite
else:
    expr_false_suite
  • Python provides else used in conjunction with if, if the conditional expression of the if statement results in a boolean value of false, then the program will execute the code after the else statement.

【example】

temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp) # input 函数将接收的任何数据类型都默认为 str。
if guess == 666:
    print("你太了解小姐姐的心思了!")
    print("哼,猜对也没有奖励!")
else:
    print("猜错了,小姐姐现在心里想的是666!")
print("游戏结束,不玩儿啦!")

ififStatements support nesting, that is, embedding another statement in one statement ifto form a selection structure of different levels.

[Example] Python uses indentation instead of braces to mark code block boundaries, so special attention should be paid to elsethe suspension problem.

hi = 4
if hi > 2:
    print("棒")
    if hi > 7:
        print('好棒!好棒!')
else:
    print('切~')

# 棒


temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
    print("大了,大了")
else:
    if guess == 8:
        print("你太了解小姐姐的心思了!")
        print("哼,猜对也没有奖励!")
    else:
        print("小了,小了")
print("游戏结束,不玩儿啦!")

3. if - elif - else statement

if expression1:
    expr1_true_suite
elif expression2:
    expr2_true_suite
    .
    .
elif expressionN:
    exprN_true_suite
else:
    expr_false_suite
  • The elif statement is an else if, which is used to check whether multiple expressions are true and execute the code in a specific code block when it is true.

【example】

temp = input('请输入成绩:')
source = int(temp)
if 100 >= source >= 90:
    print('A')
elif 90 > source >= 80:
    print('B')
elif 80 > source >= 60:
    print('C')
elif 60 > source >= 0:
    print('D')
else:
    print('输入错误!')

4. assert keyword

  • assertWe call this keyword "assertion". When the condition behind this keyword is False, the program will automatically crash and throw AssertionErroran exception.

【example】

my_list = ['lsgogroup']
my_list.pop(0)
assert len(my_list) > 0

# AssertionError

[Example] When performing unit testing, it can be used to put checkpoints in the program, and the program can work normally only if the condition is True.

assert 3 > 7

# AssertionError

loop statement

1. while loop

whileIn its most basic form, a statement consists of a Boolean expression at the top, and one or more whileindented statements belonging to a code block.

while 布尔表达式:
    代码块

whileThe code block of the loop will loop until the Boolean expression evaluates to Boolean false.

If the Boolean expression does not have <、>、==、!=、in、not inan equal operator, it is also possible to only give conditions such as values. When a non-zero integer is written later while, it is regarded as a true value, and the loop body is executed; when writing 0, it is regarded as a false value, and the loop body is not executed. You can also write str、listor any sequence, if the length is non-zero, it is regarded as a true value, and the loop body is executed; otherwise, it is regarded as a false value, and the loop body is not executed.

【example】

count = 0
while count < 3:
    temp = input("猜一猜小姐姐想的是哪个数字?")
    guess = int(temp)
    if guess > 8:
        print("大了,大了")
    else:
        if guess == 8:
            print("你太了解小姐姐的心思了!")
            print("哼,猜对也没有奖励!")
            count = 3
        else:
            print("小了,小了")
    count = count + 1
print("游戏结束,不玩儿啦!")

[Example] The Boolean expression returns 0, and the loop terminates.

string = 'abcd'
while string:
    print(string)
    string = string[1:]

2. while-else loop

while 布尔表达式:
    代码块
else:
    代码块

When whilethe loop is executed normally, the elseoutput is executed. If whilea statement that jumps out of the loop is executed in the loop, for example  , the content of the code block breakwill not be executed .else

【example】

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


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

# 0 is  less than 5

3. for loop

forA loop is an iterative loop, which is equivalent to a general sequence iterator in Python. It can traverse any ordered sequence, such as str、list、tupleetc., and can also traverse any iterable object, such as dict.

for 迭代变量 in 可迭代对象:
    代码块

Each time through the loop, the iteration variable is set to the current element of the iterable object, available for use by the code block.

【example】

for i in 'ILoveLSGO':
    print(i, end=' ')  # 不换行输出

# I L o v e L S G O


member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
    print(each)

# 张三
# 李四
# 刘德华
# 刘六
# 周润发

for i in range(len(member)):
    print(member[i])

# 张三
# 李四
# 刘德华
# 刘六
# 周润发


dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key, value in dic.items():
    print(key, value, sep=':', end=' ')
    
# a:1 b:2 c:3 d:4 



dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for key in dic.keys():
    print(key, end=' ')
    
# a b c d 



dic = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

for value in dic.values():
    print(value, end=' ')
    
# 1 2 3 4

4. for-else loop

for 迭代变量 in 可迭代对象:
    代码块
else:
    代码块

When forthe loop is executed normally, the output is executed else. If forthe statement that jumps out of the loop is executed in the loop, for example  , the content of the code block breakwill not be executed , which is the same as the statement.elsewhile - else

【example】

for num in range(10, 20):  # 迭代 10 到 20 之间的数字
    for i in range(2, num):  # 根据因子迭代
        if num % i == 0:  # 确定第一个因子
            j = num / i  # 计算第二个因子
            print('%d 等于 %d * %d' % (num, i, j))
            break  # 跳出当前循环
    else:  # 循环的 else 部分
        print(num, '是一个质数')

5. range() function

range([start,] stop[, step=1])
  • This BIF (Built-in functions) has three parameters, and the two enclosed in square brackets indicate that these two parameters are optional.
  • step=1 Indicates that the default value of the third parameter is 1.
  • range What this BIF does is generate a sequence of numbers startstarting with the value of the parameter and stopending with the value of the parameter that contains startthe value of but not stopthe value of .

【example】

for i in range(2, 9):  # 不包含9
    print(i)

for i in range(1, 10, 2):
    print(i)

6. enumerate() function

enumerate(sequence, [start=0])
  • sequence: A sequence, iterator, or other object that supports iteration.
  • start: The starting position of the subscript.
  • Returns the enumerate (enumeration) object

【example】

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1))  # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]


languages = ['Python', 'R', 'Matlab', 'C++']
for language in languages:
    print('I love', language)
print('Done!')


for i, language in enumerate(languages, 2):
    print(i, 'I love', language)
print('Done!')

7. break statement

breakThe statement can jump out of the loop of the current layer.

【example】

import random
secret = random.randint(1, 10) #[1,10]之间的随机数

while True:
    temp = input("猜一猜小姐姐想的是哪个数字?")
    guess = int(temp)
    if guess > secret:
        print("大了,大了")
    else:
        if guess == secret:
            print("你太了解小姐姐的心思了!")
            print("哼,猜对也没有奖励!")
            break
        else:
            print("小了,小了")
print("游戏结束,不玩儿啦!")

8. continue statement

continueTerminates the current cycle and starts the next cycle.

【example】

for i in range(10):
    if i % 2 != 0:
        print(i)
        continue
    i += 2
    print(i)

9. pass statement

pass A statement means "do nothing". If you don't write any statement where a statement is required, the interpreter will prompt an error, and the statement is used to  pass solve these problems.

【example】

"""
pass是空语句,不做任何操作,只起到占位的作用,其作用是为了保持程序结构的完整性。尽管pass语
句不做任何操作,但如果暂时不确定要在一个位置放上什么样的代码,可以先放置一个pass语句,
让代码可以正常运行。
"""
def a_func():
    pass

10. Derived ****

list comprehension

[ expr for value in collection [if condition] ]

【example】

x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]


x = [i ** 2 for i in range(1, 10)]
print(x)
# [1, 4, 9, 16, 25, 36, 49, 64, 81]


x = [(i, i ** 2) for i in range(6)]
print(x)

# [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]


x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)

# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]


a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)

# [(0, 2)]

tuple comprehension

( expr for value in collection [if condition] )

【example】

a = (x for x in range(10))
print(a)

# <generator object <genexpr> at 0x0000025BE511CC48>

print(tuple(a))

# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

dictionary comprehension

{ key_expr: value_expr for value in collection [if condition] }

【example】

b = {i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}

Guess you like

Origin blog.csdn.net/chunzhi128/article/details/125030359