输出
age = 20name = 'iWillLie'# 字符串拼接print('my age {0},my name {1}'.format(age, name))print('my age {},my name {}'.format(age, name))print('my age {age},my name {name}'.format(age=age, name=name))print(name + ' is ' + str(age) + ' years old')# 取十进制小数点后的精度为 3 ,得到的浮点数为 '0.333'print('{0:.3f}'.format(1.0 / 3))# 填充下划线 (_) ,文本居中# 将 '___hello___' 的宽度扩充为 11print('{0:_^11}'.format('hello'))# 用基于关键字的方法打印显示 'Swaroop wrote A Byte of Python'print('{name} wrote {book}'.format(name='Swaroop', book='A Byte of Python'))# 将print默认的换行用end替换print('a', end='')print('b', end='')
流程控制
# 流程控制# 判断msg = int(input('msg:'))if msg >= 18: print('成年')else: print('未成年')# 循环# break 中断循环# continue 跳过当前循环number = 23running = Truewhile running: guess = int(input('Enter an integer : ')) if guess == number: print('Congratulations, you guessed it.') # 这会导致 while 循环停止 running = False elif guess < number: print('No, it is a little higher than that.') else: print('No, it is a little lower than that.')else: print('The while loop is over.') # 你可以在此处继续进行其它你想做的操作print('Done')# 等价于for i in [1,2,3,4]:# range 生成1-4for i in range(1, 5): print(i, end='')else: print('The for loop is over')
函数
def say_hello(): # 属于该函数的语句块 print('hello world')# 函数结束say_hello() # 调用函数say_hello() # 再次调用函数# 任意参数的函数def total(a=5, *numbers, **phonebook): print('a', a) # 遍历元组中的所有项 for single_item in numbers: print('single_item', single_item) # 遍历字典中的所有项 for first_part, second_part in phonebook.items(): print(first_part, second_part)print(total(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560))def print_max(x, y): '''Prints the maximum of two numbers. The two values must be integers.''' # 如果有必要,将参数转为整数 x = int(x) y = int(y) if x > y: print(x, 'is maximum') else: print(y, 'is maximum')print_max(3, 5)# 文档字符串 (documentation strings),通常简称为 DocStringsprint(print_max.__doc__)