print("Hello world!")
print(1, "plus", 2, "equals", 1+2)
name=input("Give me your name: ")
print("Hello,", name)
Hello world! 1 plus 2 equals 3 Give me your name: Canhong Wen Hello, Canhong Wen
if
statement, while
loops and for
loop, is indented with a tabulator or four spaces. for i in range(3):
print("Hello")
print("Bye!")
Hello Hello Hello Bye!
The basic data types in Python are: int
, float
, complex
, str
(a string), bool
(a boolean with values True and False), and bytes
.
type()
, dtypes()
i=5
type(i)
int
f=1.5
type(f)
float
c=0+1j # Note that j denotes the imaginary unit of complex numbers.
print("Complex multiplication:", c*c)
print("The real part is", c.real, "and the imaginary part is", c.imag)
Complex multiplication: (-1+0j) The real part is 0.0 and the imaginary part is 1.0
print(3==4)
False
s="conca" + "tenation"
print(s)
concatenation
len(s)
13
print(int(-2.8))
print(float(2))
print(int("123"))
print(bool(-2), bool(0)) # Zero is interpreted as False
print(str(234))
-2 2.0 123 True False 234
1
, 1.2
, "text"
, or variables. 1+2
3
7/(2+0.1)
3.333333333333333
2**3
8
22%8
6
22//8
2
Comparison operators & Boolean operators
==
, !=
, <
, >
, <=
, >=
.and
, or
, not
42==42
True
(-1)**2 == 1
True
c > 0 and c !=1
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-17-429c2b4174f0> in <module>() ----> 1 c > 0 and c !=1 TypeError: '>' not supported between instances of 'complex' and 'int'
not True
False
Operators on strings
'Statistical' + 'software'
'Statisticalsoftware'
'Statistical' + 'software' + 2020
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-20-111e21b133df> in <module>() ----> 1 'Statistical' + 'software' + 2020 TypeError: can only concatenate str (not "int") to str
'Statistical' + 'software' + str(2020)
'Statisticalsoftware2020'
str2 * 5 ## replicate the string with 5 times
# str2 * 5.0
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-22-a37201cf2450> in <module>() ----> 1 str2 * 5 ## replicate the string with 5 times 2 # str2 * 5.0 NameError: name 'str2' is not defined
str1 = 'Statistical'
str2 = 'software'
str_combine = str1 + str2
str_combine.upper()
'STATISTICALSOFTWARE'
str_combine.islower()
False
str_combine.lower().title()
'Statisticalsoftware'
isX:
isalpha()
isalnum()
isdecimal()
isspace()
istitle()
"hello123".isalpha()
False
Paste or split strings
', '.join([str1, str2, "2020"])
'Statistical, software, 2020'
' '.join([str1, str2, "2020"])
'Statistical software 2020'
'Statistical, software, 2020'.split(',')
['Statistical', ' software', ' 2020']
'Statistical, software, 2020'.split('s')
['Stati', 'tical, ', 'oftware, 2020']
'Statistical software (2020)'.rjust(30)
' Statistical software (2020)'
'Statistical software (2020)'.rjust(30, "*")
'***Statistical software (2020)'
'Statistical software (2020)'.ljust(30)
'Statistical software (2020) '
'Statistical software (2020)'.center(50, "=")
'===========Statistical software (2020)============'
list
is a data structure that holds an ordered collection of items i.e. you can store a sequence of items in a list.[ ]
.range(num)
list0=[] #Create an empty list
list1=['团购名','店名','团购活动ID','团购介绍','购买人数','团购评价','评价人数','地址','团购内容'] #创建列表火锅数据字段名列表
list2=['13377118',8,'随便退']
list3=['壹分之贰聚会吧桌游轰趴馆(旗舰店)',list2] #列表嵌套
print(list3)
['壹分之贰聚会吧桌游轰趴馆(旗舰店)', ['13377118', 8, '随便退']]
len(list3)
2
list3[0]
'壹分之贰聚会吧桌游轰趴馆(旗舰店)'
list3[-1]
['13377118', 8, '随便退']
list3[1][0]
'13377118'
type(list)
mylist.append(newelement)
mylist.insert(position, newelement)
list1 + list2
len(list)
list[i]
, list[:length]
, list[start:end]
, in
del
index()
help(list.extend)
or help(list)
list4=['到期时间','团购价','市场价','备注','购买须知']
print(type(list4))
list6 = list4
print(list6)
list6.append('团购名') #在列表的最后的位置加入"团购名"
print(list6)
list6.insert(0,'店名') #在列表的第一个位置加入"店名"
print(list6)
list6.append('团购名') #在列表的最后的位置再加入"团购名"
print(list6)
print(list6.count('团购名')) #计算有多少个元素是"团购名",返回值为2
<class 'list'> ['到期时间', '团购价', '市场价', '备注', '购买须知'] ['到期时间', '团购价', '市场价', '备注', '购买须知', '团购名'] ['店名', '到期时间', '团购价', '市场价', '备注', '购买须知', '团购名'] ['店名', '到期时间', '团购价', '市场价', '备注', '购买须知', '团购名', '团购名'] 2
list5=list1+list4
print('List5 =', list5)
print('Sorted list5 =',list5.sort())
List5 = ['团购名', '店名', '团购活动ID', '团购介绍', '购买人数', '团购评价', '评价人数', '地址', '团购内容', '店名', '到期时间', '团购价', '市场价', '备注', '购买须知', '团购名', '团购名'] Sorted list5 = None
len(list5)
17
print (list5[:])
print (list5[0])
print (list5[:3]) # length = 3
print (list5[2:7])
['到期时间', '团购介绍', '团购价', '团购内容', '团购名', '团购名', '团购名', '团购活动ID', '团购评价', '地址', '备注', '市场价', '店名', '店名', '评价人数', '购买人数', '购买须知'] 到期时间 ['到期时间', '团购介绍', '团购价'] ['团购价', '团购内容', '团购名', '团购名', '团购名']
list5.remove('到期时间')
len(list5)
16
del list5
list5
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-45-00cbe1778fa8> in <module>() 1 del list5 ----> 2 list5 NameError: name 'list5' is not defined
list4
['店名', '到期时间', '团购价', '市场价', '备注', '购买须知', '团购名', '团购名']
list4.index('店名')
0
list4.index('Name')
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-48-4720ba27c483> in <module>() ----> 1 list4.index('Name') ValueError: 'Name' is not in list
list4.index('团购名')
6
sort
method modifies the original listsorted
function returns a new sorted list and leaves the original intact. L=[5,3,7,1]
L.sort() # here we call the sort method of the object L
print(L)
[1, 3, 5, 7]
L2=[6,1,7,3,6]
print(L2)
[6, 1, 7, 3, 6]
print(sorted(L2))
[1, 3, 6, 6, 7]
print(L2)
[6, 1, 7, 3, 6]
print(sorted(L, reverse=True)) # descending order
[7, 5, 3, 1]
list
.tuple0=() # create an empty tuple
tuple1=(2,4,5)
tuple2=('a','b','c')
tuple3=(21,'a','c')
print('Number of elements in the tuple1 is', len(tuple1))
print('The second element of tuple2 is', tuple2[1])
print('The first two elements of tuple2 are', tuple2[0:1])
Number of elements in the tuple1 is 3 The second element of tuple2 is b The first two elements of tuple2 are ('a',)
tuple4=tuple2+tuple3
print('The combination of tuple2 and tuple3 is ', tuple4)
tuple5=tuple4[2:5]
print('Some elements of tuple5 are', tuple5)
The combination of tuple2 and tuple3 is ('a', 'b', 'c', 21, 'a', 'c') Some elements of tuple5 are ('c', 21, 'a')
tuple2[2]=4 # Cannot change the value
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-57-7ee9b6d2023c> in <module>() ----> 1 tuple2[2]=4 # Cannot change the value TypeError: 'tuple' object does not support item assignment
d = {key1 : value1, key2 : value2 }
keys()
, values()
, items
, get()
dict0={'六婆串串香火锅':6,'嗲串串':14}
print('Type of dict0 is', type(dict0))
Type of dict0 is <class 'dict'>
print('嗲串串有',dict0['嗲串串'], '人团购')
嗲串串有 14 人团购
dict0['古城串串']=0
print('The new version of dict0 is',dict0)
The new version of dict0 is {'六婆串串香火锅': 6, '嗲串串': 14, '古城串串': 0}
dict0['古城串串']=2
print('The updated version of dict0 is',dict0)
The updated version of dict0 is {'六婆串串香火锅': 6, '嗲串串': 14, '古城串串': 2}
del dict0['古城串串']
print('The updated version of dict0 is',dict0)
The updated version of dict0 is {'六婆串串香火锅': 6, '嗲串串': 14}
print('商家有:', dict0.keys())
商家有: dict_keys(['六婆串串香火锅', '嗲串串'])
print('对应的团购人数为:', dict0.values() )
对应的团购人数为: dict_values([6, 14])
print(dict0.items()) #返回值[('六婆串串香火锅', 6), ('嗲串串', 14)]
dict_items([('六婆串串香火锅', 6), ('嗲串串', 14)])
print('嗲串串有',dict0.get('嗲串串'), '人团购')
嗲串串有 14 人团购
'嗲串串' in dict0.keys()
True
'海底捞' not in dict0.keys()
True
Sets are unordered collections of simple objects.
set1 = {1, 2, 's', 1, 1}
set1
{1, 2, 's'}
type(set1)
set
set2 = set([1,3,4,5])
print(set2)
{1, 3, 4, 5}
set3=set((1,3,'e'))
print(set3)
{1, 'e', 3}
set('apple')
{'a', 'e', 'l', 'p'}
set(['apple'])
{'apple'}
A={1,2,3}
B={3,4,5}
A - B ## set difference
{1, 2}
A | B ## union
{1, 2, 3, 4, 5}
A & B ## intersection
{3}
set4 = set(['grape', 'apple', 'banana', 'pear'])
print(set4)
{'apple', 'pear', 'grape', 'banana'}
set4.add('orange')
print(set4)
{'apple', 'orange', 'banana', 'pear', 'grape'}
set4.remove('orange')
print(set4)
{'apple', 'banana', 'pear', 'grape'}
set4.clear()
print(set4)
set()