# 跟老齐学python之复习if语句

if 判断条件1:

elif 判断条件2:

elif 判断条件3:

else:

>>> bool(“”)
false
>>> bool(0)
false
>>> bool(‘none’)
true
>>> bool(false)
false
>>> bool(“false”)
true
>>> bool(true)
true
>>> bool(“true”)
true
>>> bool(3>4)
false
>>> bool(“b”>”a”)
true
>>> bool(not “”)
true
>>> bool(not true)
false

if 忘记:

>>> x = 9

>>> if bool(x>7): #条件为true则执行下面的
… print “%d more than 7″%x
… else:
… print “%d not more than 7″%x

9 more than 7

>>> if x>7:
… print “%d more than 7″%x
… else:
… print “%d not more than 7″%x

9 more than 7

>>> if (x>7): #不提倡这么写，这不是python风格
… print “%d more than 7″%x

9 more than 7

#! /usr/bin/env python
#coding:utf-8

print “请输入字符串,然后按下回车键：”

user_input = raw_input()

result = user_input.isdigit()

if not result:
print “您输入的不完全是数字”

elif int(user_input)%2==0:
print “您输入的是一个偶数”
elif int(user_input)%2!=0:
print “您输入的是一个奇数”
else:
print “您没有输入什么呢吧”

#!/usr/bin/env python
#coding:utf-8

import random

numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到随机的list

odd = []
even = []

for x in numbers:
if x%2==0:
even.append(x)
else:
odd.append(x)

print numbers
print “odd:”,odd
print “even:”,even

#!/usr/bin/env python
#coding:utf-8

import random

numbers = [random.randint(1,100) for i in range(20)] #以list解析的方式得到随机的list

odd = [x for x in numbers if x%2!=0]
even = [x for x in numbers if x%2==0]

print numbers
print “odd:”,odd
print “even:”,even

>>> name = “qiwsir” if “laoqi” else “github”
>>> name
‘qiwsir’
>>> name = ‘qiwsir’ if “” else “python”
>>> name
‘python’
>>> name = “qiwsir” if “github” else “”
>>> name
‘qiwsir’

if语句似乎简单，但是在编程时间中常用到。勤加练习吧。

Posted in 未分类