<Python> python从入门到实践(3) --结构控制语句

结构控制语句

for循环

注:由于在遍历中已经有所提及,这里只对for循环中的else扩展用法进行补充

  • 循环与else:

    ~~~ python
    for <> in <>:
        <语句块1>
    else:
        <语句块2>
    
    
    while<>:
        <语句块1>
    else:
        <语句块2>
    ~~~
    
    # 这里else起到的作用有点类似于异常处理中else的作用,如果循环正常结束而不是被break掉,那么就会执行else后的语句块2
    

if语句

  1. 条件测试:if后面一个值为True或False的表达式被称为条件测试

    一般情况下,大小写不同的值会得到False,但是如果比较upper()或lower()之后的值,则会得到True

  2. 检查多个条件

    • 使用and检查多个条件(相当于&&)

    • 使用or检查多个条件(相当于||)

  3. 检查特定值是否在列表中

    • 使用关键词not inin 来对某元素是否在列表中做出判断
  4. if语句,if-else语句,if-elif-else语句,if-elif语句

    alien_color='green'
    alien_level=3
    # if
    if alien_color == 'green':
        print("5 points gotten!")
    #if-elif-else & and
    if alien_level>0 and alien_level<=99 :
    	print("Good job")
    elif alien_level>99 :
    	print("Great job")
    else :
        print("you cheated")
        
    # if-else & not in
    fruits=['apple','banana','peach','orange','pear']
    fruit='apple'
    if fruit not in fruits :
    	print("You may like "+fruit)
    else :
        print("You may not like "+fruit)
    
  5. if处理列表

    • if <列表名>用于判断列表是否为空

    • in和not in用于判断元素是否在列表内

    • 不区分大小写地判断某字符串是否在列表中

      user_names = ['admin', 'bob', 'cindy', 'dale', 'eric']
      new_names = ['frank', 'grill', 'Cindy', 'eric', 'jack']
      user_name = 'admin'
      if user_names:
          if user_name == 'admin':
              print("hello, admin".title())
          else:
              print("hello".title())
      else:
          print("we need users")
      
      if new_names:
          for new_name in new_names:
              if new_name.lower() not in [user_name.lower() for user_name in user_names]:
                  user_names.append(new_name)
              else:
                  print("Sorry, the name " + new_name+" is occupied.")
      
      print("Now we have users:")
      for user_name in user_names:
          print(user_name.title())
      
  6. 设置if语句的格式

    在诸如==,>=,<=等比较运算符两边各添加一个空格

用户输入和while循环

  1. input("参数") 函数:此函数让程序暂停运行,等待用户输入一些文本,获取用户输入后,python将其存储在一个变量中

    message = input("Tell me something")
    print(message)
    

    其中参数是向用户显示的提示或说明,可以直接为字符串常量,也可以是预先设定的字符串变量,返回值为输入的内容

    • 使用input()时,默认得到的是字符串,而使用int()函数处理可以得到数字

      age = input("Input your age")
      age = int(age)
      
    • 求模运算符%:与c_like语言类似,不过值得注意的是,python使用除法后无论是否整除都会得到浮点数,如果期望整数结果,应该使用int()函数处理

  2. while循环

    # i.e.
    current_num = 1
    while current_num <= 100:
        print(current_num)
        current_num++
    
    • 通过while循环使用户控制何时退出:
    prompt = "\nTlee me something, I'll echo for you!"
    prompt += "\nEnter 'quit' to end the program"
    
    message = ""
    #因为一开始就涉及到message的判断,所以要赋初值
    while message != 'quit':
        message = input(prompt)
        
        if message != 'quit':
            print(message)
    
    • 使用break退出循环,使用continue跳过循环
  3. 使用while循环处理列表和字典:for循环不应该修改列表,否则导致python难以追踪其中的元素,要在遍历列表的同时进行修改可以使用while 循环

    • 在列表之间移动元素

      unconfirmed_user = ["a","b","c"]
      confirmed_user = []
      
      while unconfirmed_user:
          current_user = unconfirmed_user.pop()
          if current_user not in confirmed_user:
          confirmed_user.append(current_user)
          
      
    • 删除包含特定值的所有元素

      pets = ['cat','cat','dog','cat']
      while 'cat' in pets:
          pets.remove('cat')
      
    • 使用用户输入来填充字典

      responses = {}
      polling_active = True
      while polling_active:
          name = input("Input a name:")
          response = input("Which color would you like?")
          responses[name] = response
          repeat = input("Someone else wants to take part?")
          if repeat.lower() == 'no':
              polling_active = False
      
      for name, response in responses.items():
          print(name.title() + " like "+response + ".")
      
  4. eval() 函数:eval(字符串变量或字符串),作用是返回去掉最外层单/双引号的内容,如

    eval("23")得到23

    tempstr="23" eval(tempstr)得到23

posted @ 2020-08-07 17:56  Faura_Sol  阅读(102)  评论(0)    收藏  举报
Live2D