0% found this document useful (0 votes)
148 views118 pages

Phyton

The document provides an overview of the Python programming language, discussing its creation, popularity, versatility, and why it is easy and powerful to use. It also outlines key Python concepts like types, expressions, variables, strings, lists, tuples, sets, and dictionaries. The document is intended to help readers get started with Python programming.

Uploaded by

yosia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views118 pages

Phyton

The document provides an overview of the Python programming language, discussing its creation, popularity, versatility, and why it is easy and powerful to use. It also outlines key Python concepts like types, expressions, variables, strings, lists, tuples, sets, and dictionaries. The document is intended to help readers get started with Python programming.

Uploaded by

yosia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

Getting Started with

Python – Part 1

Adila Alfa Krisnadhi, Ph.D.

digitalent.kominfo.go.id
Outline
• Python: Overview
• Types, expressions, variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Programming Language Not Python the snake

Created by Guido von Rossum in 1991

Cross platform
Freely usable including
for commercial purpose
Why Python?
Python is popular

Survey from Pakt - https://adtmag.com/articles/2016/07/19/python-skills-survey.aspx


Python is easy to use (more concise)

versus
Python is powerful
• Many big names use Python in their product
Python is versatile
• Image processing using Python - https://opencv.org
• Game development using Python - https://www.pygame.org/
• Data visualization using Python - https://matplotlib.org
• Natural language processing using Python - https://www.nltk.org
• Deep learning using Python -
https://github.com/tensorflow/tensorflow
• Web development using Python - https://www.djangoproject.com
Let’s get started …
First Python program: Revisited
• You’ve seen your first few Python programs when we discussed Jupyter Notebook
in the previous session.
• So, let’s open a new Notebook.
• Make sure Jupyter Notebook has been set up in your computer before continuing.
• The first thing to note, a Python code line that begins with a hash symbol will be
considered a comment, which will not be executed.
Syntax error message
• A mistake in writing down a Python command will yield an error
message when executed.
Semantic error
• If there is a mistake in the program logic, Python will not tell you a
mistake if no syntax error is detected.
• E.g., suppose the intention is to print ‘Hello Python 101’, but we accidentally
write ‘Hello Python 102’, then Python won’t complain although the code is
wrong.
Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Python types
Python types Example expression
int 11, -14, 0, 2
float 21.3201, 0.0, 0.8, -2.34
str “Hello Python 101”

• Use type() function to get the type


of an expression
Typecasting: Convert one type to another
Boolean type
• Boolean type only has two possible
values: True and False (with
uppercase T and F).
• The type name is bool
• Casting True to int yields 1
• Casting False to int yields 0
Expressions

• Expressions: operation that Python


performs
• E.g., arithmetic operation
• The symbols: +, -, *, /, //, etc. are
called operators
• The numbers are called operands
Expressions
• Note that / and // are different
Expressions
• Python follows the traditional convention in operator precedence, e.g.,
multiplication is of higher precedence than addition.
• Of course, parentheses takes highest precedence
Variables
• Variables store and give names to data values
• Variables do not have an intrinsic type; only data
values have it (int, float, str, bool, and many
others)
• Current type of a variable is the type of data value it
currently stores
• Data values are assigned to variables using ‘=‘ sign
• The statement/command is called variable assignment.
• A variable only stored the most recent data value
assigned to it.
• A data value assigned to a variable can be used in
any expression after the assignment by writing
that variable to the expression.
Examining types of variables
• We can use the type()command on variables to examine their
current types
Variable naming
• It’s good practice to use meaningful names for variables
• Variable names starts with a letter or underscore character (‘_’) followed by any number of
letters or numbers.
• Suppose we have data about duration of three videos: 42 minutes, 57 minutes,
and 43 minutes. How many hours of the total duration of three videos?
Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Strings
• String: sequence of characters enclosed within two double-quotes

• Can also be written by enclosing it within two single quotes.

• By default, Python interpreter outputs a string enclosed with single quotes.


Strings
• Strings may contain spaces and digits

• … also special characters


• Single quote as a character in double quoted string

• Double quotes as a character in single quoted string


Strings
• Like other data values, we can assign a string to a variable

S e m a r a n g T a w a n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

• String is an ordered sequence,


• each element can be accessed via an index represented by an array of numbers
• Non-negative indices start from 0 going from left to right
Strings
• Negative index can also be used
• The rightmost index is -1, decreasing by 1 each time going from right to left

S e m a r a n g T a w a n g
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String length
• Length of a string can be obtained via len() function
String slicing
• You can get a substring by slicing.
• s[m:n] is a substring of s taken from character at index m until character at index n-1
• If n ≤ m, then the slicing yields an empty sequence.

S e m a r a n g T a w a n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String striding
• s[m:n:p] operates like s[m:n], but starting from index m, we move p
steps at a time from left to right
S e m a r a n g T a w a n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String slicing and striding default value
• Omitting m, n, or p in the expression s[m:n] and s[m:n:p] causes Python to use their
default values: m = 0, n = len(s), p = 1

S e m a r a n g T a w a n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
-15 -14 -13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
String concatenation
• We use “+” to concatenate strings
String replication
• Multiply a string with a number (using “*”) yields a new string
containing the replication of the old string.
Strings are immutable!
• String is immutable: you cannot change • But you can reassign the
the value of characters in a string. variable to a new string
String: escape sequences
• Certain characters are difficult to input (e.g., for print() function), so we
use prefix it with a backslash “\” to use them.
• E.g., newline, tab, and the backslash itself.
• Printing backslash character without escaping can be done using raw string notation
(with the ‘r’ prefix)
String: sequence methods and string methods
• The previous methods/operations (indexing, slicing, striding) on
strings also work on other types of sequences (discussed later)
• Other than those, there are also methods specific to strings.
• Strings are immutable. So, we apply a method to a string A, the
method will return a new string B.

A Method B
String: Get uppercase version of a string
A = “Surabaya is the city of heroes”
• upper() returns uppercase version of
the string

upper()

B: “SURABAYA IS THE CITY OF HEROES”


String: replace substring with another
• Get a new string with the given substring A: “Jakarta is the largest”
replaced by a new substring
most crowded

“Jakarta is the largest”

B: “Jakarta is the most crowded”


String: Find the occurrence of substring
• Find the location of the first occurrence of the given substring

S e m a r a n g T a w a n g
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
More string operations …
• See https://docs.python.org/3/library/stdtypes.html#string-methods
Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Tuples
• Tuple is an ordered sequence
• Tuples are written as comma-separated items within parentheses.

Its length is the number of


elements it contains
Tuples
• Tuples may contain elements of different types

str int float

• But the type of the sequence remains tuple


Tuple: accessing elements

0 “Alice”

1 85

2 3.8
Tuple: accessing elements (negative index)

-3 “Alice”

-2 85

-1 3.8
Tuple concatenation
• Like string, tuple can be concatenated resulting in a new tuple.

0 1 2 3 4
Tuple slicing
• We can slice tuples like string

(‘Alice’, 85, 3.8, ‘USA’, 25)


Tuples are immutable (like strings)

grades
(95, 85, 90, 72, 68, 82, 85, 90, 75)
grades1
Tuples are immutable (like strings)

grades
(95, 85, 90, 72, 68, 82, 85, 90, 75)
grades1

Changing the value of variable is simply changing where the


reference points to

grades (95, 85, 90, 72, 68, 82, 85, 90, 75)

grades1 (90, 77, 88)


Tuples are immutable
• E.g., to sort a tuple, we use the sorted() function to get a new
sequence that is already sorted.
• The return value of sorted() is of type list (discussed later).
• To get a tuple, we typecast it to tuple.
Tuple nesting
• Tuples can be nested: a tuple may contain other tuples.
nt = (5, 7, ('Java', 'Bali'), (2, 11), ('Madura', (5, 7)))
0 1 2 3 4

nt[2] nt[3] nt[4]

('Java', 'Bali') (2, 11) (‘Madura’, (5,7))


'Java' 'Bali' 2 11 ‘Madura' (5,7)
nt[2][0] nt[2][1] nt[3][0] nt[3][1] nt[4][0] nt[4][1]

nt[2][1][0]
nt[2][1][1] nt[4][1][0]
nt[4][1][1]
'B’
'a’ 5 7
Lists
• Lists are also ordered sequence, but mutable (unlike tuples or strings)
• Lists are written inside square brackets
• Lists can be nested, containing other lists
• In fact, lists and tuples can containing anything including lists and tuples
Lists: Accessing elements
• Elements of lists can be accessed using index in the same way as
tuples or strings.

L = ['Surabaya', 3.4, 1293]


0 1 2
-3 -2 -1
Lists are mutable
• Unlike tuples or strings, elements of a list can be changed.
Lists are mutable
• If a list is referenced by two variables, changing its elements via one
variable will cause the changes to be visible from the other variable.
Suppose we have L and LL as follows: We change L[1], and the change appear in LL too
List slicing
• Slicing works like in tuples, but returns a new list (not sharing reference with the
old one).

Lst35 includes element at Lst[3]

Lst[3] is changed

But, Lst35 is NOT changed!


List slicing
• Thus slicing can be used to copy a list

Lst_c is a copy of Lst


Lst[0] is changed

But Lst_c is NOT changed!


List concatenation: use ‘+’ operator
• Concatenating two lists
yields a new list
List: extending the list at the end
• If you want to lengthen the list with elements from another list, use
extend() method.

• Lst is lengthened by adding


to its end as many positions
as the length of Lst2
• Elements of Lst2 are
successively copied to the
additional positions of Lst1
List: appending one element at the end

• append() adds just one element


to the end of the list.
• If its argument is another list,
then the old list now contains a
list as its last element.
List: deleting elements
• We can delete an element of a list at a particular index using del()
function.
Convert string to list
• To convert a string (of words, separated by spaces) into a list of words, we use the
string method split()
• If we want, we can specify which character to be used as separator/delimiter
(instead of spaces).
More list methods …
• See https://docs.python.org/3/library/stdtypes.html#sequence-
types-list-tuple-range

• Or you can type: help(list)


Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Sets
• Sets: unordered mutable collection of unique elements
• (Like lists and tuples) Sets can store elements of any Python types
• (Like lists and tuples) Sets are mutable
• (Unlike lists and tuples) Sets do not record element position
• (Unlike lists and tuples) Sets only contain unique elements –
duplicates are not stored.
• Elements of sets must be hashable, e.g.:
• immutable objects
• immutable containers/collections whose elements are all immutable objects
• So, sets cannot contain lists and other sets
Creating a set (1)
• Use curly brackets

• Notice that duplicates are not stored.


Creating a set (2)
• Or use the set() function

• Creating empty set can only be done using set() function, not curly braces!

Not a set!
Set: adding elements
“Bandung”, “Bogor”, “Depok”

“Bandung”, “Bogor”, “Depok”,


“Jakarta”

• Adding the same element doesn’t change the set

“Bandung”, “Bogor”, “Depok”,


“Jakarta”
Set: removing elements
“Bandung”, “Bogor”,
“Depok”, “Jakarta”

“Bandung”,
“Bogor”, “Depok”
Set: check if the set contain the given
element

“Bandung”, “Bogor”,
“Depok”
Set intersection

“Bogor”, “Depok”, “Bogor”, “Depok”,


“Jakarta” “Bandung”
Set intersection

“Bogor”, “Depok”
Set union

“Bogor”, “Depok”, “Bogor”, “Depok”,


“Jakarta” “Bandung”
Set union

“Jakarta” “Bogor”, “Depok” “Bandung”


Subset test

“Bogor”, “Depok”,
“Bogor”, “Depok”
“Jakarta”
Subset test

“Bogor”, “Depok”, “Jakarta”


“Bogor”, “Depok”
More set methods …
• See https://docs.python.org/3/library/stdtypes.html#set-types-set-
frozenset
Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Dictionaries
• Dictionaries: a collection of pairs
• Each pair consists of a key followed by a value separated by a colon.
• A dictionary’s keys form a set:
• The keys are unique and immutable
• Position of keys in dictionary are not recorded
• Values may be immutable, mutable, and duplicates
• Denoted by a pair of curly brackets where each key-value pair is
separated by a comma from other key-value pairs.
Dictionary: analogy with list
• Dictionaries are similar to lists in the sense that we use arbitrary immutable
objects as indices instead of integers.

List Dictionary
Index Element Key: is an index by label Value

0 Element1 Key 1 Value 1


1 Element2 Key 2 Value 2
2 Element3 Key 3 Value 3
3 Element4 Key 4 Value 4
… … … …
Dictionary

“Jakarta” 10.1
“Surabaya” 3.4
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
Dictionary: accessing elements using key

“Jakarta” 10.1
“Surabaya” 3.4
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
Dictionary: adding elements
“Jakarta” 10.1 “Jakarta” 10.1
“Surabaya” 3.4 “Surabaya” 3.4
“Bogor” 1.1 “Bogor” 1.1
“Depok” 1.8 “Depok” 1.8
“Bandung” 2.5 “Bandung” 2.5
“Medan” 2.2 “Medan” 2.2
“Makassar” 1.4 “Makassar” 1.4
“Denpasar” 0.9 “Denpasar” 0.9
“Ambon” 0.4
Dictionary: adding elements
“Jakarta” 10.1
“Surabaya” 3.4
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
Dictionary: deleting elements
“Jakarta” 10.1 “Jakarta” 10.1
“Surabaya” 3.4 “Bogor” 1.1
“Bogor” 1.1 “Depok” 1.8
“Depok” 1.8 “Bandung” 2.5
“Bandung” 2.5 “Medan” 2.2
“Medan” 2.2 “Makassar” 1.4
“Makassar” 1.4 “Denpasar” 0.9
“Denpasar” 0.9 “Ambon” 0.4
“Ambon” 0.4
Dictionary: deleting elements
“Jakarta” 10.1
“Surabaya” 3.4
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
“Ambon” 0.4
Dictionary: check if element is in dictionary
“Jakarta” 10.1
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
“Ambon” 0.4
Dictionary: get all keys using keys() method
“Jakarta” 10.1
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
• keys() returns a list-like object containing the
“Denpasar” 0.9
dictionary’s keys (which can be converted to a
“Ambon” 0.4 list or other collection
Dictionary: get all keys using keys() method
“Jakarta” 10.1
“Bogor” 1.1
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
“Ambon” 0.4
Dictionary: get all values using values() method
“Jakarta” 10.1 • values() method is similar, but for getting all
“Bogor” 1.1 values in the dictionary
“Depok” 1.8
“Bandung” 2.5
“Medan” 2.2
“Makassar” 1.4
“Denpasar” 0.9
“Ambon” 0.4
More dictionary methods …
• See https://docs.python.org/3/library/stdtypes.html#mapping-types-
dict
Outline
• Python: Overview
• Types, Expressions, Variables
• String operations
• Lists, Tuples
• Sets
• Dictionaries
• Conditions and Branching
Comparison operators

Operands Comparison
(Values) Boolean
Operator
Comparison: Equality

5 x == 8 Boolean
Comparison: Equality

5 == 8? False
Comparison: Equality

8 x == 8 Boolean
Comparison: Equality

8 == 8? True
Comparison: Greater than, Less than, etc.

because 6 is greater than or equal to 6


because 7 is greater than 6

because 1 is less than 6, i.e., NOT greater


than or equal to 6
Comparison: Greater than, Less than, etc.

because 1 is less than 6

because 1 is not equal to 6

because 1 is equal to 1
Comparing strings
• Two strings (or generally, sequences) A and B are the same if their
length is the same and for each position i, A[i] is equal to B[i].
The if Statement
• Suppose entrance to a tourist attraction is only given to those whose age is at
most than 12 years old.
• E.g., if age is 13, 14, or more, then entrance is not granted and the person just moves
on;
• if age is 12, 11, or less, then entrance is granted and (s)he moves on after enjoying
the ride.
• We can write this branching using if statement
if CONDITION:
do_something_only_when_condition_holds
everyone_do_something

• After the if-condition, the statements that we want to execute only when the if-
condition is true MUST be written with an indentation!
The if Statement
Because 11 is less than or equal to 12, if-
condition holds

Indented statements are executed when the


if-condition evaluates to true
This statement is executed regardless
whether the if-condition is true or not

Because 13 is more than 12, the indented


statement is NOT executed.
The if-else statement: choosing one of two alternatives
If-condition is True: 11 is less than or equal to 12

This is executed
This is NOT executed
This is executed, regardless of the if-condition

The else
statement

If-condition is False: 13 is more than 12


This is NOT executed
This is executed
This is executed, regardless of the if-condition
The elif statement: one of several alternatives
The condition is True (11 is less than or equal to 12)
The elif
statement

Executed

NOT executed

This is always executed


The elif statement: one of several alternatives
if-condition is False: 13 is more than 12
The elif
statement

NOT executed

elif-condition is True,
13 is equal to 13

Executed

This is always executed


The elif statement: one of several alternatives
if-condition is False: 13 is more than 12
The elif
statement

NOT executed

elif-condition is False,
15 is not equal to 13

Executed

This is always executed


The if, else, and elif statements
• Generally, we may have the following form:
• An if statement
• Followed by zero or more elif statements
• Then followed by zero or one else statement.
• The If-statement and all of elif statements have a Boolean condition
• The Boolean conditions are tested in turns from top to bottom until one condition is
found to be true.
• Once a true condition is found, the indented statements under the if/elif statement
for whose the condition is true are executed, and then we exit from the whole if-elif-
else block.
• If no condition is found to be true, and there is an else statement, then the indented
statements under it are executed. After that we exit the whole if-elif-else block. If
there is no else statement, we directly exit the if-elif-else block.
Logic operators

Boolean Logic
operands/ Boolean
values Operator
Logic operator: not

True not False

False not True


Logic operator: or
A
or C

A B A or B
False False False
False True True
True False True
True True True
Logic operator: or
The condition is true when pub_year is a
number from {…, 1978, 1979, 1990, 1991, …}

Was executed because


pub_year is 1990
Logic operator: and
A
and C

A B A and B
False False False
False True False
True False False
True True True
Logic operator: and
The condition is true when pub_year is a
number from {1980, 1981, …, 1989}

Was executed because


pub_year is 1985
More on branching and conditions …
• https://docs.python.org/3/library/stdtypes.html#truth-value-testing
• https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not
• https://docs.python.org/3/library/stdtypes.html#comparisons
• https://docs.python.org/3/reference/expressions.html#comparisons
• https://docs.python.org/3/reference/expressions.html#boolean-operations
• https://docs.python.org/3/reference/expressions.html#conditional-expressions
• https://docs.python.org/3/reference/compound_stmts.html#the-if-statement
Acknowledgements
• Materials for these slides were taken/recreated from:
• Fariz Darari, “Python in 30 Minutes”, 2018.
https://www.slideshare.net/fadirra/python-in-30-minutes
• Cognitiveclass.ai, “Your First Program”, Online course video for Python for Data
Science
• Cognitiveclass.ai, “Types”, Online course video for Python for Data Science
• Cognitiveclass.ai, “Expressions and Variables”, Online course video for Python for
Data Science
• Cognitiveclass.ai, “String Operations”, Online course video for Python for Data
Science
• Cognitiveclass.ai, “Lists and Tuples”, Online course video for Python for Data Science
• Cognitiveclass.ai, “Sets”, Online course video for Python for Data Science
• Cognitiveclass.ai, “Dictionaries”, Online course video for Python for Data Science
• Cognitiveclass.ai, “Conditions and Branching”, Online course video for Python for
Data Science
IKUTI KAMI

digitalent.kominfo
digitalent.kominfo
DTS_kominfo
Digital Talent Scholarship 2019

Pusat Pengembangan Profesi dan Sertifikasi


Badan Penelitian dan Pengembangan SDM
Kementerian Komunikasi dan Informatika
Jl. Medan Merdeka Barat No. 9
(Gd. Belakang Lt. 4 - 5)
Jakarta Pusat, 10110

digitalent.kominfo.go.id

You might also like