Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

Algoritma dan

Pemrograman

Python basics,
Comment, Data
Types, Input &
Output, Operator,
Decision

Adi
adi4vista@gmail.com
Today
• Symbols vs Identifiers
• Comment
• Data type
• Variable
• Output Statement
• Input Statement
• Operator
• Decision
Symbol vs Identifier
• A symbol is a recognizable character by a programming
language to represent a code, a sign which has a meaningful
purpose for a programming language
• A symbol can be a comment sign, bracket, arithmetic
operator, conditional operator or a logic operator
• An identifier is a unique name that identify a certain subject
in a program which make it differs from another
• An identifier can be a program statement, variable or a
function
Python Identifiers
• A Python identifier is a name used to identify a variable, function,
class, module or other object.
• An identifier starts with a letter A to Z or a to z or an underscore (_)
followed by zero or more letters, underscores and digits (0 to 9).
• Python does not allow punctuation characters such as @, $, and %
within identifiers.
• Python is a case sensitive programming language.
Thus, Manpower and manpower are two different identifiers in
Python.
Python keywords
Lines and Indentation
• Python does not use braces({}) to indicate blocks of code for class and
function definitions or flow control.
• Blocks of code are denoted by line indentation, which is rigidly enforced.
• The number of spaces in the indentation is variable, but all statements
within the block must be indented the same amount.
• Statements in Python typically end with a new line.
• Python, however, allows the use of the line continuation character (\) to
denote that the line should continue.
• The statements contained within the [], {}, or () brackets do not need to
use the line continuation character.
• The semicolon ( ; ) allows multiple statements on a single line given that
no statement starts a new code block.
Comment
• Comments (comments) are codes in Python scripts that are not executed
or not run by the machine. The comments are only used to mark or
provide written information on the script.
• Comments are commonly used to let others understand what the script is
doing. or to remind the programmer himself if one time to re-edit the
script.
• to use comments you can just write the # sign, followed by your comment.
Comment
Data Type in Computer Programming
• Bool or Logical data type
– 0 or 1
– True / False
– On / Off
• Numeric
– Integer data type (Byte, Integer, Long Integer, Integer 16 bit, Integer 32 bit, Integer 64
bit)
– Real data type (floating point, Single Precision, Double Precision)
• Non-Numeric
– Character (char)
– String (sentence)
• Others
– Array
– Structured
– List
– Date / Time
– Variant
– Class / Object
Python Data Type
• Describe the type of data
• Boolean -> True dan False
• Numbers
– int -> 1 2 3
– float -> 3.14
– complex -> 1 + 5j
• String
– “Saya”
– ‘saya’
– “””saya”””
• Compound Data Types
– List, Set, Tuple, Dict
• customized data type or a class data type
Variable
• memory locations that are reserved for storing values.
• variables are dynamic, meaning that python does not need to
be declared a particular data type and the python variable can
be changed when the program starts.
• rules:
– the first character must be a letter or underscore
– further characters can be letters, underscores or numbers
– characters in variable names are sensitive (case-sensitive)

• ex.
– name = “Tom Cruise”
scope variabel
# hint : global namespace vs local namespace

a = 10; b = 20

def my_function():
global b
a = 1
b = 200 + a

my_function()

print(a) # print 10
print(b) # print 201
Output Statement
• built-in function:
print(values[, sep, end, file, flush])
• ex.
– print(“Hello World”)  output: Hello World
– print(2 + 3)  output: 5
– name = “john”; print(name)  output: john
– nama_depan = “john”
– nama_belakang = “lennon”
print(nama_depan, nama_belakang, sep = ‘|’) 
output: john|lennon
Input Statement
• built-in function : input([prompt])
• If the prompt argument is present, it is written to standard
output without a trailing newline.
• The function then reads a line from input, converts it to a
string (stripping a trailing newline), and returns that.
• ex.
– name = input(‘your name ? ’)
– age = input(‘your age ? ’)
Data Type Conversion
• There are several built-in functions to perform conversion from one data type to
another.
• These functions return a new object representing the converted value.
• consists of :
int(x), float(x), complex(x[, imag]), str(x), repr(x), eval(str), tuple(s), list(s), set(s),
dict(d), frozenset(s), chr(x), unichr(x), ord(x), hex(x), oct(x), bin(x)
Operator
• Operators are the constructs, which can manipulate the value
of operands.
• types of operator
– Arithmetic Operators
– Comparison (Relational) Operators
– Assignment Operators
– Logical Operators
– Bitwise Operators
– Membership Operators
– Identity Operators
Arithmetic operators
• consists of:
# addition
# modules
+
%
# substraction
# exponent
-
**
# multiplication
# floor division
*
//
# division
/
Comparison (relational) operators
• consists of:
# equal
==
# not equal
!=
# less then
<
# greater then
>
# less then or equal
<=
# greater then or equal
>=
Assignment operators
• consists of:
# assign
= # modulo and assign
# add and assign %=
+= # exponent and assign
# substract and assign **=
-= # floor division and assign
# multiply and assign //=
*=
# divide and assign
/=
Bitwise operators
• Bitwise operator works on bits and performs
bit-by-bit operation.
• consists of:
# binary and # binary left shift
& <<
# binary or # binary right shift
| >>
# binary xor
^
# binary complement
~
Logical operators
• consists of:
# logical and
and
# logical or
or
# logical not
not
Membership operators
• membership operators test for membership in
a sequence, such as strings, lists, or tuples.
• consists of:
in
not in
Identity operators
• Identity operators compare the memory
locations of two objects
• consists of:
is
is not
Operators Precedence
• from highest to lowest
** exponent
~+- complement, unary + -
* / % // multiply, divide, modulo, floor division
+- addition, substraction
>> << right and left bitwise shift
& bitwise and
^| bitwise xor and or
<= < > >= comparison
== != equality
= += -= *= /= %= //= **= assignment
is, is not identity
in, not in membership
not, and, or logical
Decision making
• Decision-making is the anticipation of conditions occurring during
the execution of a program and specified actions taken according to
the conditions.
• Decision structures evaluate multiple
expressions, which produce TRUE or FALSE
as the outcome. You need to determine
which action to take and which statements
to execute if the outcome is TRUE or FALSE
otherwise.
• Python programming language assumes any non-zero and non-
null values as TRUE, and any zero or
null values as FALSE value.
Decision making (if)
Decision making (if)
Decision making (if ... else ...)
Decision making (if ... else ...)
Decision making (elif)
Decision making (elif)
Decision making (nested if)
Decision making (nested if)
Type of error
• Compilation Error (Including Semantic and
Lexical Error)
– Usually happens because of semantic, lexical and
other programming language error
– Usually happens before runtime

• Runtime Error
– Usually happens when program is running in an
unpredictable state
Error handling
• Compilation Error
– By following the rules/regulation of the
programming language, including semantic
and lexical rules
• Runtime Error
– By using exception handling
Exception Handling
• what is exception ?
– An exception is an event, which occurs during the
execution of a program that disrupts the normal flow of
the program’s instructions.
– An exception is a Python object that represents an error.

• When a Python script raises an exception, it must either


handle the exception immediately otherwise it terminates
and quits.
handling an exception
If you have some suspicious code that may raise an exception, you can
defend your program by placing the suspicious code in a try: block.
After the try: block, include an except: statement, followed by a block
of code which handles the problem as elegantly as possible.
important points
• A single try statement can have multiple except statements. This is
useful when the try block contains statements that may throw
different types of exceptions.
• You can also provide a generic except clause, which handles any
exception.
• After the except clause(s), you can include an else-clause. The code
in the else-block executes if the code in the try: block does not raise
an exception.
• The else-block is a good place for code that does not need the try:
block's protection.
• there are too many exceptiontype to be discuss, read
https://docs.python.org/3/library/exceptions.html for complete
information.
try-finally clause
You can use a finally: block along with a try: block.
The finally: block is a place to put any code that must execute,
whether the try-block raised an exception or not. The syntax of
the try-finally statement is this
try...except...else...finally... example
Exercises
1. Design an algorithm/program to determine a
number input from keyboard between 0 to 9
into a string word number.
2. Design an algorithm/program to determine
month name and number of days in that
month when a month number is input
Exercises
3. Please modify exercise 1, when the number
input is not among 0 to 9, please notify the
user or print a message that the number
must be among 0 to 9
4. Please modify exercise 2, when the number
input is not among 1 to 12, please notify the
user or print a message that the month
number is wrong
Exercises
5. Design an algorithm/program to determine grade according to the rules
below when a numeric examination mark is entered
Grade A+: 95<Mark<=100
Grade A: 90<Mark<=95
Grade A-: 85<Mark<=90
Grade B+: 80<Mark<=85
Grade B: 75<Mark<=80
Grade B-: 70<Mark<=75
Grade C+: 60<Mark<=65
Grade C: 55<Mark<=60
Grade C-: 50<Mark<=55
Grade D: 35<Mark<=50
Grade E: 0<=Mark<=35

You might also like