Introduction to Python Programming - Python Programming BasicKnowledge-based Data Discovery INHA KDD Lab. Young-Duk Seo mysid88@inha.ac.kr 2 What is Python? ▪ Python is currently a popular programing language - Created by Guido van Rossum who is a Dutch programmer, and released in 1991 - Interpreter (Interpreted language or Scripting language) » code can be executed as soon as it is written 3 Guido van Rossum (Source: Wiki) Features of Python ▪ Similar to the English language - if 4 in [1,2,3,4]: print("There is a 4") » If 4 is among [1, 2, 3, 4], the “There is a 4” is an output ▪ Easy to learn - because Python has a simple syntax ▪ An opensource SW ▪ Prototyping with Python can be very quick - “Life is too short, You need Python.” 4 Basic syntax of Python ▪ Python variable - String - Integer >>> a = "Python" >>> print(a) Python >>> a = 1 >>> b = 2 >>> a + b 3 >>> a = "Python" >>> a 'Python' 5 Basic syntax of Python ▪ Python conditions - if >>> a = 3 >>> if a > 1: ... print("a is greater than 1") ... a is greater than 1 ❖ The '...' in front of the print statement means that the statement is not finished yet ❖ This space always be indented using the Tab key or 4 spacebar keys 6 Image source: https://wikidocs.net/17684 Editors of Python (Python IDLE) ▪ Python IDLE (Integrated Development and Learning Environment) IDLE shell window 7 Image source: https://wikidocs.net/17684 Editors of Python ▪ ▪ Visual Studio Code - https://code.visualstudio.com PyCharm - http://www.jetbrains.com/pycharm/download 8 Downloading Python ▪ https://www.python.org/ 9 Installing Python (Windows) 10 Installing Python (Mac) 11 Installing PyCharm (Windows) ▪ https://www.jetbrains.com/ko-kr/pycharm/download/#section=windows ▪ Community version Download 12 Installing PyCharm (Mac) ▪ https://www.jetbrains.com/ko-kr/pycharm/download/#section=mac ▪ Community version Download 13 Environmental Setting (Windows) ▪ CS101 Library 다운 - https://github.com/cjnam/ice1003/archive/main.zip 14 Hubo library ▪ Writing an example code - Hubo basic example from cs1robots import * create_world() hubo = Robot() hubo.set_trace("blue") hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() hubo.move() hubo.turn_left() 15 THIS WEEK.. 16 Tentative Schedule Week1 Course Overview Week16 - Week2 Introduction to Python Programming Week15 Final Exam Week3 Python Programming Basics Week14 Summary Week4 Programming with Robots Week13 Text Processing Week5 Conditionals and If Statements Week12 String, Set, Dictionary and Image Processing Week6 While Loops vs For Loops Week11 Sequences: Lists, Strings, and Tuples Week7 Variables and Basic Data Types Week10 Local/Global Variables Week8 Midterm Exam Week9 Functions with Parameters and Return Values 17 Table of contents ▪ Data Types ▪ Conditional Statements ▪ Loop Statements ▪ Functions ▪ Input & Output ▪ File Handling 18 Python Data Types 19 Python Data Types ▪ Python has the following data types built-in by default - ▪ Text Type: Numeric Types: Sequence Types: Mapping Type: Set Types: Boolean Type: str int, float, complex list, tuple, range dict set, frozenset bool Getting the Data Type: type() >>> x = 5 >>> print(type(x)) <class ‘int’> 20 Numbers ▪ Int - Integer is a whole number, positive or negative, without decimals, of unlimited length >>> a = 123 >>> a = -178 >>> a = 0 ▪ Float - Floating point number is a number, positive or negative, containing one or more decimals >>> a = 1.2 >>> a = -3.45 - Float can also be scientific numbers with an "e" to indicate the power of 10 >>> a = 4.24E10 >>> a = 4.24e-10 21 Numbers – Arithmetic operators ▪ ▪ The four fundamental arithmetic operators - Addition, Subtraction, Multiplication, Division >>> a = 3 >>> b = 4 >>> a + b # Addition 7 >>> a - b # Subtraction -1 >>> a * b # Multiplication 12 >>> a / b # Division 0.75 The other operators - Exponentiation >>> a = 3 >>> b = 4 >>> a ** b 81 - Modulus >>> 7 % 3 1 >>> 3 % 7 3 - Floor division >>> 7 // 4 1 22 String ▪ Strings in python are surrounded by - either single quotation marks, or double quotation mark >>> print('Python') Python >>> print("Python") Python ▪ Multiline Strings - Using three single quotes, or three double quotes >>> multiline=''' >>> multiline=""" ... Life is too short ... Life is too short ... You need python ... You need python ... """ ... ''' 23 >>> print(multiline) Life is too short You need python String ▪ Including single or double quotation marks in a string - Single quotation mark >>> food = "Python's favorite food is perl" >>> food "Python's favorite food is perl" - Double quotation mark >>> say = '"Python is very easy." he says.' >>> say "Python is very easy." he says - Using backslash (\) >>> food = 'Python\'s favorite food is perl' >>> say = "\"Python is very easy.\" he says." 24 Lists ▪ Lists are used to store multiple items in a single variable - Lists are created using square brackets [ ] >>> odd = [1, 3, 5, 7, 9] - List items can be of any data type >>> a = [] # Empty list >>> b = [1, 2, 3] # Number >>> c = ['Life', 'is', 'too', 'short'] # String >>> d = [1, 2, 'Life', 'is'] # Number + String >>> e = [1, 2, ['Life', 'is']] # Number + List 25 Lists – Indexing ▪ List items are indexed - The first item has index [0], the second item has index [1] etc. >>> >>> [1, >>> 1 >>> 4 >>> 3 >>> a = [1, 2, 3, ['a', 'b', 'c']] >>> a[0] 1 >>> a[-1] ['a', 'b', 'c'] >>> a[3] ['a', 'b', 'c'] >>> a[-1][0] 'a' >>> a[-1][1] 'b' >>> a[-1][2] 'c' a = [1, 2, 3] a 2, 3] a[0] a[0] + a[2] a[-1] 26 Lists – Change and Delete ▪ Change list items - To change the value of a specific item, refer to the index number >>> a = [1, 2, 3] >>> a[2] = 4 >>> a [1, 2, 4] ▪ Delete list items - Using del keyword to remove the specified index >>> a = [1, 2, 3] >>> del a[1] >>> a [1, 3] 27 Tuple ▪ A tuple is almost same as a list, but two things are different - Tuples are written with round brackets () - Unchangeable: A tuple cannot change, add or remove their items >>> t1 = () >>> t2 = (1,) >>> t3 = (1, 2, 3) >>> t4 = 1, 2, 3 >>> t5 = ('a', 'b', ('ab', 'cd')) 28 Tuple ▪ What if we try to delete or change an item in a tuple? - When trying to delete an item in a tuple? >>> t1 = (1, 2, 'a', 'b’) >>> del t1[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object doesn't support item deletion - When trying to change an item in a tuple? >>> t1 = (1, 2, 'a', 'b’) >>> t1[0] = 'c' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'tuple' object does not support item assignment 29 Dictionary ▪ Dictionaries are used to store data values in “key:value” pairs - Dictionaries are written with curly brackets { }, and have keys and values - In key part, values are unchangeable, but values can be both changeable and unchangeable in value part >>> dic = { key value 'name':'pey', name pey 'phone':'0119993323’, phone 01199993323 'birth': '1118’ } birth 1118 >>> a = {1: 'hi'} >>> a = {'a': [1,2,3]} 30 Dictionary ▪ Add a key:value pair in a dictionary >>> >>> >>> {1: >>> >>> {1: >>> >>> {1: a = {1: 'a'} a[2] = 'b' # add a 2:‘b’ pair in the dictionary a a 'a', 2: 'b’} a['name'] = 'pey' # add a ‘name’:‘pey’ pair in the dictionary a a 'a', 2: 'b', 'name': 'pey’} a[3] = [1,2,3] # add a 3:[1,2,3] pair in the dictionary a a 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]} 31 Dictionary ▪ Dictionary items can be referred to by using the key name >>> grade = {'pey': 10, 'julliet': 99} >>> grade['pey'] 10 >>> grade['julliet'] 99 >>> dic = {'name':'pey', 'phone':'0119993323', 'birth': '1118'} >>> dic['name'] 'pey' >>> dic['phone'] '0119993323' >>> dic['birth'] '1118' 32 Set ▪ Sets are the datatype for handling sets in mathematics - Written with set keyword >>> s1 = set([1,2,3]) >>> s1 {1, 2, 3} - A set is a collection which is both unordered and unindexed. Also, it does not allow duplicate (often used as a filter to remove duplicate data) >>> s2 = set("Hello") >>> s2 {'e', 'H', 'l', 'o'} 33 Set – mathematics ▪ ▪ Union (U) - Using ‘|’ and union method >>> s1 | s2 {1, 2, 3, 4, 5, 6, 7, 8, 9} >>> s1.union(s2) {1, 2, 3, 4, 5, 6, 7, 8, 9} Intersection (∩) - Using ‘&’ and intersection method >>> s1 = set([1, 2, 3, 4, 5, 6]) >>> s2 = set([4, 5, 6, 7, 8, 9]) >>> s1 & s2 {4, 5, 6} >>> s1.intersection(s2) {4, 5, 6} ▪ Difference (–) - Using ‘–’ and difference method >>> s1 - s2 {1, 2, 3} >>> s2 - s1 {8, 9, 7} >>> s1.difference(s2) {1, 2, 3} >>> s2.difference(s1) {8, 9, 7} 34 Variables ▪ In Python, variables do not need to be declared with any particular data type - If you create variable, just using assignment (=) symbol >>> a = 1 >>> b = "python" >>> c = [1,2,3] ▪ Python variables are pointers >>> a = [1, 2, 3] >>> id(a) # the address of the list [1, 2, 3] 4303029896 - A list data type (i.e., object) with a value of [1, 2, 3] is automatically created in the memory - The variable a points the address of the memory where the list [1, 2, 3] is stored 35 Variable Names ▪ A variable can have a short name (e.g., x and y) or a more descriptive name (age, carname, total_volume) ▪ Rules for Python variables - Must start with a letter or the underscore character - Cannot start with a number - Can only contain alpha-numeric characters and underscores - Case-sensitive Legal variable name Illegal variable names myvar = "John" my_var = "John" _my_var = "John" myVar = "John" MYVAR = "John" myvar2 = "John" 2myvar = "John" my-var = "John" my var = "John" 36 Variable Names ▪ There are several techniques you can use to make them more readable - Camel case: Each word, except the first, starts with a capital letter myVariableName = "John" - Pascal case: Each word starts with a capital letter MyVariableName = "John" - Snake case: Each word is separated by an underscore character my_variable_name = "John" 37 Conditional Statements 38 if Statement ▪ Basic structure - An “if statement” is written by using if keyword if condition: statement 1 statement 2 ... >>> a = 33 >>> b = 200 >>> if b > a: ... print("b is greater than a") 39 if Statement ▪ Basic structure - It can also be used with else keyword if condition: >>> statement 1 >>> statement 2 >>> ... ... else: ... statement A ... statement B ... a = 33 b = 200 if b > a: print("b is greater than a") else: print(“b is not greater than a") 40 Indentation ▪ All statements belonging to the if statement must be indented - if statement without indentation will raise an error - Indentation should always be the same width money = True money = True if money: if money: print("Seo") print("Seo") print("Young") print("Young") print("Duk") print("Duk") 41 money = True if money: print("Seo") print("Young") print("Duk") Conditional Statement ▪ Conditional statement is a statement that judges true or false - Using the comparison operators, the logical operators, and the membership operators ▪ Comparison operators - Used to compare two values >>> money = 2000 >>> if money >= 3000: ... print("Take a taxi") ... else: ... print("Just walk") ... Just walk Operator Description Example < Less than x<y > Greater than x>y == Equal x == y != Not equal x != y >= Greater than or equal to x >= y <= Less than or equal to x <= y 42 Conditional Statement ▪ Logical operators - Used to combine conditional statements >>> money = 2000 >>> card = True >>> if money >= 3000 or card: ... print("Take a taxi") ... else: Operator ... print("Just walk") ... and Take a taxi Description Example Return True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, return False if the result is True not(x < 5 and x < 10) 43 Elif ▪ If the previous conditions were not true, then try this condition - That is, elif is executed when if condition: statement 1 statement 2 ... elif condition: statement 1 statement 2 ... else: statement 1 statement 2 ... the previous conditional statement is false >>> pocket = ['paper', 'cellphone’] >>> card = True >>> if 'money' in pocket: ... print("Take a taxi") ... elif card: ... print("Take a bus") ... else: ... print("Just walk") ... Take a bus 44 Loop Statements 45 Python Loops ▪ Python has two primitive loop commends - while loops >>> i = 1 >>> while i < 6: ... print(i) ... i += 1 - for loops >>> fruits = ['apple', 'banana', 'cherry'] >>> for x in fruits: ... print(x) 46 while loops ▪ Basic structure - Can execute a set of statements as long as a condition is true - The while loop requires relevant variables to be ready while condition: statement 1 statement 2 statement 3 ... 47 while loops ▪ Example - >>> treeHit = 0 >>> while treeHit < 10: ... treeHit = treeHit +1 ... print("Cut down a tree, %d time." % treeHit) ... if treeHit == 10: ... print("A tree falls.") ... treeHit condition statement while statement 0 0 < 10 True Cut down a tree, 1 time. Loop 1 1 < 10 True Cut down a tree, 2 time. Loop 2 2 < 10 True Cut down a tree, 3 time. Loop ... 8 8 < 10 True Cut down a tree, 9 time. Loop 9 9 < 10 True Cut down a tree, 10 time. A tree falls. Loop 10 10 < 10 False Complete 48 for loops ▪ Python for loops - Used for iterating over a sequence that is either a list, a tuple, a dictionary, a set, or a string - This is less like the for keyword in other programming languages ▪ Basic structure - Can execute a set of statements, once for each item in a list, tuple, set etc. for variable in list(or tuple, string): statement 1 statement 2 ... 49 for loops ▪ Example - >>> test_list = ['one', 'two', 'three’] >>> for i in test_list: ... print(i) ... one two three - >>> for x in "banana": ... print(x) ... 50 >>> a = [(1,2), (3,4), (5,6)] >>> for (first, last) in a: ... print(first + last) ... 3 7 11 for loops ▪ Advanced example - A total of 5 students took a test. If the test score is over 60, it’s a pass. Otherwise, it’s a fail. Show the results of a pass or fail of each student. - marks = [90, 25, 67, 45, 80] Student Student Student Student Student 1 2 3 4 5 passed failed passed failed passed number = 0 for mark in marks: number = number +1 if mark >= 60: print("Student %d passed the test." % number) else: print("Student %d failed the test." % number) 51 the the the the the test. test. test. test. test. range() function ▪ The range() function returns a sequence of numbers - Starting from 0 by default, and increments by 1 (by default), and ends at a specified number >>> a = range(10) >>> a range(0, 10) # a range object containing numbers from 0 to less than 10 - To specify the starting value by adding a parameter >>> a = range(1, 11) >>> a range(1, 11) # a range object containing numbers from 1 to less than 11 - To specify the increment value by adding a third parameter >>> a = range(2, 30, 3) >>> a range(2, 30, 3) # a range object containing numbers from 2 to less than 30 and increments by 3 52 range() function ▪ To loop through a set of code a specified number of times for a Python for loop - Mainly using range() function >>> for x in range(6): ... print(x) >>> add = 0 >>> for i in range(1, 11): ... add = add + i ... >>> print(add) >>> for x in range(2, 6): ... print(x) >>> for x in range(2, 30, 3): ... print(x) 53 Functions 54 Python Functions ▪ What is the functions? - A function is a block of code which only runs when it is called - You can pass data, known as parameters, into a function - A function can return data as a result ▪ Why we use the functions? - If you anticipate needing to repeat the same or very similar code more than once, it may be worth writing a reusable function - Can also help make your code more readable 55 Python Functions ▪ Basic Structure - In Python, a function is defined using the def keyword def name(parameters): statement1 statement2 ... - Example >>> def add(a, b): ... return a+b ... >>> >>> >>> >>> >>> 7 a = 3 b = 4 c = add(a, b) print(c) 56 Parameters & Arguments ▪ What is the difference between a parameter and an argument - A parameter – the variable listed inside the parentheses in the function definition - An argument – the value that is sent to the function when it is called def add(a, b): # a and b are parameters return a+b print(add(3, 4)) # 3 and 4 are arguments 57 Types of Functions in Python ▪ There are 4 types of function in Python - ▪ A function with argument and return value With no argument and with a return value With argument and no return value With no argument and no return value A function with argument and return value >>> def add(a, b): ... result = a + b ... return result ... >>> a = add(3, 4) >>> print(a) 7 - def name(parameters): statement ... return result 58 Types of Functions in Python ▪ A function with no argument and with a return value - def name(): statement ... return result ▪ >>> def say(): ... return 'Hi’ ... >>> a = say() >>> print(a) Hi A function with argument and no return value - def name(paramenter): statement ... >>> a = add(3, 4) 3, 4의 합은 7입니다. >>> a = add(3, 4) >>> print(a) None >>> def add(a, b): ... print("%d, %d의 합은 %d입니다." % (a, b, a+b)) ... >>> add(3, 4) 3, 4의 합은 7입니다. 59 Types of Functions in Python ▪ A function with no argument and no return value - def name(): statement ... >>> def say(): ... print('Hi’) ... >>> say() Hi 60 Return values ▪ What if we call this function? >>> ... ... >>> >>> >>> >>> ▪ def add_and_mul(a,b): return a+b, a*b result = add_and_mul(3,4) result1, result2 = add_and_mul(3, 4) print(result) print(result1, result2) A function always has one return value How about this function? - >>> def add_and_mul(a,b): ... return a+b ... return a*b ... >>> result = add_and_mul(2, 3) >>> print(result) 5 61 Input & Output 62 User Input ▪ Python uses the input() method and gets input from the users - An input() method treats every input as a string >>> a = input() Life is too short, you need python >>> a 'Life is too short, you need python' - The prompt argument is used to display a message to the user (optional) >>> number = input("Please enter a number: ") Please enter a number: 3 >>> print(number) 3 >>> type(number) <class 'str'> 63 Print ▪ The print() function prints the specified message - Can take any number of arguments, but can only have one expression ▪ Basic structure - Print(object(s), sep=separator, end=end, file=file, flush=flush) Parameter Description object(s) Any object, and as many as you like. Will be converted to string before printed sep=separator Optional. Specify how to separate the objects, if there is more than one. Default is ' ' end=end Optional. Specify what to print at the end. Default is '\n' (line feed) 64 Print ▪ Using a sep parameter - Default is ' ' >>> print("life", "is", "too short") life is too short - Specify the separator >>> print("010", "111", "1234", sep="-") 010-111-1234 ▪ Using an end parameter - Default is '\n' >>> for i in range(3): ... print(i) ... 0 1 2 - Specify the end >>> for i in range(10): ... print(i, end=' ') ... 0 1 2 3 4 5 6 7 8 9 65 File Handling 66 File open ▪ The key function for working with files in Python is the open() function - The open() function takes two parameters; filename, and mode f = open(filename, mode) # f is file object - A file is located in the same directory as a Python file f = open("new_file.txt", "r") f.close() Mode f = open("new_file.txt", "w") f.close() r - If the file is located in a different location, you will have to specify the file path f = open("C:/opensourse/new_file.txt") f.close() 67 Description Read (Default value) – Opens a file for reading, error if the file does not exist w Write – Open a file for writing, create the file if it does not exist a Append – Open a file for appending, creates the file if it does not exist Write Files ▪ Create a new file - Using the open() method with write mode (w) # writedata.py f = open("C:/opensourse/newfile.txt", 'w') for i in range(1, 11): data = "This is line %d.\n" % i f.write(data) f.close() 68 Read Files ▪ There are several ways to read a file This is line 1. - Using readline() function # readline_test.py f = open("C:/opensourse/newfile.txt", 'r') line = f.readline() print(line) f.close() - If you want to read all lines # readline_all.py f = open("C:/opensourse/newfile.txt", 'r') while True: line = f.readline() if not line: break print(line) f.close() 69 This This This This This This This This This This is is is is is is is is is is line line line line line line line line line line 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Read Files ▪ There are several ways to read a file - Using readlines() function # readlines_test.py f = open("C:/opensourse/newfile.txt", 'r') lines = f.readlines() # list for line in lines: print(line) f.close() - Using read() function – return a string # read_test.py f = open("C:/opensourse/newfile.txt", 'r') data = f.read() # string print(data) f.close() 70 This This This This This This This This This This is is is is is is is is is is line line line line line line line line line line 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. Append Data in a File ▪ Write to an existing file - Using write mode (w) – will overwrite any existing content - Using append mode (a) – will append to the end of the file # adddata.py f = open("C:/opensourse/newfile.txt", 'a') for i in range(11, 21): data = "This is line %d.\n" % i f.write(data) f.close() 71 Summary 72 Lecture Summary ▪ Python Programming Basic - Data types (Number, String, List, Tuple, Dictionary, Set) Conditional statements (if statement) Loop statements (while & for statements) Functions (parameter, argument, return value) Input & Output (input method, print function) File Handling (file open, write file, read file, append data in a file) 73 We will learn the chapter 4. Programming with Robots 74 Thanks for listening Knowledge-based Data Discovery INHA KDD Lab.