输出

  1. age = 20
  2. name = 'iWillLie'
  3. # 字符串拼接
  4. print('my age {0},my name {1}'.format(age, name))
  5. print('my age {},my name {}'.format(age, name))
  6. print('my age {age},my name {name}'.format(age=age, name=name))
  7. print(name + ' is ' + str(age) + ' years old')
  8. # 取十进制小数点后的精度为 3 ,得到的浮点数为 '0.333'
  9. print('{0:.3f}'.format(1.0 / 3))
  10. # 填充下划线 (_) ,文本居中
  11. # 将 '___hello___' 的宽度扩充为 11
  12. print('{0:_^11}'.format('hello'))
  13. # 用基于关键字的方法打印显示 'Swaroop wrote A Byte of Python'
  14. print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))
  15. # 将print默认的换行用end替换
  16. print('a', end='')
  17. print('b', end='')

流程控制

  1. # 流程控制
  2. # 判断
  3. msg = int(input('msg:'))
  4. if msg >= 18:
  5. print('成年')
  6. else:
  7. print('未成年')
  8. # 循环
  9. # break 中断循环
  10. # continue 跳过当前循环
  11. number = 23
  12. running = True
  13. while running:
  14. guess = int(input('Enter an integer : '))
  15. if guess == number:
  16. print('Congratulations, you guessed it.')
  17. # 这会导致 while 循环停止
  18. running = False
  19. elif guess < number:
  20. print('No, it is a little higher than that.')
  21. else:
  22. print('No, it is a little lower than that.')
  23. else:
  24. print('The while loop is over.')
  25. # 你可以在此处继续进行其它你想做的操作
  26. print('Done')
  27. # 等价于for i in [1,2,3,4]:
  28. # range 生成1-4
  29. for i in range(1, 5):
  30. print(i, end='')
  31. else:
  32. print('The for loop is over')

函数

  1. def say_hello():
  2. # 属于该函数的语句块
  3. print('hello world')
  4. # 函数结束
  5. say_hello() # 调用函数
  6. say_hello() # 再次调用函数
  7. # 任意参数的函数
  8. def total(a=5, *numbers, **phonebook):
  9. print('a', a)
  10. # 遍历元组中的所有项
  11. for single_item in numbers:
  12. print('single_item', single_item)
  13. # 遍历字典中的所有项
  14. for first_part, second_part in phonebook.items():
  15. print(first_part, second_part)
  16. print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))
  17. def print_max(x, y):
  18. '''Prints the maximum of two numbers.
  19. The two values must be integers.'''
  20. # 如果有必要,将参数转为整数
  21. x = int(x)
  22. y = int(y)
  23. if x > y:
  24. print(x, 'is maximum')
  25. else:
  26. print(y, 'is maximum')
  27. print_max(3, 5)
  28. # 文档字符串 (documentation strings),通常简称为 DocStrings
  29. print(print_max.__doc__)