2

Python__09--函数结构之顺序结构与选择结构

 1 year ago
source link: https://blog.51cto.com/husheng/5958875
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Table of Contents

1 顺序结构

按照实物本身特性,必须一个接着一个来完成。

2 选择结构

到某个节点后,会根据一次判断结果来决定之后走哪一个分支。 在编写代码时,函数体可用pass占位,防止报错

2.1 单分支结构

if 判断 (90<=a<=100):

2.2 双分支结构

if else

if 判断 : 
	函数体
else: 
	函数体

测试代码:

num=int(input('请输入一个整数:'))
if num%2==0 :
    print(num ,'是偶数')
else:
    print(num,'是奇数')

测试结果:

Python__09--函数结构之顺序结构与选择结构_函数结构

条件表达式:if else的简写

'判断为真执行的函数体' **if** a>=b **else** '判断为假执行的函数体'

测试代码:

a = 1
b = 2
print("==============1===============")
print(str(a)+'大于等于'+str(b) if a>=b else str(a)+'小于'+str(b))
a = 2
b = 1
print("==============2===============")
print(str(a)+'大于等于'+str(b) if a>=b else str(a)+'小于'+str(b))

测试结果:

Python__09--函数结构之顺序结构与选择结构_函数结构_02

2.3 多分支结构

if  判断 1 :
        函数体
elif   判断2:
        函数体
elif   判断3:
        函数体
…………
elif   判断n:
        函数体
else:(可省略)
        函数体

测试代码:

score=int(input('请输入一个成绩:'))
if 90 <= score <= 100:
    print('A')
elif score>=80 and score<=89:
    print('B')
elif score>=70 and score<=79:
    print('C')
elif score>=60 and score<=69:
    print('D')
elif score>=0 and score<=59:
    print('E')
else:
    print('成绩有误,请重新输入')

测试结果:

Python__09--函数结构之顺序结构与选择结构_函数结构_03


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK