python学习 一.基础知识

# -*- coding: utf-8 -*-

Python3全面支持Unicode后,变量名可以为中文

你好 = "Hello"

两种注释的方法

# print(1)

"""
print(2)
"""
第二种方法还可以使用在多行字符串
_str = """
    Life is short,
    I use python
"""

同时为多个变量赋值

a = b = 1
a, b = 1, 2

解释下a = "abc" 时,python做的事情

1.在内存中创建了一个‘abc’的字符串对象

2.在内存中创建了一个名为a的变量,并把它指向’abc‘


运算符

  • / : 普通除法,结果为浮点型
  • // : 地板除,取商的整数部分
  • % : 取余数

同时得到商和余数

print(divmod(10, 3))
> (3, 1)
print(type(divmod(10, 3)))
> tuple


浮点数精度的问题

print(0.1+0.1+0.1-0.3)
> 5.551115123125783e-17

解决这个问题需要引入Decimal模块

from decimal import Decimal

res = Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
print(res, type(res))
> 0.0 <class 'decimal.Decimal'>


比较运算符结合使用——有意(N)思(C)的题目

3 > 2 > 1
# 等价于
3 > 2 and 2 > 1
> True

True == 1
> True
False == 0
> True

(3 > 2) > 1
> False
# (3 > 2)的结果为True,True > 1的结果为False

(3 > 2) > 0
> True


逻辑运算符

  • and
  • or
  • not

成员运算符

  • in,可用于字符串、列表、字典等
  • not in
print('a' in 'abc')
print('a' in {'a': 1, 'b': 2})
print(1 in [1, 2, 3])

三元运算符,python中的三元运算符可读性更突出

a = 1 if 2 > 1 else 0


字符串操作strip(),去除字符串左右两边的空格

s = '   H e l l o   '
print(s.strip())
> H e l l o

strip

  • n.带;(陆地、海域等)狭长地带;带状水域;队服
  • v.夺;脱掉大部分衣服;扒光…的衣服;进行脱衣表演
  • adj.脱衣舞的;被剥去外皮的

来自bing的中文翻译....


return

return可以返回多个值,例如return 1, 2, 3

def func():
	return 24, {"player": "kobe"}, [5, 81]

a, b, c = func()


猜你喜欢

转载自blog.csdn.net/chenjineng/article/details/80693658
今日推荐