Python: Introduction¶
This notebook provides basic information to get you started. You should read the Python tutorial carefully if you want to master Python.
Comments¶
In [1]:
# This is a python comment
a = 3 # Another comment
Basic types¶
Numbers¶
In [2]:
1234567891011121314151617181920
Out[2]:
1234567891011121314151617181920
In [3]:
3.14
Out[3]:
3.14
In [4]:
2 + 3j
Out[4]:
(2+3j)
Strings¶
In [7]:
'hello, world'
Out[7]:
'hello, world'
In [8]:
"hello, world"
Out[8]:
'hello, world'
In [9]:
"""hello,
world"""
Out[9]:
'hello,\nworld'
In [10]:
'''hello,
world'''
Out[10]:
'hello,\nworld'
In [11]:
b'hello world'
Out[11]:
b'hello world'
In [12]:
name = 'world'
f'hello {name}'
Out[12]:
'hello world'
None¶
In [13]:
None
Basic collection¶
Operators¶
Arithmetic operators¶
In [17]:
1 + 2
Out[17]:
3
In [18]:
1 - 2
Out[18]:
-1
In [19]:
1 * 2
Out[19]:
2
In [20]:
1 / 2
Out[20]:
0.5
In [21]:
1 // 2
Out[21]:
0
In [22]:
7 % 3
Out[22]:
1
In [23]:
7**3
Out[23]:
343
Relational operators¶
In [24]:
2 < 2, 2 > 2
Out[24]:
(False, False)
In [25]:
2 <= 2
Out[25]:
True
In [26]:
2 == 2
Out[26]:
True
In [27]:
2 != 2
Out[27]:
False
Logical operators¶
In [28]:
not True
Out[28]:
False
In [29]:
True and False
Out[29]:
False
In [30]:
True or False
Out[30]:
True
Bitwise¶
In [31]:
16 << 2
Out[31]:
64
In [32]:
16 >> 2
Out[32]:
4
In [33]:
16 | 4
Out[33]:
20
In [34]:
bin(16 | 4)
Out[34]:
'0b10100'
In [35]:
bin(16 & 4)
Out[35]:
'0b0'
In [36]:
bin(16 ^ 4)
Out[36]:
'0b10100'
In [37]:
bin(16)
Out[37]:
'0b10000'
Assignment and augmented assignment¶
In [38]:
a = 3
In [39]:
b = a
In [40]:
a, b
Out[40]:
(3, 3)
In [41]:
a = a + 3
In [42]:
a, b
Out[42]:
(6, 3)
In [43]:
a = [1,2,3]
In [44]:
b = a
In [45]:
a, b
Out[45]:
([1, 2, 3], [1, 2, 3])
In [46]:
a[1] = 12
In [47]:
a, b
Out[47]:
([1, 12, 3], [1, 12, 3])
In [48]:
c = 1
c += 2
In [49]:
c
Out[49]:
3
In [50]:
c *= 3
In [51]:
c
Out[51]:
9
Identity and membership¶
In [52]:
a = 3
b = 3
In [53]:
a is b
Out[53]:
True
In [54]:
a == b
Out[54]:
True
In [55]:
id(a), id(b)
Out[55]:
(4409367312, 4409367312)
In [56]:
a = [1,2,3]
b = [1,2,3]
In [57]:
a is b
Out[57]:
False
In [58]:
a == b
Out[58]:
True
In [59]:
id(a), id(b)
Out[59]:
(4449129352, 4449130760)
In [60]:
2 in [1,2,3]
Out[60]:
True
In [61]:
2 not in [1,2,3]
Out[61]:
False
In [62]:
2 in {'a': 1, 'b': 2}
Out[62]:
False
In [63]:
2 in {1: 'a', 2: 'b'}
Out[63]:
True
Naming conventions¶
In [64]:
NAMES_FOR_CONSTANTS = None
In [65]:
variable_and_function_names = None
In [66]:
ClassNamesAreInCamelCase = None
Control Flow¶
if-elif-else¶
In [67]:
day = 'sunny'
if day == 'rainy':
print('Bring an umbrella')
In [68]:
if day == 'rainy':
print('Bring an umbrella')
else:
print('Come as you are')
Come as you are
In [69]:
if day == 'rainy':
print('Bring an umbrella')
elif day == 'sunny':
print('Bring sunglasses')
elif day == 'snowing':
print('Stay home')
else:
print('Come as you are')
Bring sunglasses
Input and output¶
Reading text files¶
In [75]:
%%file test_file.txt
This old man
He played one
He played knick-knack on my thumb
Writing test_file.txt
The standard way is to treat the file handler as an iterator of lines¶
In [76]:
with open('test_file.txt', 'r') as f:
for line in f:
print(line, end='')
This old man
He played one
He played knick-knack on my thumb
For small files, you may choose to read into memory as a single string¶
In [77]:
with open('test_file.txt', 'r') as f:
text = f.read()
text
Out[77]:
'This old man\nHe played one\nHe played knick-knack on my thumb'
Or as a list of lines¶
In [78]:
with open('test_file.txt', 'r') as f:
text = f.readlines()
text
Out[78]:
['This old man\n', 'He played one\n', 'He played knick-knack on my thumb']
Appending to text files¶
In [79]:
with open('test_file.txt', 'a') as f:
f.write('\nThis old man\n')
f.write('He played two\n')
f.write('He played knick-knack on my shoe\n')
In [80]:
! cat test_file.txt
This old man
He played one
He played knick-knack on my thumb
This old man
He played two
He played knick-knack on my shoe
Writing to text files¶
In [81]:
with open('test_file.txt', 'w') as f:
f.write('This old man\n')
f.write('He played three\n')
f.write('He played knick-knack on my knee\n')
In [82]:
! cat test_file.txt
This old man
He played three
He played knick-knack on my knee
Errors and exceptions¶
Examples of common errors and exceptions¶
In [83]:
prnt(123)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-83-40e9627afc71> in <module>()
----> 1 prnt(123)
NameError: name 'prnt' is not defined
In [84]:
for (i in 1:5) {
print(i)
}
File "<ipython-input-84-137ebde5c214>", line 1
for (i in 1:5) {
^
SyntaxError: invalid syntax
In [85]:
for i in [1,23]:
print(i)
File "<ipython-input-85-831c2af95670>", line 2
print(i)
^
IndentationError: expected an indented block
In [86]:
x = 1
if x ==1:
print(2)
else:
print(3)
File "<ipython-input-86-8f7c872dc949>", line 4
else:
^
SyntaxError: invalid syntax
In [87]:
xs = [1,2,3]
xs[3]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-87-cd06bc19b999> in <module>()
1 xs = [1,2,3]
----> 2 xs[3]
IndexError: list index out of range
In [88]:
d = {'a': 1, 'b': 2}
d['c']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-88-c9ac53e894ce> in <module>()
1 d = {'a': 1, 'b': 2}
----> 2 d['c']
KeyError: 'c'
In [89]:
1/0
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-89-05c9758a9c21> in <module>()
----> 1 1/0
ZeroDivisionError: division by zero
In [90]:
with open('foobar.txt', 'r'):
for line in f:
print(line)
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-90-8fccf0e2e539> in <module>()
----> 1 with open('foobar.txt', 'r'):
2 for line in f:
3 print(line)
FileNotFoundError: [Errno 2] No such file or directory: 'foobar.txt'
try-except-finally¶
In [91]:
n = 0
try:
x = 1/n
except ZeroDivisionError as e:
print(e)
division by zero
Can catch different types of exceptions¶
In [92]:
try:
xs = [1,2,3]
xs[3]
except ZeroDivisionError as e:
print(e)
except IndexError as e:
print(e)
except KeyError as e:
print(e)
list index out of range
The finally clause is normally used for resource clean-up¶
Code in finally block will be executed regardless of whetehr an
exception occurred.
In [93]:
try:
f = open('foobar.txt', 'w')
f.write(str(1/0))
except Exception as e:
print(e)
finally:
f.close()
division by zero
Clean-up¶
In [94]:
! rm foobar.txt test_file.txt