Python from Scratch¶

Feng Li

School of Statistics and Mathematics

Central University of Finance and Economics

feng.li@cufe.edu.cn

https://feng.li/python

Using Python as a calculator¶

In [4]:
3***2
  Cell In[4], line 1
    3***2
       ^
SyntaxError: invalid syntax
In [2]:
17 - 4
Out[2]:
13
In [3]:
4/2
Out[3]:
2.0
In [3]:
(5 + 4)*3
Out[3]:
27
  • The remainder can be calculated with the % operator
In [6]:
x = 2004
print(x % 100 == 0)
print(x % 4   == 0)
False
True
  • Powers With Python, use the ** operator to calculate powers.
In [12]:
print(5^2) # ^ XOR

print(5**2)

print(5*2)
7
25
10
  • Note Caret (^) invokes the exclusive OR(XOR) of the object: a logical operation that outputs true only when both inputs differ (one is true, the other is false).
In [7]:
True^True
Out[7]:
False
In [7]:
False^True
Out[7]:
True
In [9]:
True^False
Out[9]:
True
In [10]:
2^3
Out[10]:
1
In [11]:
format(2,'b')
Out[11]:
'10'
In [12]:
format(3,'b')
Out[12]:
'11'
In [13]:
int('01',2)
Out[13]:
1
  • The equal sign (=) is used to assign a value to a variable. Afterwards, no result is displayed before the next interactive prompt.
In [2]:
a = 3
b = 5
c = a + b
c
Out[2]:
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.

In [14]:
100/3.0
Out[14]:
33.333333333333336
In [16]:
_
Out[16]:
33.333333333333336

Strings¶

  • Python can also manipulate strings, which can be expressed in several ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same result.
In [16]:
LastName = "Li"
In [18]:
FirstName = "Feng"
  • \ can be used to escape quotes:
In [12]:
print(r"Hello \\\\n World!")
Hello \\\\n World!
  • If you don't want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote:
In [3]:
print(r"Hello \n World!")
print("Hello \\n World!")
Hello \n World!
Hello \n World!
  • Strings can be concatenated (glued together) with the + operator, and repeated with *:
In [21]:
"I " + 'L' + 'o'*5  + 've' + ' you'
Out[21]:
'I Looooove you'
  • The built-in function len() returns the length of a string:
In [24]:
print( ("Feng Li"))
print('love is "love" ')
7
love is "love" 
  • Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings:
In [23]:
"Feng" "Li"
Out[23]:
'FengLi'
In [25]:
print("Hi, my name is Feng Li." 
      " And I am from Beijing.")
Hi, my name is Feng Li. And I am from Beijing.
  • Strings can be indexed (subscripted), with the first character having index 0. There is no separate character type; a character is simply a string of size one:
In [26]:
Name = "Feng Li"
#       0123456
#   ...-4-3-2-1
Name[1]
Out[26]:
'e'
In [26]:
Name[-1]
Out[26]:
'i'
In [27]:
Name[-2]
Out[27]:
'L'
  • In addition to indexing, slicing is also supported. While indexing is used to obtain individual characters, slicing allows you to obtain a substring:
In [28]:
# "Feng Li"
Name[0:4]  # [a:b] - > [a, b)
Out[28]:
'Feng'
In [29]:
Name[:4]   # 0,1,2,3 4)
Out[29]:
'Feng'
In [30]:
Name[5:]
Out[30]:
'Li'
In [22]:
print = 2
In [25]:
del print
In [26]:
print("myhome")
myhome
  • However, out of range slice indexes are handled gracefully when used for slicing:
In [32]:
Name[5:100]
Out[32]:
'Li'
In [13]:
myhome = "mama" + '13800001234' + 'mama@163.com'
In [18]:
myhome[4:]
myhome[8:]
Out[18]:
'0001234mama@163.com'

Lists¶

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.

In [33]:
values = [1,5,7,9,12]
In [34]:
len(values)
Out[34]:
5
In [35]:
values[0]
Out[35]:
1
In [36]:
values[-2:]
Out[36]:
[9, 12]
  • Lists also supports operations like concatenation:
In [37]:
values + ["22","33"]
Out[37]:
[1, 5, 7, 9, 12, '22', '33']
  • Lists are a mutable type, i.e. it is possible to change their content:
In [5]:
values = [1,2,3,4,67,22]
values
Out[5]:
[1, 2, 3, 4, 67, 22]
In [6]:
values[2] = 1000
values
Out[6]:
[1, 2, 1000, 4, 67, 22]
In [27]:
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

In [7]:
values.append(9999)
values
Out[7]:
[1, 2, 1000, 4, 67, 22, 9999]
  • Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

[1, 2, 1000, 4, 67, 22, 9999] 0 1 2 3 4 5 6 [1, 2, 2, 3, 4, 67, 22, 9999]

In [41]:
values[2:4] = [2,3,4]
values
Out[41]:
[1, 2, 2, 3, 4, 67, 22, 9999]