python 基础教程之5 loop,函数,注释

linux python基础教程 python 3.5

Posted by ivo on March 20, 2018

0x0E loops

  • 循环与列表
    >>> words = ['Hello','world','!','good']
    >>> counter = 0
    >>> maxindex = len(words) -1
    >>> while counter <= maxindex:
    ...     word = words[counter]
    ...     print(word + '?')
    ...     counter = counter + 1
    ...
    Hello?
    world?
    !?
    good?
    
  • for loop
    >>> words = ['Hello','world','!','good']
    >>> for word in words:
    ...     print(word)
    ...
    Hello
    world
    !
    good
    

    注意格式 要加:

    >>> for i in range(5)
    File "<stdin>", line 1
      for i in range(5)
                      ^
    SyntaxError: invalid syntax
    
  • 可以把range与for 结合当做次数来使用
    >>> for i in range(5):
    ...     print("hello")
    ...
    hello
    hello
    hello
    hello
    hello
    

    简单计算器

    ➜  test cat test11.py
    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    # Fuction calculator
    while True:
      print("Options:")
      print("Enter 'add' to add two numbers")
      print("Enter 'subtract' to subtract two numbers")
      print("Enter 'multiply' to multiply two numbers")
      print("Enter 'divide' to divide two numbers")
      print("Enter 'quit' to end the program")
      user_input = input(:)
      if user_input == 'add'
          num1 = float(input("Enter a number:"))
          num2 = float(input("Enter another number:"))
          result = str(num1 +num2)
          print("The answer is " + result)
      elif user_input == 'subtract'
          pass
      elif user_input == 'multiply'
          pass
      elif user_input == 'devide'
          pass
      elif user_input == 'quit'
          break
    

0x0F 函数

  • 定义一个函数
    >>> def print_with_input(word):
    ...     print(word + '!')
    ...
    >>> print_with_input(good)
    File "<stdin>", line 1
      print_with_input(good)
                           ^
    SyntaxError: invalid character in identifier
    传递进去的参数要匹配类型,字符串就是字符串
    >>> print_with_input("good")
    good!
    >>>
    
  • 多个参数传递
    >>> def print_sum_twice(x,y):
    ...     print(x+y)
    ...
    >>> print_sum_twice(6,9)
    15
    
  • 局部变量,全局无效
    >>> def fuction(variable):
    ...     variable +=1
    ...     print(variable)
    ...
    >>> fuction(10)
    11
    
    >>> print(variable)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    NameError: name 'variable' is not defined
    
  • 返回值
    >>> def max(x,y):
    ...     if x>=y:
    ...             return x
    ...     else:
    ...             return y
    ...
    
    >>> print(max(5,7))
    7
    
    >>> z = max(6,8)
    >>> print(z)
    8
    
  • return不能在定义的函数之外使用
  • 字符串长短比较
    >>> def short_test(x,y):
    ...     if len(x) >= len(y):
    ...             return x
    ...     else:
    ...             return y
    ...
    >>> short_test('sada','asdasd')
    'asdasd'
    
  • return 遇到return后立即中止
    >>> def add_numbers(x,y):
    ...     total = x + y
    ...     return total
    ...     print("The result is " + str(total))
    ...
    >>> add_numbers(5,9)
    14
    
  • 问题 关于print函数 无效的句法,问题出在数据类型上
     def add_numbers(x,y):
    ...     total = x + y
    ...     return total
    ...     print("The result is " total)
    File "<stdin>", line 4
      print("The result is " total)
                                 ^
    SyntaxError: invalid syntax
    

    只有它自己时候是正常的,因为只有一种数据类型

    def add_numbers(x,y):
    ...     total = x + y
    ...     print(total)
    ...
    >>> add_numbers(5,9)
    14
    

    前面字符串+还是字符串

     def add_numbers(x,y):
    ...     
    ...     total = x + y
    ...     print("The result is " + total)
    ...
    >>> add_numbers(5,9)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 4, in add_numbers
    TypeError: Can't convert 'int' object to str implicitly
    

0x10 注释

  • 常规方式的 #注释 #以后的内容都是注释
    >>> x = 365
    >>> y = 7
    >>> # This is comment
    ...
    >>> print(x % y) #find the remainder
    1
    >>> # print (x // y )
    ...
    >>> # another comment
    ...
    >>>
    
  • 脚本方式
    ➜  test ./1.py       
    1
    ➜  test cat 1.py
    #!/usr/bin/env python3
    #-*- coding: utf-8 -*-
    x = 365
    y = 7
    # This is comment
    print(x % y) #find the remainder
    # print (x // y )
    # another comment
    
  • 多行注释中间可以用成对儿的3个'''或3个"""
    >>> def shout(word):
    ...     '''
    ...     Print a word with an
    ...     exclamation mark following it.
    ...     '''
    ...     print(word + "!")
    ...
    >>> shout("good")
    good!