Feng Li
School of Statistics and Mathematics
Central University of Finance and Economics
3***2
Cell In[4], line 1 3***2 ^ SyntaxError: invalid syntax
17 - 4
13
4/2
2.0
(5 + 4)*3
27
%
operatorx = 2004
print(x % 100 == 0)
print(x % 4 == 0)
False True
print(5^2) # ^ XOR
print(5**2)
print(5*2)
7 25 10
exclusive OR
(XOR) of the object: a logical operation that outputs true only when both inputs differ (one is true, the other is false).True^True
False
False^True
True
True^False
True
2^3
1
format(2,'b')
'10'
format(3,'b')
'11'
int('01',2)
1
a = 3
b = 5
c = a + b
c
8
If you forget to assign a value, you could use the underscore (_
) to fetch the last output.
In interactive mode, the last printed expression is assigned to the variable _. This means that when you are using Python as a desk calculator, it is somewhat easier to continue calculations.
100/3.0
33.333333333333336
_
33.333333333333336
'...'
) or double quotes ("..."
) with the same result.LastName = "Li"
FirstName = "Feng"
\
can be used to escape quotes:print(r"Hello \\\\n World!")
Hello \\\\n World!
\
to be interpreted as special characters, you can use raw strings by adding an r
before the first quote:print(r"Hello \n World!")
print("Hello \\n World!")
Hello \n World! Hello \n World!
+
operator, and repeated with *
:"I " + 'L' + 'o'*5 + 've' + ' you'
'I Looooove you'
len()
returns the length of a string:print( ("Feng Li"))
print('love is "love" ')
7 love is "love"
"Feng" "Li"
'FengLi'
print("Hi, my name is Feng Li."
" And I am from Beijing.")
Hi, my name is Feng Li. And I am from Beijing.
Name = "Feng Li"
# 0123456
# ...-4-3-2-1
Name[1]
'e'
Name[-1]
'i'
Name[-2]
'L'
# "Feng Li"
Name[0:4] # [a:b] - > [a, b)
'Feng'
Name[:4] # 0,1,2,3 4)
'Feng'
Name[5:]
'Li'
print = 2
del print
print("myhome")
myhome
Name[5:100]
'Li'
myhome = "mama" + '13800001234' + 'mama@163.com'
myhome[4:]
myhome[8:]
'0001234mama@163.com'
Python knows a number of compound data types, used to group together other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets. Lists might contain items of different types, but usually the items all have the same type.
values = [1,5,7,9,12]
len(values)
5
values[0]
1
values[-2:]
[9, 12]
values + ["22","33"]
[1, 5, 7, 9, 12, '22', '33']
values = [1,2,3,4,67,22]
values
[1, 2, 3, 4, 67, 22]
values[2] = 1000
values
[1, 2, 1000, 4, 67, 22]
a.b = 5
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[27], line 1 ----> 1 a.b = 5 NameError: name 'a' is not defined
You can also add new items at the end of the list, by using the append() method
values.append(9999)
values
[1, 2, 1000, 4, 67, 22, 9999]
[1, 2, 1000, 4, 67, 22, 9999] 0 1 2 3 4 5 6 [1, 2, 2, 3, 4, 67, 22, 9999]
values[2:4] = [2,3,4]
values
[1, 2, 2, 3, 4, 67, 22, 9999]