Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 86

KULIAH #3 ALGORITMA DAN PEMROGRAMAN

DASAR PYTHON,
PENYELEKSIAN &
PERULANGAN
DASAR-DASAR BAHASA
PYTHON

12/04/2023 2
Tujuan Pembelajaran

• Memberi informasi tentang dasar-dasar Python


• Mengenal kelebihan Python

12/04/2023 3
Outline of this Lesson

• Brief History of Python


• Installing Python
• Basic Commands in Python
• Code Examples
• Challenges to students
• Some algorithms
• Home Exercises

12/04/2023 4
Brief History of Python
• The programming language Python was conceived in the late 1980s,[1] and
its implementation was started in December 1989[2] by Guido van Rossum
at CWI in the Netherlands as a successor to ABC capable of
exception handling and interfacing with the Amoeba operating system
• Python was named after the BBC TV show Monty Python's Flying Circus
• Python 2.0 was released on October 16, 2000
• Python 3.0, a major, backwards-incompatible release, was released on
December 3, 2008
• Written in C
• Open source

12/04/2023 5
Why Use Python (1)

• Python is free – is open source distributable software.


• Python is easy to learn – has a simple language syntax.
• Python is easy to read – is uncluttered by punctuation.
• Python is easy to maintain – is modular for simplicity.
• Python is “batteries included” – provides a large standard library for easy
integration into your own programs.
• Python is interactive – has a terminal for debugging and testing snippets
of code.

12/04/2023 6
Why Use Python (2)

• Python is portable – runs on a wide variety of hardware platforms and has


the same interface on all platforms.
• Python is interpreted – there is no compilation required.
• Python is high-level – has automatic memory management.
• Python is extensible – allows the addition of low-level modules to the
interpreter for customization.
• Python is versatile – supports both procedure-orientated programming
and object-orientated programming (OOP).
• Python is flexible – can create console programs, windowed GUI
(Graphical User Interface) applications, and CGI (Common Gateway
Interface) scripts to process web data.

12/04/2023 7
Installing Python

• Untuk kuliah ini tidak perlu menginstall IDE


• Kita akan menggunakan Google Colab (https://colab.research.google.com)

• Install anaconda

12/04/2023 8
Example
codes (1)

12/04/2023 9
Example
codes (2)

12/04/2023 10
Operator Artimetika

12/04/2023 11
Example codes (3)

12/04/2023 12
Challenges (1)

12/04/2023 13
Challenges
(2)

12/04/2023 14
Outline

• Penyeleksian • Loop
• Penyeleksian Tunggal • Perulangan for
• Penyeleksian Ganda • Range
Penyeleksian multi • Perintah break
• Menentukan pilihan • Perintah continue
• Contoh-contoh kasus penyeleksian • Perintah pass
• Perulangan while
• Loop bersarang
Contoh kode

num=int(input(“Masukkan sebuah bilangan: “));


If num==0:
num=num+1
print(num)
num1,num2,num3=input("masukkan 3 bilangan: ").split()
if (num1>num2) and (num1>num3):
print(num1," is the largest")
elif (num2>num1) and (num2>num3):
print(num2," is the largest")
else:
print(num3," is the largest")
LOOP
Loops in Python

• For loop
• While loop
For loop Syntax
Contoh
range()

• The range() function can produce an integer sequence at runtime


• For example, a statement like range(0, 10) will generate a series of ten
integers starting from 0 to 9.
range()
Step Values for the range Function
• If negative step value is used and initial value is greater than terminating
value,
• Range function generates a decreasing sequence
• Examples:

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Some Examples (1)

• Example 1: • Example 2:
for x in range(6): for x in range(2, 6):
print(x) print(x)

• Output: • Output:
0 2
1 3
2 4
3 5
4
5
Some Examples (2)

• Example 3: • Example 4:
for x in range(2, 30, 3): a=[“banana”, “apple”, ”jackfruit”]
print(x) for element in a:
print(element)
• Outputs:
2 • Outputs:
5
8 Banana
11 Apple
14 jackfruit
17
20
23
26
29
Some Examples (3)
Step Values for the range Function
• Example 3: Program requests
• amount deposited
• annual rate of interest
• then calculates balance after each quarter-year for four
quarters.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Step Values for the range Function

• Example 3, cont.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Latihan

• Hitung jumlah bilangan dari 1-10


• Hitung rata-rata bilangan dari 1-10.
Python For Loop Example – Find the Average
of N Numbers

• Create a list of integers and populate with N (=6) values.


• Initialize a variable (sum) for storing the summation.
• Loop N (=6) number of times to get the value of each integer from the list.
• In the loop, add each value with the previous and assign to a variable
named as the sum.
• Divide the “sum” with N (=6). We used the len() function to determine the
size of our list.
• The output of the previous step is the average we wanted.
• Finally, print both the “sum” and the average.
Kode:
Else Clause with Python For Loop

• Syntax
For-Else Flowchart
Example

for x in range(6):
print(x)
else:
print("Finally finished!")

0
1
2
3
4
5
Finally finished!
Break Statement

• The break statement, like in C, breaks out of the innermost enclosing for
or while loop.
• Loop statements may have an else clause; it is executed when the loop
terminates through exhaustion of the iterable (with for) or when the
condition becomes false (with while), but not when the loop is terminated
by a break statement.
• When used with a loop, the else clause has more in common with
the else clause of a try statement than it does with that of if statements: a
try statement’s else clause runs when no exception occurs, and a
loop’s else clause runs when no break occurs. For more on
the try statement and exceptions, see Handling Exceptions.
• Example: • Example 2:
fruits = ["apple", "banana", "cherry"] fruits = ["apple", "banana", "cherry"]
for x in fruits: for x in fruits:
print(x) if x == "banana":
if x == "banana": break
break print(x)

• Output:
• Ouput: apple
apple
banana
Continue Statement

• With the continue statement we can stop the current iteration of the loop,
and continue with the next
Some Examples

• Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

• Output:
apple
cherry
• for x in "banana":
print(x)
Looping Through Arithmetic Progression of
Numbers
• Example 2: Program displays a table showing the population each year until
2018.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
While Loop
• A while loop is a control flow structure which repeatedly executes a block
of code indefinite no. of times until the given condition becomes false.
• For example, say, you want to count the occurrence of odd numbers in a
range. Some technical references call it a pre-test loop as it checks the
condition before every iteration.

• Syntax

If the check fails, then the control won’t enter into the loop instead will get
transferred to the next statement. Whereas if the condition passes, then the
statements inside the loop shall execute.
This cycle would repeat itself until the while condition fails or returns false. When
such a situation would occur, the loop would break and pass control to the next
executable statement.
While Flowchart
Examples:

• i=1 • i=1
while i <= 6: while i < 6:
print(i) print(i)
i += 1 if i == 3:
• Output: break
i += 1
1
• Output
2
1
3
2
4
3
5
6
• Contoh:
i=1 • Output:
while i < 6: 1
2
print(i) 3
i += 1 4
else: 5
i is no longer less than 6
print("i is no longer less than 6")
• i=0
while i < 6:
i += 1
if i == 3:
continue
The while Loop

• Example 1: Program displays 1 – 5, after loop terminates, num will be 6

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The while Loop

FIGURE 3.22 Flowchart


for Example 1.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


The while Loop

• Example 2: Input validation.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The while Loop

• Example 3: Find min, max, average.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The while Loop

• Example 3: Find min, max, average.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The while Loop
• Example 4: Stores the numbers in a list, and then uses list methods and
functions to determine the requested values.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The while Loop

• Example 5: Determines when bank deposit


reaches one million dollars

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The break Statement

• Example 6: Program uses break to avoid two input statements.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The break Statement

FIGURE 3.23 Flowchart for Example 6

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


The continue Statement

• When continue executed in a while loop


• Current iteration of the loop terminates
• Execution returns to the loop’s header
• Usually appear inside if statements.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The continue Statement
• Example 7: Searches a list for the first int object that is divisible by 11.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Creating a Menu
• Example 8: Uses a menu to obtain facts about the United States.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
The continue Statement

• Example 8: Uses a menu to obtain facts about the United States.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Infinite Loops

• Example 9: Condition number >= 0 always true.

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Infinite Loops

FIGURE 3.24
Program Containing
an Infinite Loop.

© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.


Nested Loop

• A nested loop is a loop inside a loop.


• The "inner loop" will be executed one time for each iteration of the "outer
loop"
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Nested for Loops

• Example 4: Program displays a multiplication table for the integers from 1


to 5

© 2016 Pearson Education, Inc., Hoboken,


NJ. All rights reserved.
Pass Statement

• for loops cannot be empty, but if you for some reason have a for loop with
no content, put in the pass statement to avoid getting an error.
• for x in [0, 1, 2]:
pass
Latihan

• Konversikan 0-100 der C, ke Fahrenheit


• Buat table factorial dari 1-10
Cetak: def pypart(n):
* for i in range(0, n):
** for j in range(0, i+1):
***
print("* ",end="")
****
print("\r")
*****
n=5
pypart(n)
THANK YOU

You might also like