本文是笔者在学习MOOC课程《Python语言基础与应用》 (北京大学-陈斌)中根据上机课时的要求写下在代码
课程总链接:
本节课链接
数值基本运算: 33和7
+, -, *, /, //, %, **
hex(), oct(), bin()
Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 33+7
40
>>> 33-7
26
>>> 33*7
231
>>> 33/7
4.714285714285714
>>> 33//7
4
>>> 33%7
5
>>> 33**7
42618442977
>>> 7**33
7730993719707444524137094407
>>> 33**33
129110040087761027839616029934664535539337183380513
>>> hex(33)
'0x21'
>>> hex(7)
'0x7'
>>> oct(7)
'0o7'
>>> oct(33)
'0o41'
>>> bin(33)
'0b100001'
>>> bin(7)
'0b111'
类型转换
1, 0, 'abc', None, 1.2, False, ''
str(), bool(), int(), float()
is None, ==, !=
>>> str(1)
''
>>> str(0)
''
>>> bool(1)
True
>>> bool(0)
False
>>> bool('abc')
True
>>> int('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'
>>> int('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>> float('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: 'abc'
>>> float(1)
1.0
>>> str(None)
'None'
>>> int(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
>>> int('None')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'None'
>>> int(1.2)
1
>>> int(False)
0
>>> int(True)
1
>>> float('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float:
>>> bool('')
False
>>> 1 is None
False
>>> 0 is None
False
>>> '' is None
False
>>> 1==1.2
False
>>> False is None
False
>>> True is None
False
字符串基本操作
+, *, len(), [], in
ord(), chr()
含有中文的字符串
>>> a='Congratulations'
>>> b='misunderstandings'
>>> a+b
'Congratulationsmisunderstandings'
>>> a+' '+b
'Congratulations misunderstandings'
>>> len(a)
15
>>> len(b)
17
>>> c in a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> 'c' in a
False
>>> 's' in b
True
>>> 'C' in a
True
>>> [a]
['Congratulations']
>>> ord('a')
97
>>> chr(86)
'V'
>>> ord(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: ord() expected a character, but string of length 15 found
>>> c='你好'
>>> d='国'
>>> len(c)
2
>>> len(d)
1
>>> ord(d)
22269
>>> chr(83475)
'