1. if
- if语句
- if expression(关键字):
statement(s)
- if expression(关键字):
注:Python使用缩进作为其语句分组的方法,建议使用4个空格,不要用table制表符。这是通用习惯。
举例:
#!/usr/bin/python
if 1 < 2:
print 'hello'
执行结果:
[root@t1 py]# python if.py
hello
- 逻辑值(bool)包含了两个值:
- True:表示非空的量(比如:string,tuple,list,set,dictonary),所有非零数。
- False:表示0,None,空的量等。
2. else
- else语句:
- if expression:
statement(s)
else:
statement(s)
- if expression:
#!/usr/bin/python
if 1 > 2:
print 'hello'
else:
print 'haha'
执行结果
[root@t1 py]# python if.py
haha
- 复杂的套嵌elif
- if expression1:
statement1(s)
elif expression2:
statement2(s)
else:
statement2(s)
- if expression1:
#!/usr/bin/python
if 1 < 2:
print 'hello'
elif 3 > 2 :
print 'mid'
else:
print 'none'
如果直接执行,结果是hello
改一下脚本:
#!/usr/bin/python
if not 1 < 2:
print 'hello'
elif 3 > 2 :
print 'mid'
else:
print 'none'
结果是mid
3. 得分判断的例子
[root@t1 py]# cat df.py
#!/usr/bin/python
score = int(raw_input("please input a num: "))
if score >= 90:
print 'A'
elif score >= 80:
print 'B'
elif score >= 70:
print 'C'
else:
print 'D'
执行结果:
[root@t1 py]# python df.py
please input a num: 75
C
[root@t1 py]# python df.py
please input a num: 99
A
[root@t1 py]# python df.py
please input a num: 3
D
4. 练习
习题
- 输入三个整数x,y,z,请把这三个数由小到大输出。 1.程序分析:我们想办法把最小的数放到x上,先将x与y进行比较,如果x>y则将x与y的值进行交换, 然后再用x与z进行比较,如果x>z则将x与z的值进行交换,这样能使x最小。
- 企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高 于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提 成7.5%;20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于 40万元的部分,可提成3%;60万到100万之间时,高于60万元的部分,可提成1.5%,高于 100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数?
1.解答
[root@t1 py]# cat lx.py
#!/usr/bin/python
x=int(input('x='))
y=int(input('y='))
z=int(input('z='))
if x<y:
a=x
x=y
y=a
if x<z:
a=x
x=z
z=a
if y<z:
a=y
y=z
z=a
print(x,y,z)
执行结果
[root@t1 py]# python lx.py
x=88
y=5
z=33
(88, 33, 5)
- 解答
[root@t1 py]# cat lx2.py
#!/usr/bin/python
# -*- coding: UTF-8 -*- #很重要,缺失导致字符报错
def reward(profit):
reward = 0.0
if profit<=10:
return profit*0.1
elif profit<=20 and profit>10:
return (profit-10)*0.075+1
elif profit<=40 and profit>20:
return (profit-20)*0.05+10*0.1+10*0.075
elif profit<=60 and profit>40:
return (profit-40)*0.03+20*0.05+10*0.075+10*0.1
elif profit<=100 and profit>60:
return (profit-60)*0.015+20*0.03+20*0.05+10*0.075+10*0.1
elif profit>100:
return (profit-100)*0.01+40*0.015+20*0.03+20*0.05+10*0.075+10*0.1
if __name__ == "__main__":
profit = float(raw_input("please input the profit: "))
print reward(profit)*10000
执行结果
[root@t1 py]# python lx2.py
please input the profit: 55.3
32090.0
网友评论