Python学习笔记——条件控制

时间:2021-09-21 18:22:45

Python中的条件控制方式基本和C语言类似,主要有如下几种语法:

If条件判断

Python的条件语句的语法是if…elseif…else,如下的一个简单的猜数字的示例演示了这一过程:

number = 23
    guess = int(raw_input('Enter an integer : '))

if guess == number:
        print
'Congratulations, you guessed it.'         # New block starts here
    elif guess < number:
        print
'No, it is a little higher than that'     # Another block
    else:
        print
'No, it is a little lower than that'

从上我们也可以看到:和C不同的是,python并不是通过括号,而是通过缩进来表示语法块。(为了文章排版整齐,我文章的例子都在行首都插入了一个tab键,使用时需要去掉)

While循环语句

这里以一个从1加到100来简单的演示一下while循环的用法:

total = 0;
    count = 0;
    
    whilecount < 100 :
        count = count + 1
        total = total + count
    
    print total

for循环

Python的for循环其实是类似c#的foreach,实现的是遍历功能:

total = 0;
    
    for i in range(1, 101):
     total = total + i
    print total

break & Continue语句

break & continue用法和C语言基本类似:

while True:
        s = raw_input('Enter something : ')
        if s == 'quit':
            break
        if len(s) < 3:
            continue
        print
'Input is of sufficient length'