Python Tutorial
Introduction:
Getting started
This page can be downloaded as interactive jupyter notebook
An additional quiz about the contents of this tutorial, can be downloaded here
What is Python?
Python is an easy to learn and powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms. You can download the latest version of Python here.
What is jupyter notebook?
The jupyter notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. You can install jupyter via the anaconda Navigator. Anaconda Navigator is a desktop application that allows you to launch the related applications (e.g. the jupyter notebook server). Anaconda is open source and you can download it here.
Jupyter notebook interface and tools
When you launch jupyter notebook for the first time it looks similar to the figure below. On the left side (black rectangle) you can navigate threw directories. You can create new Checkpoint by clicking on a button which is marked with the red rectangle. Then you can start to write your code. To learn more on jupyter you can check this tutorial.
Checkpoint interface and tools are described here.
-
In the green box you have the main tools used for saving, making copies, to download the code in different formats and some other tools that we will be explained during this training.
-
In the purple box you have access to some useful tools which are used to save code, add cells, cut cells, copy cells and move them.
-
In the red box you have tools that you can use run, stop or continue code execution in the notebook.
-
In the blue box you can choose the cell type as code or markdown
-
In the pink box is the first, blank (code) cell. It is marked as highlighted by the blue bar to the left.
First code in Python
Now that we have the jupyter notebook running, we can start to write our first Python code. Type the following in the code cell below:
print("Hello world")
Run the code by selecting the code cell (e.g. by clicking on it) and pressing either the ‘Run’ button or using the key combination [CTRL]-[ENTER].
# your code goes here
We just used the built-in function print()
, to print out a string to the string. String is the value that we type inside the “ “. Now try to print out your name by running a modified version of the code above.
# your code goes here
Keywords and Identifier
An identifier is the name given to entities in Python like variables, function, class etc. Keywords are the reserved words in Python. We cannot use a keyword as variable name or function name or any other identifier, since they are used to define the syntax and structure of the Python language.
Keywords in Python | ||||
---|---|---|---|---|
False | class | finally | is | return |
None | continue | for | lambda | try |
True | def | from | nonlocal | while |
and | del | global | not | with |
as | elif | if | or | yield |
assert | else | import | pass | break |
except | in | raise |
Rules for naming identifiers:
- Keywords cannot be used as identifier
- Identifier can have any length
- Identifiers can consist of uppercase or lowercase letters as well as digits and the underscore
- You cannot use special symbols like
!, @, # %
etc, to define identifiers - Python is case-sensitive programming language. This means variables
GUG
andgug
are not the same
Exercise: define two variables via: V1 = "upercase defined"
and v1 = "lowercase defined"
and print both of them.
# your code goes here
Statement
A statement is an instruction that can be executed by the Python interpreter. For example print("Hello world")
.
Multi-line statement: In Python the end of a statement is usually defined by a newline character. Nevertheless, line continuation is implied inside ()
, []
and {}
. For example we can write a statement in this way,
a = (1 + 2 + 3 +
4 + 5 + 6 +
7 + 8 + 9)
or we can use continuation character \
,
a = 1 + 2 + 3 + \
4 + 5 + 6 + \
7 + 8 + 9
Python indentation
Any programming language use syntax to define a block of codes, for example c and c++ use {}
. Python uses indentation. It means a code block starts with indentation and ends with the first unindented line. Generally you can use four space or tab for indentation. Here is an example:
for i in range(0, 25):
if i <= 10:
print("less than 10)
if i > 10:
print("bigger than 10)
Comments and statements
When you want to describe your code you can write comments. Comments are very important, e.g. to help the next reader of your code understanding it. Comments are not executed and have no effect to the actual code. In Python comments start with the hash symbol #
. You can write several lines of comments by using #
at the beginning of each line. Here is an example of commented code. You can run it and see the result.
# This is my first code in python
A = [10, 20, 30, 40] # <- Initializing a list
a_sum = 0 # <- Initializing a counter variable with zero
# Sum all cells in variable A
for i in range(0,4):
a_sum = a_sum + A[i]
print("The result is:", a_sum) # Print the result
Docstring
In python you can use docstring for documentation a string. It is a string that occurs as the frst statement in a class, function or method definition. In codstring we must write what a function does. Here is an example.
def sum(x,y):
"""Function to compute the sum of two variables"""
return x + y
Variables
In most programming languages (also Python) any variable points to a location of your computer memory that is used to store the corresponding data. Therefore, each variable must have a unique name that identifies the variable and thus the address in memory. The name of a variable is called identifier.
Note: Variables do not need declaration to reserve memory space, it happens automatically.
Assigning value to a Variable:
Values are assigning to variables by using the assignment operator =
.
Exercise: Define a variable hello
, assign the value "Hello World"
to it and print it.
# your code goes here
After you run the program, the output should be:
Hello World
Note: Python is a type inferred language, it means Python can infer the type of "Hello World"
as a string and declare the variable as a string.
Now we want to change the value of a variable. For this purpose, we need to assign a new value to the variable. Then, the new value will replace the old value. For confirmation, do next exercise and print the variable.
Exercise: Change value of the variable hello
by assigning the value of "Hello Leibniz"
, then print it.
# your code goes here
In Python we have different ways to assign values to variables. You can see some of them in the examples below. Run these examples to see the results.
- First example is assigning multiple values to multiple variables (using tuples) in one statement
- Second is assigning same value to multiple variables
- Third is assigning value of a variable to another variable
# Example 1
a, b, c = 88, "icaml.org", 3.96
print(a)
print(b)
print(c)
# Example 2
x = y = z = "same value"
print(x)
print(y)
print(z)
# Example 3
p = 2018
q = p
r = q
print(p)
print(q)
print(r)
Constants
A constant is a type of variable that value cannot be changed. It is useful when you want to hold information which cannot be changed later like containers. In Python, constants usually define and assign on a module. You will learn how to create module and how to assign it to your program. Constants are written in all capital letters and using underscores for separating words. e.g. PI = 3.1415
Example: Declaring and assigning value to a constant
- Create a
constants.py
C = 299792458
GRAVITY = 9.8
You can run the next cell and see the result.
import constants
print(constants.C)
print(constants.GRAVITY)
Numbers
Python numbers includes integers, floating point numbers and complex numbers. The corresponding keywords are int
, float
and complex
. An integer number in Python can have an arbitrary length. A floating number is accurate up to 15 decimal places. A complex number is defined in the form a + bj
, where a is the real part and b is the imaginary part of the number. If you want to know class of a variable or to check an object belongs to a class, you can use these functions.
type(x)
get class of a variable x
isinstance(x, int)
check class of an object (here is checked, whether x
is an integer)
Exercise: Define some variables (int and complex) and try to check their class
# your code goes here
Lists
The list is a very flexible built-in data type in Python. We can put different types of items to a list. Lists are defined in this form:
>>> My_list = [4, 8.23, 'Jupyter Notebook']
For calling any items of a list you can use slicing operator []
. In Python the index counting starts from 0 (first item).
Exercise: Create a list and try to print items individually. After running your code, you will see some code that say your code is correct or not.
# your code goes here
My_list =
# Check part (Please do not change this part)
import Check
Check.check_datatype(My_list)
Tuple
Tuple is a class which is very similar to the class list. The major difference is that tuples are immutable, meaning that we cannot modify a tuple once it is initialized. Tuples cannot change dynamically and are thus used to define and save protected data. A tuple is defined using ()
and it’s items are separated by ,
. For slicing tuple item we can again use []
.
Example: >>> My_tuple = (2018, 'Leibniz', 5+3j)
Exercise: Create a tuple which contains the numbers 1 to 5, then sum tuple’s items by slicing them and save it in Sum
variable.
# your code goes here
first_tuple =
Sum =
# Check part (Please do not change this part)
import Check
Check.check_sum(first_tuple,Sum)
Note: A tuple can be a item in a list, it means a list can contain some tuple.
Example: Check the code below and run it to see result.
l = [(1,2,3),(4,5,6),(7,8,9)]
print(l[1])
print(l[0][1])
String
String is sequence of Unicode characters. In Python, strings are represented by using ' '
or " "
. We can use []
for slicing strings like list and tuple.
Example: Run this code and see the result.
my_string = 'Geodesy and Geoinformatics'
print(my_string[2])
print(my_string[0:7])
print(my_string[12:26])
Set
Set is an unordered collection of items. We can use {}
to create a set and separate items by ,
. In a set indexing and slicing is not possible since it has no meaning (because sets are unordered by definition). It is possible to create a set by unifying two sets or computing the intersection of two sets.
Example: Run this code and see the result.
a= {1,2,3,5,5,5,1,1}
print(a)
Dictionary
Dictionary is a unordered set of key-value pairs. We can define keys for value and by using the key, we can retrieve the value.
Example: Run this code and see the result.
dic = {'key':2019 , 5:'Happy new year'}
print(type(dic))
print(dic['key'])
print(dic[5])
Conversion between data types
We can use different conversion like int()
, float()
, str()
to convert between data types. Conversion between data types has some rules:
- Conversion between float to int will make the value closer to zero.
- Conversion from and to a string must contain compatible values.
- To convert to a dictionary, each item must contain a pair
Example: Run the following cells and see the result.
# convert between int and float
a = 3
b = float(a)
c = 53.69
print('a=',a)
print('b=',b)
print('integer value of c =', int(c))
# convert to a set, tuple and dict
x = [1,2,3]
y = {9,8,7}
z = [[8,'Hello'],[3,'World']]
print('x in type set:',set(x))
print('y in type tuple:', tuple(y))
print('z in type dict:', dict(z))
Output
print()
print()
is a function that is used to output data to the screen. The actual syntax of the print()
function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
object
is the value to be printedsep
is separator is used between values(It is a space in default)end
it is printed after values and defaults into a next line.The file
is the object where the values are printed. (It issys.stdout
in default)
Output formating
There is some formats that we can use them to make our output more understandable. In case of string object, it is possible to use str.format()
method. And it is possible to use keyword to format a string. Also we can use %
function to take output.
Example: Run this code and see the result.
a = 20.654987
b = 30
print('The value of a is {} and b is {}'.format(a,b))
print('Hello {name}, {greeting}'.format(greeting = 'Happy new year', name = 'Sara'))
print('The value of a is %3.2f' %a)
Input
Up to now, we defined the value of all variables. Our all code were in static mode. Sometime we want to take value from the user and make more flexibility in our program. In this case we can use input()
function to do that. The syntax for input()
is:
input([prompt])
prompt
is the string that we want to display it.(It is optional)
Example: Run this code and see the result.
input_number = input('Please enter a number: ')
print('Your input number is: ', input_number)
print('data type of input is:' ,type(input_number))
# Changing the input data type
print('Your input number in integer type is: ', int(float(input_number)))
Import
Python modules is a file that contains Python functions, definitions and statement in .py
format. We can use import
keyword to import a module to another module. Python has several useful module like math
, calendar
, random
etc. But we can create any module that we need to use them in our program. It is possible to break a program to different modules, and it is very useful when our program grows very big.
Example: Run this code and see the result.
from math import pi
print(pi)
Operators
In Python operators are symbols that implement mathematical computation.
For example in ` 1+2 the
+ is the operator that executes the addition.
1 and
2` are the operands.
Arithmetic operators are used to perform mathematical operations like addition, subtraction etc. Some of the mathematical operators are listed below.
Operator | Meaning | Example |
---|---|---|
+ | Add two or more operands | a+b+4 |
- | Subtract right operand from the left one | 10-a-b |
* | Multiply two operands | a*b |
/ | Devide left operand than right one | b/a |
% | Modulus, compute remainder of the division | b%a |
// | Floor division | b//a |
** | Exponent, left operand with power of of right operand | a**b |
Example: Run this code and see the result of the arithmetic operators.
a = 10
b = 3
# Result: a + b = 13
print('a + b =',a+b)
# Result: a - b = 7
print('a - b =',a-b)
# Result: a * b = 30
print('a * b =',a*b)
# Result: a / b = 3.3333...
print('a / b =',a/b)
# Result: a // b = 3
print('a // b =',a//b)
# Result: a % b = 1
print('a % b =',a%b)
# Result: a ** b = 1000
print('a ** b =',a**b)
Comparison operators
We use these operators to compare values. The result of this comparison would be True
or False
according to the condition. You can see a list of comparison operators in the table below.
Operator | Meaning | Example |
---|---|---|
> | True, if left one is greater than the right one | a > b |
< | True, if left one is less than the right one | a < b |
== | True, if left one is equal with the right one | a == b |
!= | True, if left one is not equal with the right one | a != b |
<= | True, if left one is less than or equal with the right one | a <= b |
>= | True, if left one is greater than or equal with the right one | a >= b |
Example: Run this code and see the result of comparison operators.
a = 5
b = 18
c = 5
# Result: a > c is False
print('a > c is',a>c)
# Result: a < b is True
print('a < b is',a<b)
# Result: a == c is True
print('a == c is',a==c)
# Result: b != c is True
print('b != c is',b!=c)
# Result: a >= c is True
print('a >= c is',a>=c)
# Result: b <= a is False
print('b <= a is',b<=a)
Logical operators
In Python we have three logical operators. and
, or
, not
You can see the operation of them below:
Operator | Meaning | Example |
---|---|---|
and | True, if both operands are true | a and b |
or | True, if one of the operands is true | a or b |
not | True, if the operand is false | not a |
Example: Run this code and see the result of logical operators.
result1 = True
result2 = False
# result1 and result1 is False
print('result1 and result2 is', result1 and result2)
# result1 or result2 is True
print('result1 or result2 is', result1 or result2)
# not result1 is False
print('not result1 is', not result1)
result1 and result2 is False
result1 or result2 is True
not result1 is False
Bitwise operators
When our variables are string of binary digits, we can use bitwise operators to act on them. Bitwise operate bit by bit. You can see the bitwise operators and operation of them in table below.
a
= 10(0000 1010
in binary)
b
= 4(0000 0100
in binary)
Operator | Meaning | Example |
---|---|---|
& | Bitwise AND | a&b = 0(0000 0000) |
| | Bitwise OR | a|b= 14(0000 1110) |
~ | Bitwise NOT | ~a = -11(1111 0101) |
^ | Bitwise XOR | a^b= 14(0000 1110) |
>> | Bitwise right shift | a >> 2 = 2(0000 0010) |
<< | Bitwise left shift | a << 2 = 40(0010 1000) |
Assignment operators
In Python, we use these operators to assign values to variables. You can see assignment operators that are used in Python in table below.
Operator | Example | Same as |
---|---|---|
= | x = 3 | x = 3 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
//= | x //= 3 | x = x // 3 |
**= | x **= 3 | x = x**3 |
&= | x &= 3 | x = x & 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Special operators
Python offers some special operators that sometimes are realy usefull. We describe two of them below.
Identity operators: identity operators are is
and is not
. You can see the table below and run the example after that to understand operation of these operators.
Operator | Meaning | Example |
---|---|---|
is | True, if the operands are identical | x is True |
is not | True, if the operands are not identical | x is not True |
Example: Run this code and see the result of identical operators.
a = 8
b = 8
c = 'ICAML'
d = 'ICAML'
e = [10,20,30]
f = [10,20,30]
# Result: False
print(a is not b)
# Result: True
print(c is d)
# Result: False
print(e is f)
Membership operators: membership operators are in
and not in
. They are used in variables like string
, list
, tuple
and dictionary
to test whether a value or variable(in dictionary for presence of key) is found in a sequence or not.
Operator | Meaning | Example |
---|---|---|
in | True, if value/variable is found in the sequence | 3 in A |
not in | True, if value/variable is not found in the sequence | 4 not in A |
Example:
a = 'Hello ICAML'
b = {1:'x',2:'y'}
# Output: True
print('I' in a)
# Output: True
print('hello' not in a)
# Output: True
print(1 in b)
# Output: False
print('y' in b)
Name
Name or identifier is a name given to object. Name is a way to access to an object. And we know everything is in Python an object. For example, when we assign a value to a variable like x = 5
, here 5
is an object stored in memory and x
is the name we associate it with. We can get the address of an object by using the built-in function, id()
.
Example: Let’s Run this code and check it works and give the object address in RAM.
# Note: You may get different value of id
# variable name: vn
# value : 6
vn = 6
# Result: id(2)= 1595960496
print('id(6) =', id(6))
# Result: id(a) = 1595960496
print('id(vn) =', id(vn))
Exercise: In previous example both refer to the same object. In this exercise we try to make things more interesting.
- Create variable
x
and assign value9
in it - Get address(
id()
) ofx
. - Change value of
x
by additionx = x + 1
- Get again address(
id()
) ofx
. - Get address(
id()
) of10
. - Create variable
y
and assign value9
in it - Get address(
id()
) of9
.
# your code goes here
Note: What is happend in the above code? Initially, an object 9
is created and the name x
is associated with it, when you do x = x+1
, a new object 10
is created and then x
associated with new object. Furthermore, when you do y = 9
, the new name y
is associated with the object 9
.
Sequence of running and storing variables
In Jupyter Notebook we can any section individually or all sections together. Saving variables values happen in sequence of running sections. It means, when we run a section, the value of variables in that section store in memory. Anytime we change the value of a variable, we must run again the section to store new value in variable.
Exercise: Let’s modify these codes, then run them to check.
# Define variables a and b,then associate them to an integer(1) and a string('Hello') value
# Print variables a and b
# Define two other variables(c and d), then associate them to the values of a and b
# Print variables c and d
# Change value of variable a to `2`
# Change value of variable b to `Hi'
# Print variables a and b
# again take print variables c and d
# Run second code again
# Then print variables c and d
Namespace
In simple definition, we can say, namespace is a collection of names. In Python, a namespace like a mapping every name that we have defined, to corresponding objects. A namespace containing all the built-in names is created when start the Python interpreter and exists as long we we do not exit. This is the reason that some built-in function like id()
and print()
always are available for us. Each module
creates its own global namespace. These different namespaces are isolated. Any module
can have several function
and classes
. A local namespace is created when a function or class is called, which has all names defined in it.
Variable Scope
You have seen, there are various namespaces defined. We do not have access to all of them from any part of our program. The concept of scope is used here. Scope is a part of the program that shows from where we have access to a namespace without any prefix. There are three nested scopes.
- Scope of the current function which has local names
- Scope of the module which has global names
- Outemost scope which has built-in names
When we make a reference inside a function, the name is searched in the local namespace, then in the global namespace and finally in the built-in namespace. To clarify this important concept, let’s check next examples.
Author: | Mohsen Soleymanighezelgechi |
Last modified: | 03.05.2019 |