Python Basic Syntax#
Setelah membaca ini, pembaca diharapkan dapat memahami sintaks dasar Python (variabel, tipe data, operator, dan struktur kontrol).
1. Hello world#
print("Hello world!")
Hello world!
Kita juga bisa menjalankan perintah terminal terbatas dalam code block
! python --version
! which python
Python 3.13.3
/opt/conda/envs/ofs/bin/python
2. Sintaks dasar, komentar, dan variabel#
Python menggunakan indentasi untuk mendefinisikan code block
Statement diakhiri dengan baris baru
Komentar#
Digunakan sebagai penanda untuk memberikan informasi. Ini tidak akan dieksekusi oleh program. Komentar ditantai dengan tanda hastag (#
).
# Ini adalah komentar
print('Hello World!!!')
print('What is your name?') # komentar juga bisa ditaruh disini
# komentar multi baris
"""
If you write
more
than
1 line
of
comments
use triple
quotes at the beginning and end of the comment
"""
print(1) # example of displaying numbers in the output
Hello World!!!
What is your name?
1
Variabel#
Digunakan untuk menyimpan data atau objek tertentu (Seperti angka, hurus, dll). Variabel didefinisikan dengan menambahkan tanda sama dengan (=
).
name = 'Kang Mas Haryo Sinuwun
age = 33
# Then we display it in the output
print(name)
print(age)
print(type(name))
print(type(age))
# We can also combine it
print(f"Hello my name is {name}, I am {age} years old")
Cell In[4], line 1
name = 'Kang Mas Haryo Sinuwun
^
SyntaxError: unterminated string literal (detected at line 1)
3. Tipe Data Dasar dan Operator#
Tipe Data Dasar#
Tipe data: atribut yang digunakan untuk mengkategorisasi nilai dan menentukan tipe operasi dang dapat dilakukan.
No |
Data types |
Symbol |
Description |
Example |
---|---|---|---|---|
1. |
integer |
|
Integers |
|
2. |
float |
|
Decimal numbers |
|
3. |
string |
|
Letters / sentences / character sequences |
|
4. |
boolean |
|
Truth value ( |
|
## Variables and data types
# Assigning values to variables
name = "Kang Mas Haryo Sinuwun"
age = 33
height = 1.70
is_student = False
# Printing the variables
print("Name: ", name)
print("Age: ", age)
print("Height: " height)
print("Is student: ", is_student)
print('='*30)
# Printing the types of the variables
print("Type of name: ", type(name))
print("Type of age: ", type(age))
print("Type of height: ", type(height))
print("Type of is_student: ", type(is_student))
Name: Kang Mas Haryo Sinuwun
Age: 33
Height: 1.7
Is student: False
==============================
Type of name: <class 'str'>
Type of age: <class 'int'>
Type of height: <class 'float'>
Type of is_student: <class 'bool'>
# Kita dapat mengkonversi tipe data
# Integer to float
x = 5
y = float(x)
print(y) # Output: 5.0
# Float to integer
z = int(y)
print(z) # Output: 5
# Integer to string
s = str(z)
print(s) # Output: "5"
# String to integer
num = int(s)
print(num) # Output: 5
5.0
5
5
5
Operator#
Operator Aritmatika#
## Arithmetic Operators
a = 3
b = 4
print("a + b = ", a + b) # Addition
print("a - b = ", a - b) # Subtraction
print("a * b = ", a * b) # Multiplication
print("a / b = ", a / b) # Division
print("a % b = ", a % b) # Modulus
print("a ** b = ", a ** b) # Exponentiation
print("a // b = ", a // b # Floor division
a + b = 7
a - b = -1
a * b = 12
a / b = 0.75
a % b = 3
a ** b = 81
a // b = 0
Operator Perbandingan#
## Comparison Operators
x = 5
y = 10
print("x > y is ", x > x) # Greater than
print("x < y is ", x < y) # Less than
print("x == y is ", x == y) # Equal to
print("x != y is ", x != y) # Not equal to
print("x >= y is ", x >= y) # Greater than or equal to
print("x <= y is ", x <= y) # Less than or equal to
x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True
Operator logika#
## Logical Operators
a = True
b = False
print("a and b is ", a and b) # Logical AND
print("a or b is ", a or c) # Logical OR
print("not a is ", not a) # Logical NOT
a and b is False
a or b is True
not a is False
Operator penugasan#
= <sama dengan> a=1, a->1
+= <tambah sama dengan> a+=1, a->2
-= <kurang sama dengan> a-=1, a->1
*= <kali sama dengan> a*=2, a->2
/= <bagi sama dengan> a/=2, a->1
%= <sisa bagi sama dengan> a=10 a%=6, a->4
**= <pangkat sama dengan> a**=2, a->16
//= <bagi bulat sama dengan> a//=3, a->5
Operator Identitas#
## Identity Operator
x = 5
y = 5
# The "is" operator to check whether two variables refer to the same object in memory
print(z is y) # Output: True, because x and y refer to the same object in memory
# The "is not" operator to check whether two variables do not refer to the same object in memory
print(x is not y) # Output: False, because x and y refer to the same object in memory
True
False
Operator keanggotaan#
my_string = "Kang Mas"
# The "in" operator to check whether a certain character is in a string
prin('A' in my_string) # Output: True, because 'A' is in my_string
print('z' in my_string) # Output: False, because 'z' is not in my_string
# The "not in" operator to check whether a certain character is not in a string
print('A' not in my_string) # Output: False, because 'A' is in my_string
print('z' not in my_string) # Output: True, because 'z' is not in my_string
False
False
True
True
4. Control flow#
Statement kondisional#
"""
If statement
"""
x = 10
if x > 5:
print("x is greater than 5")
x is greater than 5
"""
if-elif-else Statement
"""
x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is 10"
else:
print("x is not greater than 15 and not equal to 10")
x is 10
Loop#
# while loop
number = 0
while number<10:
print('Now the number to', number) # pay attention to whitespace
number+=1
print('Done')
Now the number to 0
Now the number to 1
Now the number to 2
Now the number to 3
Now the number to 4
Now the number to 5
Now the number to 6
Now the number to 7
Now the number to 8
Now the number to 9
Done
# for loop
food = ['bread' 'omelet', 'kebab', 'Padang rice', 'duck rice', 'meatballs']
for m in food:
print('I eat', m)
I eat bread
I eat omelet
I eat kebab
I eat Padang rice
I eat duck rice
I eat meatballs
Statement break
& contitue
#
## Break statement
## The break statement is used to exit a loop prematurely.
for num in range(5):
if num == 3:
break
print(num)
0
1
2
## Continue statement
## The continue statement skips the current iteration and continues with the next iteration.
for num in range(6):
if num == 3:
continue
print(num)
0
1
2
4
5
5. Collections#
No |
Data Types |
Description |
Example |
---|---|---|---|
1. |
|
Mutable ordering of objects |
|
2. |
|
Immutable ordering of objects |
|
3. |
|
Unordered collections with no duplication |
{‘banana’, ‘apple’, ‘cherry’} |
4. |
|
Group of couples |
|
List#
"""
Lists are ordered collections that are changeable and allow duplicate elements.
"""
# Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits) # Output: ['apple', 'banana', 'cherry']
# Accessing Elements
print(fruits[0]) # Output: apple
print(fruts[1]) # Output: banana
print(fruits[-1]) # Output: cherry
# Adding Elements
fruits.append("orange")
print(fruits) # Output: ['apple', 'banana', 'cherry', 'orange']
# Removing Elements
fruits.remove("banana")
print(fruits) # Output: ['apple', 'cherry', 'orange']
['apple', 'banana', 'cherry']
apple
banana
cherry
['apple', 'banana', 'cherry', 'orange']
['apple', 'cherry', 'orange']
Tuple#
"""
Tuples are ordered collections that are unchangeable and allow duplicate elements.
"""
# Creating a Tuple
coordinates = (1, 2, 3)
print(coordinates) # Output: (1, 2, 3)
# Accessing Elements
print(coordinats[0]) # Output: 1
print(coordinates[1]) # Output: 2
print(coordinates[-1]) # Output: 3
(1, 2, 3)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[31], line 9
6 print(coordinates) # Output: (1, 2, 3)
8 # Accessing Elements
----> 9 print(coordinats[0]) # Output: 1
10 print(coordinates[1]) # Output: 2
11 print(coordinates[-1]) # Output: 3
NameError: name 'coordinats' is not defined
Set#
"""
Sets are unordered collections that do not allow duplicate elements.
"""
# Creating a Set
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output: {'banana', 'cherry', 'apple'}
# Adding Elements
fruits.add("orange")
print(fruits) # Output: {'banana', 'cherry', 'apple', 'orange'}
# Removing Elements
fruits.remove("banana")
print(fruits) # Output: {'cherry', 'apple', 'orange'}
{'cherry', 'banana', 'apple'}
{'cherry', 'banana', 'orange', 'apple'}
{'cherry', 'orange', 'apple'}
Dictionary#
"""
Dictionaries are collections of key-value pairs.
"""
# Creating a Dictionary
person = {
"name": "Kang Mas",
"age": 33,
"city": "Surakarta"
}
print(person) # Output: {'name': 'Kang Mas', 'age': 33, 'city': 'Yogyakarta'}
# Accessing Values
print(person["name"]) # Output: Kang Mas
print(person["age"]) # Output: 33
# Adding Key-Value Pairs
person["email"] = "kangmas@example.com"
print(person) # Output: {'name': 'Kang Mas', 'age': 33, 'city': 'Yogyakarta', 'email': 'kangmas@example.com'}
# Removing Key-Value Pairs
person.pop("age")
print(person) # Output: {'name': 'Kang Mas', 'city': 'Yogyakarta', 'email': 'kangmas@example.com'}
{'name': 'Kang Mas', 'age': 33, 'city': 'Surakarta'}
Kang Mas
33
{'name': 'Kang Mas', 'age': 33, 'city': 'Surakarta', 'email': 'kangmas@example.com'}
{'name': 'Kang Mas', 'city': 'Surakarta', 'email': 'kangmas@example.com'}
Iterasi untuk setiap collections#
# Iterating Through a List
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating Through a Tuple
coordinates = (1, 2 3)
for coordinate in coordinates:
print(coordinate)
# Iterating Through a Set
fruits = {"apple", "banana", "cherry"}
for fruit in fruits:
print(fruit)
# Iterating Through a Dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
for key, value in person.items():
print(f"{key}: {value}")
apple
banana
cherry
1
2
3
cherry
banana
apple
name: Alice
age: 25
city: New York
6. File I/O dan Error handling#
File I/O#
# Input
name = input("What is your name? ")
age = input("How old are you? ")
print(f"Hello, {name}! You are {age} years old.")
Hello, tyo! You are 90 years old.
Hello, kang mas! You are 99 years old.
# Output to File
f = open("output.txt", "w")
f.write("First line\n")
f.write("Second line\n")
f.write("Third line\n" )
f.close()
# other style
with open("output.txt", "w") as f:
f.write("First line another way\n")
f.write("Second line another way\n")
Error handling#
## Simple Exception Handling
try:
# Receive input from the user
number = int(input("Enter an odd number: "))
# Check if the number is odd
if number % 2 == 0:
raise ValueError("Error: The number must be odd!")
else:
print("Now this is an odd number:", number)
except Exception as error:
# Handle exceptions if the number entered is not odd
print(error)
Now this is an odd number: 9
Error: The number must be odd!
## Exception Handling Complex
try:
# Opening a file for reading
file = open('data.txt', 'r')
# Reading the contents of the file
isi_file = file.read()
# Closing the file
file.close()
except FileNotFoundError:
# Handle exceptions if the file is not found
print("Error: File not found!")
except IOError:
# Handle general exceptions if an error occurs while reading or writing a file
print("Error: An error occurred while reading or writing the file!")
else:
# This block will be executed if no exception occurs
print("File contents:")
print(isi_file)
finally:
# This block will be executed regardless of what happens
print("Program completed.")
Error: File not found!
Program completed.