Python基础浅析之流程控制


哪门语言都会有流程控制,即if switch while等语句。

应该是每种语言路程控制的原理、作用都是相近的,只是表达形式有所差异而已。

今天就跟大家分享一个Python中的条件、循环等语句。

这里最主要不再用大括号了,而是代码块。

首先需要注意的是if和else之后的冒号:
if

name = raw_input("What is your name? ")
if(name.endswith('Gumby')):
  print 'Hello, Mr. Gumby'

else

name = raw_input("What is your name? ")
if(name.endswith('Gumby')):
  print 'Hello, Mr. Gumby'
else:
  print 'Hello, Stranger'

elif
这里需要注意一下,我们再C++中使用的else if语句,在Python中直接写作:elif

num = input('Enter a number: ')
if num >0 :
  print 'The number is positive'
elif num < 0:
  print 'The number is negative'
else:
  print '0'

while

x = 1
while x <= 100
  print x
  x += 1

for循环
能使用for,就尽量避免使用while

words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
  print word

for遍历字典

d = {'x':1, 'y':2, 'z':3}
for key in d:
  print key, 'corresponds to', d[key]

zip并行迭代

names = ['name', 'beth', 'george', 'damo']
ages = [12, 45, 32, 99]

for name, age in zip(names, ages):
  print name, 'is', age, 'years old'

break跳出循环

continue

 
 

评论关闭