Python笔记(1)----条件、循环语句

来源:互联网 发布:淘宝偏远地区有哪些 编辑:程序博客网 时间:2024/05/13 14:59
1,if条件语句


    if 判断条件:
         执行语句
    else:
         执行语句


num = 3if num < 5:    print "yes"else:    print "no




条件较多时可以用or或者and,and(同时成立)、or(一个成立即可)。


if (num > 1 and num < 5) or (num > 6 and num < 9):
    print "yes"
else:
    print "no"


2,while循环语句
 
 while 判断条件:
      执行语句


count = 0
while (count < 9):
    print"the count is:",count
    count = count + 1
print "good bye"


while语句的continue、break命令


i=1
while i <10:
    i +=1
    if i%2>0:
        continue
    print i


i=1
while 1:
    print i
    i+=1
    if i>10:
        break


while 无线循环


v = 1
while v == 1:
    num = raw_input("Enter a number : ")
    print "You entered: ", num


while.....else循环


c = 0
while c < 5:
    print c, "is less than 5"
    c = c + 1
else:
    print c, " is not less than 5"


3,for循环
  
for interating_var in sequence:
    statements(s)


fruits = ['banana','apple','mango']
for fruit in fruits:
    print "current fruit:",fruit




通过索引执行循环


fruits = ['banana','apple','mango']
for index in range(len(fruits)):
    print "current fruit:",fruits[index]


注:range()返回一个序列数,len()返回列表的长度。


for....else


for num in range(10,20):
    for i in range(2,num):
        if num % i == 0:
            j = num/i
            print "%d equal %d * %d" % (num ,i,j)
            break
    else:
        print num, "is a prime number"


4,循环嵌套


i = 2
while(i < 100):
    j = 2
    while(j <= (i/j)):
        if not(i%j):
            break
        j = j + 1
    if (j > i/j):
          print i, "is a prime number"
    i = i + 1
print "Good bye!"


pass语句


for letter in 'Python':
   if letter == 'h':
      pass
      print 'this is pass block'
   print 'current letter :', letter


print "Good bye!"

阅读全文
0 0