程序员

Python基础学习2:Python基础概念

2017-10-02  本文已影响84人  Andy_Ron
# print absolute value of an integer:
a = 100
if a >= 0:
    print(a)
else:
    print(-a)

数据类型和变量

'I\'m \"OK\"!'
>>> print '\\\t\\'
\       \
>>> print r'\\\t\\'
\\\t\\
print('''line1
line2
line3''')
>>> 9 / 3
3.0
>>> 10 // 3
3

字符编码

Python的字符串

>>> ord('A')
65
>>> ord('中')
20013
>>> chr(66)
'B'
>>> chr(25991)
'文'
>>> '\u4e2d\u6587'
'中文'
>>> 'ABC'.encode('ascii')
b'ABC'
>>> '中文'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
>>> '中文'.encode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)

纯英文的str可以用ASCII编码为bytes,内容是一样的,含有中文的str可以用UTF-8编码为bytes。含有中文的str无法用ASCII编码,因为中文编码的范围超过了ASCII编码的范围,Python会报错。

>>> b'ABC'.decode('ascii')
'ABC'
>>> b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'中文'
>>> len(b'ABC')
3
>>> len(b'\xe4\xb8\xad\xe6\x96\x87')
6
>>> len('中文'.encode('utf-8'))
6
# -*- coding: utf-8 -*-
>>> '%2d-%02d' % (3, 1)
' 3-01'
>>> '%.2f' % 3.1415926
'3.14'
>>> 'Age: %s. Gender: %s' % (25, True)
'Age: 25. Gender: True'

如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串。

使用list和tuple

classmates = ['Michael', 'Bob', 'Tracy']
classmates[-1]
classmates.append('Adam')
classmates.insert(1, 'Jack')
classmates.pop()          # 删除list末尾的元素
classmates.pop(1)        # 删除指定位置的元素
classmates[1] = 'Sarah'
len(classmates)
>>> classmates = ('Michael', 'Bob', 'Tracy')

条件判断

if age >= 18:
    print('your age is', age)
    print('adult')
else:
    print('your age is', age)
    print('teenager')


if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
else:
    print('kid')

循环

sum = 0
for x in range(101):
    sum = sum + x
print(sum)

使用dict和set

    d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}
    d['Michael']
    d.get('Thomas')     # None
    d.get('Thomas', -1) # -1
    d.pop('Bob')
>>> 'Thomas' in d
False
 >>> d.pop('Bob')
75
>>> d
{'Michael': 95, 'Tracy': 85}
>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.remove(4)
>>> s
{1, 2, 3}

参考:《Python教程》

上一篇下一篇

猜你喜欢

热点阅读