1 of 57

Python Basic

Soo Kyung Kim

Colleague of AI�Ewha Womans University�sookim@ewha.ac.krsookim@ainsteinresearch.com

2 of 57

Python Data structure:�String, List, Sets, Tuples, Dictionary

2

3 of 57

String Type

  • Recall that Python uses int and float types to represent numeric values.�
  • Python defines another type, string (str), to represent text values:
    • Text is a sequence of characters (letters, digits, and symbols).�
  • Python recognizes that a value is string if it is surrounded by ' ' or " ":
    • 'Data Science'
    • "Machine Learning"
  • Quiz: 19 vs. "19"?

3

4 of 57

List Type

  • Suppose we want to deal with the list of students in this course:
    • We have 29 students registered!
    • For each of them, we need to declare a variable (nightmare!)
      • student1 = ”Seun Kim"
      • student2 = ”Yeobin Paik"
      • student3 = ”Seoyeon Ye"
      • …�
  • Instead, we would like to declare a single variable, containing all of the students’ names.
    • students = ["Seun Kim", "Yeobin Paik", "Seoyeon Ye", … , ”Minsuh Joo"]

4

5 of 57

Lists

  • List is a type of object (i.e., class) that contains a set of ordered items:
    • [<expression1>, <expression2>, …, <expressionN>]
    • [] (empty list)�
  • Memory model

0

1

2

3

29

Seun Kim

Yeobin Paik

Seoyeon Ye

Minsuh Joo

5

6 of 57

Lists: Access and Assign

  • Suppose we have a list:
    • students = ["Seun Kim", "Yeobin Paik", "Seoyeon Ye", … , ”Minsuh Joo"]�
  • Access elements within the list:
    • students[0]”Seun Kim"
    • students[1]"Yeobin Paik"
    • students[-1]"Minsuh Joo"
  • An element within the list can be also assigned to another variable:
    • first_student = students[0]
    • print(first_student)”Seun Kim"

The first item from the back

6

7 of 57

Lists: Modifying Elements

  • Elements can be modified, just as variables:
    • students[1] = ”Soo Kim"

Soo Kim

0

1

2

3

29

Seun Kim

Yeobin Paik

Seoyeon Ye

Minsuh Joo

7

8 of 57

Lists: Type

  • Lists can contain any type of data, and do not necessarily homogeneous types.
    • jaesuk_info = ["MC", "1972.8.14", 178, 65]�������
  • Mixed types are error-prone, since we need to remember what is where.
    • It is recommended to hold single-type data in each list.

8

9 of 57

Slicing

  • a[i:j]: A list comprised of elements from index i to j-1 from the list a.
    • Remember! The start index is inclusive, but the end index is exclusive.
    • students = ["Seun Kim", "Yeobin Paik", "Seoyeon Ye",”Minsuh Joo”]

    • students[1:3] → ["Yeobin Paik", "Seoyeon Ye"]
    • students[2:] → ["Seoyeon Ye",”Minsuh Joo”]
    • students[:2] → ["Seun Kim", "Yeobin Paik”]
    • students[:]["Seun Kim", "Yeobin Paik", "Seoyeon Ye",”Minsuh Joo”]

9

10 of 57

Copy vs. Alias

  • Copy: creates another list with the same elements.
    • students_copy = students[:]
    • Modifying students_copy does NOT impact the original students.�
  • Alias: another name referring to the same list.
    • students_alias = students
    • Modifying students_alias DOES impact students.

del students_copy[-1]?

students is not affected!

del students_alias[-1]?

students is affected!

10

11 of 57

Parameters are Aliases!

  • Since function parameters are variables, list parameters cause aliasing.
    • def remove_last_item(L: list) -> list:� if len(L) > 0:� del L[-1]� else:� print("The list is empty.")��remove_last_item(students)�
    • This function does not have return, but students is changed since the list L in the function is an alias of students.

11

12 of 57

Sets

  • Differently from Lists, Sets store unordered and distinct items.
  • Like Lists, Sets are mutable and can be used as function arguments.
  • Just as int, float, str, bool, and List, Set is also a class that has its own methods.�
  • Declare a set using { }
    • vowels = {"a", "e", "i", "o", "u", "a", "u", "i", "e"}
    • vowels{'a', 'u', 'e', 'o', 'i'}
      • No particular order (different from that we typed)
      • No duplicate items�
  • Check if duplicates are ignored
    • {"a", "e", "i", "o", "u", "a", "u", "i"} == {'a', 'u', 'e', 'o', 'i'}

True

12

13 of 57

Sets

  • An empty set
    • a = set()
    • Be careful! This is different from {} (which is an empty Dictionary).�
  • We can change a list to a set by
    • set([2, 3, 2, 5, 5, 5]){2, 3, 5}�
  • We can iterate over a set by
    • students = set(["Seun Kim", "Yeobin Paik", "Seoyeon Ye”])
    • for student in students:� print(student)

13

14 of 57

Tuples

  • Like Lists, Tuples have ordered items.
  • Unlike Lists (and like Strings), Tuples are immutable.�
  • Declare a tuple using ():
    • nums = ()
    • nums = (8,)
    • nums = (5+3,)�
  • Loop over a tuple:
    • nums = (1, 2, 3, 4)
    • for num in nums:� print(num)

to differentiate from arithmetic operations

14

15 of 57

Tuples

  • Tuples cannot be mutated:
    • family = ("dad", "mom", "me", "brother")
    • family[0] = "grand father"
  • Objects inside a tuple can be mutated:
    • family = (["dad", 54], ["mom", 48], ["me", 20], ["brother", 19])
    • family[0][1] = 55
    • family (["dad", 55], ["mom", 48], ["me", 20], ["brother", 19])

15

16 of 57

Dictionaries

  • Dictionaries have ordered mutable items without duplicates.�
  • Unlike those in sets, items in dictionaries are key/value pairs:
    • A key is like index in Lists.�
  • Declare using {}:
    • dict_empty = {}
    • dict_grades = {"Jihye": "A+", "Sunghyun": "A+", "jose": "A0"}�
  • Access using keys
    • dict_grades["Jihye"]"A+"

16

17 of 57

Dictionaries

  • Updating and checking membership of Dictionaries:
    • dict_grades = {}
    • dict_grades["Sora"] = "A" (adding a new key/value pair)
    • dict_grades["Sora"] = "B" (modifying an existing pair)
    • "Sora" in dict_gradesTrue (this is fast like sets)
    • del dict_grades["Sora"] (this is fast like sets)�
  • In some sense, a Set is like a Dictionary without values.

17

18 of 57

Dictionaries

  • Looping over dictionaries:���
    • The loop variable is assigned each key from the dictionary.�
  • Example
    • for student in dict_grades:� print(student, "got grade", dict_grades[student])

for <variable> in <dictionary>:

<block>

Jihye got grade A+

Sunghyun got grade A+

Jose got grade A0

Sora got grade B

18

19 of 57

Python Function

19

20 of 57

Defining Your Own Functions

  • General rule:
    • Iindented before the function body

  • <parameters> are variables.
    • Can be more than one.
    • Ex) ���
  • Most functions have a return statement at the end of the function body:
    • return <expression>
    • It evaluates the <expression>, produces a value, which is the result of the function call.

def <function_name>(<parameters>):

<function_body>

def sum(a, b):

return a + b

20

21 of 57

Local Variables

  • Local variables: Variables created within a function.
    • Used to temporarily store intermediate results.
    • Parameters are also local variables.
    • There are erased when the function returns (cannot be used outside of the function)�
  • Implement convert_to_fahrenheit :

def convert_to_fahrenheit(celsius):

a = 9 / 5

b = 32

return celsius * a + b

21

22 of 57

Namespace

  • When Python executes a function call, it creates a namespace in which to store local variables for that call.�
  • If a variable name in the namespace is same as a variable in another namespace, Python just considers the current namespace!

22

23 of 57

Memory Models for Functions

23

24 of 57

Memory Models for Functions

So… what happens when you call a function?

24

25 of 57

Terminology & Overview

  • Function call overview:
    • Step 1: Evaluate the arguments left to right.
    • Step 2: Create a namespace to hold the function call’s local variables, including the parameters.
    • Step 3: Pass the resulting argument values into the function by assigning them to the parameters.
    • Step 4: Execute the function body. When a return statement is executed, the function terminates and the value of the expression in the return statement is used as the value of the function call.

def convert_to_fahrenheit(celsius):

a = 9 / 5

b = 32

return celsius * a + b

convert_to_fahrenheit(36.5)

argument (values)

local variables

parameters

25

26 of 57

Memory Model Example

  • Example:

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

frames for namespaces

memory objects

26

27 of 57

Memory Model Example

  • Example:

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

27

28 of 57

Memory Model Example

  • Example:

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

28

29 of 57

Memory Model Example

  • Example:

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

29

30 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

10

30

31 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.
    • Creating a namespace for doubling.

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

10

doubling

31

32 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.
    • Creating a namespace for doubling.
    • Assigning the argument value to the function parameter.

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

10

doubling

x

32

33 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.
    • Creating a namespace for doubling.
    • Get the value to return (20).

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

10

doubling

x

20

33

34 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.
    • Creating a namespace for doubling.
    • Get the value to return (20).
    • Actually return the value back to where it was called.

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

10

doubling

x

20

return

34

35 of 57

Memory Model Example

  • Example:
  • Function call
    • Evaluate argument and get a value (10), using x in the global namespace.
    • Creating a namespace for doubling.
    • Get the value to return (20).
    • Actually return the value back to where it was called.
    • Terminate the function and assign the result to x.

frames

def doubling(x):

return 2*x

x = 5

x = doubling(x+5)

objects

global

func doubling()

doubling()

5

x

20

35

36 of 57

Function Design

36

37 of 57

Guidelines for Designing New Functions

  • Recall what coding is:
    • Coding is writing in programming language, to communicate with a computer.�
  • Just as writing a good essay/paper requires planning,
    • Topic, background material, outline, body, …
  • you must have a plan (an algorithm) in advance!�
  • Writing a good function does need a plan!

37

38 of 57

Guidelines for Designing New Functions

  • Whenever writing a new function, you need to answer the following questions:
    • Name: What is the name of your new function?
    • Parameters: What are the parameters, and what types of information do they refer to?
    • Body: What calculations will this function perform?
    • Return: What information does the function produce (output)?
    • Test: Does it work as intended? How can you ensure it?
  • Remember!
    • A good program code should be readable not just by a machine (executable without an error), but also by a human programmer (easy to follow).
    • Function name should be self-explanatory.

38

39 of 57

Function Design Example

  • Example: write a function to calculate difference between two days.
    • Step 1: Determine the function name, considering what it does.
      • days_difference�
    • Step 2: Determine the parameters and return value.
      • Parameters: day1 (int), day2 (int)
      • Return value: difference between the two days�
    • Step 3: Write the function header.
      • def days_difference(day1: int, day2: int) -> int:

optional, but useful for readability

39

40 of 57

Function Design Example (cont’d)

  • Example: write a function to calculate difference between two days.
    • Step 4: Write a short description
      • # Return the number of days between day1 and day2, which are both in the range 1-365 (thus indicating the day of the year)
      • This is a very important step, both for you and your co-workers!�
    • Step 5: Write the function body.
      • return abs(day2 - day1)�
    • Step 6: Make some test cases with your expectation and run them:
      • days_difference(200, 224)24
      • days_difference(27, 27)0
      • days_difference(30, 18)12

In Python, characters after # in the same line are ignored by the interpreter.

40

41 of 57

Function Design Example (cont’d)

  • Example: write a function to calculate difference between two days.
    • The complete function:

def days_difference(day1: int, day2: int) -> int:

# Return the number of days between day1 and day2, which are both in the range 1-365 (thus indicating the day of the year)

return abs(day2 - day1)

41

42 of 57

Using Modules

42

43 of 57

Modules

  • A module is a package of (reusable) variables and functions, grouped together in a single file.�
  • Once you import a module, you can use all the functions and variables in it.
    • import math

43

44 of 57

Module: What Happens when Importing?

  • import math
    • Creates a variable called math that refers to the math module object.

44

45 of 57

Module: What Happens when Importing?

  • import math as my_math
    • Creates a variable called my_math that refers to the math module object.

my_math

45

46 of 57

Module: Warning

  • You can even change the value of a module’s variable, but DON’t DO THIS!
    • math.pi = -17482�
  • Likewise, DON’t MANIPULATE a built-in function name! (e.g., max = min)�
  • Python does not allow programmers to “freeze” values, which is a significant flaw.
    • Other programming languages like C provides constants as well as variables and do not allow the constants to be changed.

46

47 of 57

Module: Importing Specific Things

  • It is inconvenient to always type math to use something in the module math.�
  • We can import specific functions and variables into the current namespace:
    • from math import sqrt, pi
      • Now we don’t have math but sqrt and pi directly in the current namespace.
      • Don’t have to and cannot use math anymore.
    • sqrt(9)3.0

47

48 of 57

Module: Importing Specific Things

  • Importing a single function does not save memory compared to importing an entire module.
    • All things in the math module are loaded on memory anyway.
    • The difference is how the module is mapped to names in the global namespace.
    • https://www.youtube.com/watch?v=vhzdwoJangI
  • Therefore, importing specific things really for the ease of typing.

48

49 of 57

Module: Importing Specific Things

  • What if you do “from math import *”?
    • You can import all the functions and variables from the math module and use them directly.
    • You can save some typing. Great!
    • We don’t need to type (math.).�
  • However, this is NOT a good idea!
    • Python library contains several hundreds of modules.
    • Multiple modules might have functions or variables having same name.

49

50 of 57

Module: Importing Specific Things

  • What’s wrong with this?
    • from Korean import say_hi (안녕하세요)
    • from English import say_hi (Hello)�
  • The function say_hi in Korean module is just gone, replaced by that in English module.
    • say_hi()Hello�
  • It is NOT wise to take this risk by doing
    • from Korean import *
    • from English import *

50

51 of 57

Writing a Module

51

52 of 57

Making Your Own Module

  • Open a new text file and make the file name temperature.py.�
  • Write some variables and functions in the file.��������
  • Save the file.

a = 5.0

b = 9.0

c = 32.0

def convert_to_celsius(fahrenheit: float) -> float:

return (fahrenheit - c) * a / b

def convert_to_fahrenheit(celsius: float) -> float:

return (celsius * b) / a + c

52

53 of 57

Making Your Own Module

  • Now you have the temperature module.
    • import temperature would work in the same directory.
    • Play with variables and functions in another module!�
  • Good and convenient to group related variables and functions in a module!

53

54 of 57

Classes

54

55 of 57

Class

  • Class is a customized data type to represent a same kind of objects.
    • Intuitie examples: Car, Person, Course, …�
  • A more general class includes arbitrary number of
    • Attributes: variables used to specify properties of individual objects in the class.
    • Methods: functions that belong to the object, performing some actions to it, like reading or editing its attributes.

Class Person

Attributes: age, gender, name, address, nationality

Methods: change_name(), move(), immigrate_to()

55

56 of 57

Class Object

  • Class vs. Class object
    • A class is a blueprint, definition of its attributes and methods (but not real yet).
    • A class object is an instance of the class (realization of a blueprint).
    • Example: TESLA model Y
      • TESLA designs model Y’s blueprint and produces numerous model Y objects according to it.
      • We can buy a model Y object but not the model Y blueprint.
      • The model Y blueprint has an attribute ‘color.’
      • My model Y object’s color attribute is white.
      • Your model Y object’s color attribute is red.
      • I can perform some actions (methods) on my model Y, like
        • change_oil(), change_tire(), sell(), …
      • I can drive my model Y object without knowing its blueprint.

56

57 of 57

Built-in Classes

  • In fact, all built-in types we’ve seen so far are also classes.
    • int class, float class, str class, bool class
    • You can see their definitions by typing, for example, help(int).�
  • We can create objects of these built-in classes and easily use their methods and attributes, without worrying about how they are implemented. (abstraction)�
  • Example: str class
    • name = ”Sookyung Kim"
    • name.lower()”sookyung kim"
    • name.upper()”SOOKYUNG KIM"
    • name.find("s")1 (location where "s" appears for the first time in ”Sookyung Kim")
    • name.count("o")2 (number of "o" in ”Sookyung Kim")

57