python while 循环 if 循环

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。当判断条件假false时,循环结束。

执行流程图如下:

python while 循环 if 循环_第1张图片

python while 循环 if 循环_第2张图片

  • if else 的两种循环结构
name = 'python'
flag = True


if name == 'luna':
    print flag
else:
    print name


if name == 'xiaphong':
    print flag
elif name == 'xiapong':
    print flag
elif name == 'python':
    print '朋友你猜对了'
else:
    print False
  • while 循环:
#!/usr/bin/python

count = 0
while count < 100:
    print 'The count is:', count
    count = count + 1

print "Good bye!"
  • 无限循环:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
var = 1
while var == 1 :  # 该条件永远为true,循环将无限执行下去
   num = raw_input("Enter a number  :")
   print "You entered: ", num
 
print "Good bye!"

输出:

Python 2.7.15 |Anaconda, Inc.| (default, Dec 10 2018, 21:57:18) [MSC v.1500 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.
IPython 5.8.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
PyDev console: using IPython 5.8.0
Python 2.7.15 |Anaconda, Inc.| (default, Dec 10 2018, 21:57:18) [MSC v.1500 64 bit (AMD64)] on win32
runfile('D:/pycharm/TEST02/python file/test02.py', wdir='D:/pycharm/TEST02/python file')
Enter a number  :>? 3
You entered: 傻瓜 3
Enter a number  :

你可能感兴趣的:(python)