码迷,mamicode.com
首页 > 编程语言 > 详细

Python之‘’控制流‘’

时间:2017-09-08 22:51:45      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:inpu   hat   number   loop   bre   使用   put   highlight   higher   

一、if语句

格式:

i1 = 3
if i1 > 4:
    print(‘yes you are right‘)
elif 0 < i1 < 4:
    print(‘im dont konw‘)
else:
    print(‘no you are wrong‘)

注意if、elif以及else后面的(:)符号,我们通过它告诉Python下面跟着一个语句块。

二、while语句

number = 23
running = True

while running:
    guess = int(input(‘enter an integer:‘))

    if guess == number:
        print(‘congratulations,you guessed it‘)
        running = False
    elif guess < number:
        print(‘no,it is a little lower than that‘)
    else:
        print(‘no,it is a little higher than that ‘)
else:
    print(‘the while loop is over‘)

print(‘done‘)

输出结果:

enter an integer:22
no,it is a little lower than that
enter an integer:24
no,it is a little higher than that
enter an integer:23
congratulations,you guessed it
the while loop is over
done

注意:在Python2.x版本中输入使用的是raw_input而在Python3.x版本中输入使用的是input。并且后面都要跟冒号。

三、for循环

格式:for...in

for i in range(1,5):
    print(i)
else:
    print(‘the loop is over‘)

结果:
C:\Python36\python.exe C:/Users/蔡瑞/7.py
1
2
3
4
the loop is over

Process finished with exit code 0

注意:range(1,5)只是输出1-4没有5。还有,else部分是可选的,如果包含else,它总是在for循环结束后执行一次,除非遇到break语句。

for循环在这个范围内递归,这就相当于把序列中的每个数(或对象)赋值给i,一次一个,然后以每个i的值执行这个程序块。

 

Programming is fun 

When the work is done

if you wanna make your work also fun:

  use Python

Python之‘’控制流‘’

标签:inpu   hat   number   loop   bre   使用   put   highlight   higher   

原文地址:http://www.cnblogs.com/caicairui/p/7496596.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!