Python 条件语句
Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
可以通过下图来简单了解条件语句的执行过程:

Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
Python 编程中 if 语句用于控制程序的执行,基本形式为:
if 判断条件:
执行语句……
else:
执行语句……其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。
else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句。
Gif 演示:

import ifTest
if __name__ == '__main__':
try:
print('条件循环开始:')
count1 = 0;
count2 = 0;
test = 0;
ifWhileForObj = ifTest.ifWhileFor(count1,count2,test)
ifWhileForObj.ifWhileFors()
print('条件循环结束:')
except BaseException as Argument:
print(Argument)
except ValueError as Argument:
print(Argument)猜数字小游戏
import random
class ifWhileFor:
def __init__(self,count1,count2,test):
self.count1 = count1
self.count2 = count2
self.test = test
def ifWhileFors(self):
count1 = self.count1;
count2 = self.count2;
test = self.test;
randoms = random.randint(0,100);
# print(randoms);
print('猜数字游戏');
while (count1<3):
if count1 == 0:
YN = input("是否开始游戏(Y:开始,N:退出):");
if YN == "Y":
count1 = count1 + 1;
while (count2 <5):
test = input("第" + str(count2 + 1) + "次输入0-100请输入你心中想的数字:");
test = int(test);
count2 = count2 + 1;
if test == randoms:
print('太棒了,你简直是个小机灵鬼');
break;
elif test > randoms:
print('您猜大了,再接再厉!');
else :
print('您猜小了,再接再厉!');
if test != randoms:
print("您的5次机会已用尽,游戏自动退出");
else:
print("游戏退出");
break;
else:
YN = input("是否继续游戏(Y:继续,N:退出):");
if YN == "Y":
count2 = 0;
count1 = count1 + 1;
while (count2 <5):
test = input("第" + str(count2 + 1) + "次输入0-100请输入你心中想的数字:");
test = int(test);
count2 = count2 + 1;
if test == randoms:
print('太棒了,你简直是个小机灵鬼');
break;
elif test > randoms:
print('您猜大了,再接再厉!');
else :
print('您猜小了,再接再厉!');
if test != randoms:
print("您的5次机会已用尽,游戏自动退出");
else:
print("游戏退出");
break;
print("游戏退出,数字为:", randoms);fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
输出结果为:
当前水果 : banana
当前水果 : apple
当前水果 : mango
使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。
print("计算1+2+3+...+100的结果:")
result=0
for i in range(101):
result+=i
print(result)
range()函数,该函数是python内置函数,用于生成一系列联连续的整数。
range(start,end,step)
start:用于指定计数的起始,可以省略,如果省略则从0开始。
end:用于指定计数的结束值,但是不包括结束的值,比如range(7),则得到的值为0-6,不包括7)
step:用于指定步长,就是两个数之间的间隔。可以省略,如果省略则表示步长为1。
a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
print i, a[i]增强循环
f = open("a.txt")
lines = f.readlines()
print(type(lines))
for line in lines:
print line,
f.close()
输出结果:
<type 'list'>
Hello
Welcome
What is the ...
















