0% found this document useful (0 votes)
130 views64 pages

Python in 30 Minutes! : Fariz Darari

The document provides an introduction to the Python programming language, discussing that it was created in 1991 by Guido van Rossum and can be used freely even for commercial purposes. It also shows some basic Python code examples and highlights areas where Python is commonly used like data science, image processing, and game development. The document concludes by exploring the Python universe and covering topics like variables, conditionals, loops, functions, and strings.

Uploaded by

Juan Dominguez
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)
130 views64 pages

Python in 30 Minutes! : Fariz Darari

The document provides an introduction to the Python programming language, discussing that it was created in 1991 by Guido van Rossum and can be used freely even for commercial purposes. It also shows some basic Python code examples and highlights areas where Python is commonly used like data science, image processing, and game development. The document concludes by exploring the Python universe and covering topics like variables, conditionals, loops, functions, and strings.

Uploaded by

Juan Dominguez
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/ 64

Python in 30 minutes!

*
Fariz Darari

* Recommended slide reading time unless otherwise specified


Not this python, unfortunately

2
But this Python!

3
But this Python!

Programming Language

4
But this Python!

Programming Language

Created in 1991 by Guido van Rossum

5
But this Python!

Cross Platform

Programming Language

Created in 1991 by Guido van Rossum

6
But this Python!

Cross Platform

Programming Language

Created in 1991 by Guido van Rossum Freely Usable Even for Commercial Use

7
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

8
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

9
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

public class Main {


public static void main(String[] args) {
System.out.println("Hello world!");
}
}

10
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

public class Main { print("Hello world!")


public static void main(String[] args) {
System.out.println("Hello world!");
}
}

11
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

12
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

Big names using Python 13


print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

https://opencv.org/
Image Processing using Python
14
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

https://www.pygame.org
Game Development using Python

15
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

https://matplotlib.org/
Data Science using Python 16
print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice


for beginners and experts alike." – codeschool.com

https://github.com/amueller/word_cloud
Natural Language Processing (NLP) and Text Mining using Python
17
Let's now explore the Python universe!

18
Python Setup
How to install Python the Anaconda way
1. Download Anaconda (which includes Python):
https://www.anaconda.com/download/
2. Run the installer and follow the installation instructions
3. Run the Spyder editor and create your first Python program "helloworld.py"

19
Variables and Data Types
• Variables store and give names to data values
• Data values can be of various types:
• int : -5, 0, 1000000
• float : -2.0, 3.14159
• bool : True, False
• str : "Hello world!", "K3WL"
• list : [1, 2, 3, 4], ["Hello", "world!"], [1, 2, "Hello"], [ ]
• And many more!
• In Python, variables do not have types!
• Data values are assigned to variables using "="
x = 1 # this is a Python comment
x = x + 5
y = "Python" + " is " + "cool!"
20
Variables and Data Types in Real Life

21
Conditionals and Loops

22
Conditionals and Loops

• Cores of programming!
• Rely on boolean expressions which return either True or False
• 1 < 2 : True
• 1.5 >= 2.5 : False
• answer == "Computer Science" :
can be True or False depending on the value of variable answer
• Boolean expressions can be combined with: and, or, not
• 1 < 2 and 3 < 4 : True
• 1.5 >= 2.5 or 2 == 2 : True
• not 1.5 >= 2.5 : True

23
Conditionals: Generic Form

if boolean-expression-1:
code-block-1
elif boolean-expression-2:
code-block-2
(as many elif's as you want)
else:
code-block-last

24
Conditionals: Usia SIM (Driving license age)

age = 20
if age < 17:
print("Belum bisa punya SIM!")
else:
print("OK, sudah bisa punya SIM.")

25
Conditionals: Usia SIM dengan Input

age = int(raw_input("Usia: ")) # use input() for Python 3


if age < 17:
print("Belum bisa punya SIM!")
else:
print("OK, sudah bisa punya SIM.")

26
Conditionals: Grading

grade = int(raw_input("Numeric grade: "))


if grade >= 80:
print("A")
elif grade >= 65:
print("B")
elif grade >= 55:
print("C")
else:
print("E")

27
Loops

• Useful for repeating code!


• Two variants:

while boolean-expression:
code-block

for element in collection:


code-block
28
while boolean-expression:

While Loops code-block

while raw_input("Which is the best subject? ") != "Computer Science":


print("Try again!")
print("Of course it is!")
29
for element in collection:

For Loops code-block

So far, we have seen (briefly) two kinds of collections:


string and list

For loops can be used to visit each collection's element:

for chr in "string": for elem in [1,3,5]:


print(chr) print(elem)

30
Conditionals and Loops in Real Life

31
Functions

• Functions encapsulate (= membungkus) code blocks


• Why functions? Modularization and reuse!
• You actually have seen examples of functions:
• print()
• raw_input()
• Generic form:
def function-name(parameters):
code-block
return value
32
def function-name(parameters):

Functions: Celcius to Fahrenheit code-block


return value

def celsius_to_fahrenheit(celsius):
fahrenheit = celsius * 1.8 + 32.0
return fahrenheit

33
Functions: Default and Named Parameters

def hello(name_man="Bro", name_woman="Sis"):


print("Hello, " + name_man + " & " + name_woman + "!")

>>> hello()
Hello, Bro & Sis!
>>> hello(name_woman="Lady")
Hello, Bro & Lady!
>>> hello(name_woman="Mbakyu",name_man="Mas")
Hello, Mas & Mbakyu!
34
Imports
• Code made by other people shall be reused!
• Two ways of importing modules (= Python files):
• Generic form: import module_name

import math
print(math.sqrt(4))

• Generic form: from module_name import function_name

from math import sqrt


print(sqrt(4))

35
Functions in Real Life

36
String
• String is a sequence of characters, like "Python is cool"
• Each character has an index
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
• Accessing a character: string[index]
x = "Python is cool"
print(x[10])
• Accessing a substring via slicing: string[start:finish]
print(x[2:6])

37
String Operations

P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13

>>> x = "Python is cool"


>>> "cool" in x # membership
>>> len(x) # length of string x
>>> x + "?" # concatenation
>>> x.upper() # to upper case
>>> x.replace("c", "k") # replace characters in a string
38
String Operations: Split
P y t h o n i s c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13

x.split(" ")

P y t h o n i s c o o l
0 1 2 3 4 5 0 1 0 1 2 3

>>> x = "Python is cool"


>>> x.split(" ") 39
String Operations: Join
P y t h o n i s c o o l
0 1 2 3 4 5 0 1 0 1 2 3

",".join(y)

P y t h o n , i s , c o o l
0 1 2 3 4 5 6 7 8 9 10 11 12 13
>>> x = "Python is cool"
>>> y = x.split(" ")
>>> ",".join(y) 40
Strings in Real Life

41
Input/Output

• Working with data heavily involves reading and writing!


• Data come in two types:
• Text: Human readable, encoded in ASCII/UTF-8, example: .txt, .csv

• Binary: Machine readable, application-specific encoding,


example: .mp3, .mp4, .jpg

42
Input
python
is
cool
cool.txt

x = open("cool.txt", "r") # read mode

y = x.read() # read the whole


print(y)

x.close()
43
Input
python
is
cool
cool.txt

x = open("cool.txt", "r")

# read line by line


for line in x:
line = line.replace("\n","")
print(line)

x.close() 44
Input
python
is
cool
cool.txt

x = open("C:\\Users\\Fariz\\cool.txt", "r") # absolute location

for line in x:
line = line.replace("\n","")
print(line)

x.close()
45
Output

# write mode # append mode


x = open("carpe-diem.txt", "w") x = open("carpe-diem.txt", "a")

x.write("carpe\ndiem\n") x.write("carpe\ndiem\n")

x.close() x.close()

Write mode overwrites files,


while append mode does not overwrite files but instead appends at the end of the files' content
46
Input in Real Life

47
Output in Real Life

48
Lists

• If a string is a sequence of characters, then


a list is a sequence of items!
• List is usually enclosed by square brackets [ ]
• As opposed to strings where the object is fixed (= immutable),
we are free to modify lists (that is, lists are mutable).
x = [1, 2, 3, 4]
x[0] = 4
x.append(5)
print(x) # [4, 2, 3, 4, 5]

49
List Operations

>>> x = [ "Python", "is", "cool" ]


>>> x.sort() # sort elements in x
>>> x[0:2] # slicing
>>> len(x) # length of string x
>>> x + ["!"] # concatenation
>>> x[2] = "hot" # replace element at index 0 with "hot"
>>> x.remove("Python") # remove the first occurrence of "Python"
>>> x.pop(0) # remove the element at index 0

50
List Comprehension

It is basically a cool way of generating a list

[expression for-clause condition]

Example:
[i*2 for i in [0,1,2,3,4] if i%2 == 0]

[i.replace("o", "i") for i in ["Python", "is", "cool"] if len(i) >= 3]


51
Tuples

• Like a list, but you cannot modify it (= immutable)


• Tuple is usually (but not necessarily) enclosed by parentheses ()
• Everything that works with lists, works with tuples,
except functions modifying the tuples' content
• Example:
x = (0,1,2)
y = 0,1,2 # same as x
x[0] = 2 # this gives an error

52
List in Real Life

53
Sets
• As opposed to lists, in sets duplicates are removed and
there is no order of elements!
• Set is of the form { e1, e2, e3, ... }
• Operations include: intersection, union, difference.
• Example:
x = [0,1,2,0,0,1,2,2]
y = {0,1,2,0,0,1,2,2}
print(x)
print(y)
print(y & {1,2,3}) # intersection
print(y | {1,2,3}) # union
print(y - {1,2,3}) # difference
54
Dictionaries
• Dictionaries map from keys to values!
• Content in dictionaries is not ordered.
• Dictionary is of the form { k1:v1, k2:v2, k3:v3, ... }
• Example:
x = {"indonesia":"jakarta", "germany":"berlin","italy":"rome"}
print(x["indonesia"]) # get value from key
x["japan"] = "tokyo" # add a new key-value pair to dictionary
print(x) # {'italy': 'rome', 'indonesia': 'jakarta', 'germany': 'berlin', 'japan': 'tokyo'}

55
Dictionary in Real Life

56
Classes

• While in functions we encapsulate a set of instructions,


in classes we encapsulate objects!
• A class is a blueprint for objects, specifying:
• Attributes for objects
• Methods for objects
• A class can use other classes as a base
• Generic:
class class-name(base):
attribute-code-block
method-code-block
57
class class-name(base):

Classes: Person attribute-code-block


method-code-block

class Person:

def __init__(self, first, last):


self.firstname = first
self.lastname = last

def describe(self):
return self.firstname + " " + self.lastname

guido = Person("Guido","Van Rossum")


print(guido.describe())

58
class class-name(base):

Classes: Person & Employee attribute-code-block


method-code-block
# first add code for class Person here

class Employee(Person):

def __init__(self, first, last, staffnum):


Person.__init__(self, first, last)
self.staffnum = staffnum

def describe(self):
return self.lastname + ", " + str(self.staffnum)

guido = Employee("Guido", "Van Rossum", 123456)


print(guido.describe()) 59
Class in Real Life

60
Lessons learned

61
What's next?

62
What's next? Keep learning!

https://docs.python.org
Python Official Documentation http://greenteapress.com/wp/think-python-2e/
Free Python e-book

https://stackoverflow.com/questions/tagged/python
Python on stackoverflow (QA website on programming)

63
Food pack is ready,
enjoy your journey!

64

You might also like