3. Introduction to Python

  • Notebook of this section (open in a separate tab)

  • Video of this section (31 minutes)

3.1. Overview

  • Variables are mainly integers, real numbers, Boolean variables, characters, lists, dictionaries, etc., each of which defines operations and comparison operators.

  • The elements of a list start from the zero th element.

  • A partial list can be extracted from a list in slice notation.

  • In for and if statements, processing blocks are distinguished by a colon and indentation. An error occurs if the indentation is not aligned in a block.

  • Functions and classes are defined in the same way, using a colon and indentation.

  • Classes allow variables to be used in multiple functions (class functions). This also makes it easier to avoid variable name collisions.

3.2. Python Basics

Version check

[ ]:
!python --version
Python 3.7.12

Arithmetic calculations

Arithmetic calculations are intuitive in Python: one instruction per line.

[ ]:
1 + 2
3
[ ]:
4 * 5
20
[ ]:
2 / 7
0.2857142857142857
[ ]:
3 ** 4 # 3 to the fourth power
81
[ ]:
3 ** 0.5 # 0.5 power of 3 = root 3
1.7320508075688772

Data types

Each variable in Python has a data type, which can be displayed using the type() function. Data types include integer (int), floating-point (float), and string (str).

[ ]:
type(10)
int
[ ]:
type(1.3)
float
[ ]:
type('hello')
str

list

Data type is list

[ ]:
a = [10, 31, 2.4,  6]
print(a)
type(a)
[10, 31, 2.4, 6]
list

length of lists

[ ]:
len(a)
4

Lists differ from vectors in the rules of operation.

[ ]:
[1, 2] + [3, 4]
[1, 2, 3, 4]
[ ]:
[1,'ABC'] * 3
[1, 'ABC', 1, 'ABC', 1, 'ABC']

The first element in the list is the zeroth.

[ ]:
print(a[0])
print(a[1])
print(a[2])
print(a[3])
10
31
2.4
6
[ ]:
print(a[-1])
6

To extract a partial list, the notation Slicing can be used. The first number is zero, the second is one, and so on.

[ ]:
a=[0,1,2,3,4,5]
print(a[:]) # from the first to the last, that is, a itself
print(a[1:3]) # from the first to the third "one before
print(a[2:]) # from the second to the last
[0, 1, 2, 3, 4, 5]
[1, 2]
[2, 3, 4, 5]

Dictionary

A dictionary is a set of keyed (labeled) values:

{key0: value0,key1: value1,... , key N-1: value N-1}

The data type is dict.

[ ]:
alice = {'height': 160, 'weight': 50}
alice
{'height': 160, 'weight': 50}
[ ]:
type(alice)
dict
[ ]:
alice['height']
160

Adds a new element to the dictionary.

[ ]:
alice['nationality'] = 'UK'
alice
{'height': 160, 'nationality': 'UK', 'weight': 50}

3.3. Control statements

If

If statements can be used for conditional branching.

if Condition: True
    If True, execute.
    If true, then execute.
else: Execute if False.
    Execute if False.
    Execute if False.

In Python, indentation must be aligned within the same block.

[ ]:
# Compare two numbers and return the larger one

a = 5
b = 3

if a > b:
    c = a
    print('a =', c ,'の方が大きい')
else:
    c = b
    print('b =', c ,'の方が大きい')

c
a = 5 の方が大きい
5

for

You can iterate using `for'' statements. `` for i in range(10): 「process」 ` the "process" is executed from`\ i=0\ ``toi=9`.

[ ]:
# Add 1 to 10

s = 0
for i in range(10):
    s += i+1

s
55

where += is the operation of adding the right-hand side to the original value.

It can also be written as follows.

[ ]:
# Add 1 to 10

s = 0
for i in range(1,11):
    s += i

s
55

Function

Define a new function using def.

def function name(argument):
    Calculation rule
    Calculation rule
    Calculation rule
    return Return value.

Example 1 (using if statement)

Function to output the maximum of three numbers.

[ ]:
def max3(a,b,c): # a, b, c are arguments
    x = a
    if b > x:
        x = b
    if c > x:
        x = c
    return x

[ ]:
m = max3(3,7,-2)
m
7
Example 2 (using for statement)

Function that returns \(1 + 2 + \cdots + n\) for a given number \(n\).

where += is the operation of adding the right-hand side to the original value.

[ ]:
def f(n):
    y = 0
    for i in range(n): #i from 0 to n-1
        y += i + 1
    return y
[ ]:
f(10)
55

3.4. Classes

Definition of Classes

Classes allow you to define your own data types and functions for those data types.

  • Class: A class has its own data type, class variables and methods.

  • Class variables: various variables that objects of a class have. In this course, they are sometimes called parameters for the sake of explanation.

  • Methods: functions for the class.

  • Instance: An object (variable) with the data type of the class.

Variables of objects of a class are called by instance.variable

Functions of a class are called by  instance.method() or class.method(instance).

[ ]:
class Person:
    def __init__(self, name): # Constructor
        self.name = name

    def hello(self, keisho):    # hello() method
        print('Hello '+ self.name +' ' + keisho + '!')

    def bye(self, keisho):    # bye() method
        print('Good bye '+ self.name +' ' + keisho + '!')

where

def __init__(self, name): # Constructor
      self.name = name

is the constructor, which is the default definition. `self `` is a temporary instance name used in the class definition.

Instance Creation

[ ]:
abc = Person('Sato')

Checking class variables

[ ]:
abc.name
'Sato'

Using a method: There are two ways to write it.

[ ]:
abc.hello('san')

# Same if written as follows
Person.hello(abc, 'san')
Hello Sato san!
Hello Sato san!
[ ]:
abc.bye('san')
Good bye Sato san!

As shown in this example, class functions can be used without specifying the class variable abc.name.