美文网首页
【Python】-008-语句表达式-条件/循环

【Python】-008-语句表达式-条件/循环

作者: 9756a8680596 | 来源:发表于2017-07-16 21:32 被阅读9次

    1.条件语句

    语法

    if xxx: statements1
    elif: statements2
    else: statements3
    

    其他用法

    逻辑表达式:not / and / or / 1<x<3
    

    2.循环语句

    while举例

    #判断输入的整数是否为质数
    y = input('Pleae a number:')
    x = y//2
    flag = 1
    
    while x > 1:
      if y%x == 0:
        flag = 0
        print y,'has factor, ', x
        # break
      x = x - 1;
    
    if flag == 1:
      print y,'is prime number.'
    else:
      print y,'is not a prime number.' 
    

    for举例

    #遍历字符串/元组
    s = u'你在远方'
    t = (u'我', u'在', u'故乡')
    for i in s: print '\b'+i,
    for j in t: print '\b'+j,
    #遍历字典,并写入文件
    d = {'name': 'Bob', 'age': 33, 'gender': 'male'}
    file = open('test.txt', 'w')
    for key in d:
        print >> file, key, '==>', d[key]
    file.close()
    # 读取文件内容,体会while和for两种方式差别
    file = open('test.txt', 'r')
    while True:
      line = file.readline()
      if not line: break
      print line.strip()
    file.close()
    
    for line in open('test.txt', 'r'):
      print line.strip()

    相关文章

      网友评论

          本文标题:【Python】-008-语句表达式-条件/循环

          本文链接:https://www.haomeiwen.com/subject/mpxxkxtx.html