python learning 7 (three logical structures)

Logical structure

The logical structure consists of three basic structures

  • Sequence structure
  • Judgment structure
  • Cyclic structure

Sequence structure:

Meaning: The program code is executed sequentially from top to bottom.
Code example:

print(1)
print(2)
print(3)
print(4)
print(5)

Example result:
Insert picture description here

Judgment structure:

Meaning: if the situation a is met, it will be event 1; if the situation a is not met, then the event 2 will be
judged sentence

  1. Single branch statement
  2. Double branch structure
  3. Multi-branch structure
  4. Conditional expression

Code example:

money=int(input('输入你的存款'))
#单分支结构
if money<=0:
    print("你没钱")
#双分支结构
if 0<money<1000:#更复合自然语言含义,与c语言不同
    print("你钱很少")
else:
    print("稍有资产")
#多分支结构
if 0<money<100:
    #符合条件后,其余的elif不比较
    print("10元户")
elif 0<money<1000:
    print("百元户")
elif 0<money<10000:
    print("千元户")
elif 0<money<100000:
    print("万元户")
else:
    print("else可有可无")
#条件表达式
print("表达式为真" if money>0 else "表达式为假")

Example result:
Insert picture description here

Loop structure:

Meaning: the code segment is executed repeatedly until the conditions are met

  • while loop
  • for-in loop

Code example:

r=range(10)
print(list(r))
n=0
#定义序列  从1到9的数组
while n<5:
    n+=1
    print(n)
print('while循环')
for R in '这是字符串':
    print(R)
print('for循环')
for R in r:
#for _ in r:不需要变量时可用_代替
    print(R)
print('for循环')

Example result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_40551957/article/details/114233445