Python is a programming language that is easy to read. Its code looks close to everyday language, so it fits learning programming from zero. This tutorial covers the basics: installation, variables, data types, branching, loops, functions, and input/output.
Installing Python
On Arch Linux, install Python with pacman. The command is one line:
sudo pacman -S python
On other operating systems, download the installer from python.org. Pick the latest stable version, then follow the installation steps.
Warning: there are Python 2 and Python 3. They differ and do not match each other. This tutorial uses Python 3. Make sure the command you use is python3, not plain python. On some systems, python still points to the old Python 2.
Check the installed version with this command:
python3 --version
The result should look like Python 3.13.0 (the numbers may differ). If you see “command not found”, Python is not installed yet.
Running Python
There are two ways to run Python. First, interactive mode: type python3 in the terminal with no arguments. The >>> prompt appears, then type code and press Enter. The result shows at once. Leave this mode with exit() or Ctrl+D.
$ python3
>>> print("Halo, dunia!")
Halo, dunia!
>>> exit()
Second, through a file. Save code in a file with the .py extension, then run it from the terminal. Create a file halo.py with this one line:
print("Halo, dunia!")
Run it with this command:
python3 halo.py
The result: Halo, dunia! prints in the terminal. For longer programs, use this file method.
Variables
A variable is a labeled box that stores a value. Write the name, then an = sign, then the value. Python needs no special command to create a variable.
nama = "Briyan"
umur = 25
A variable name may hold letters, numbers, and underscores. It must not start with a number, and it must not hold spaces. Variable names are case-sensitive: nama and Nama are two different variables.
Basic data types
Every value has a type (kind of data). These five basic types are the most common:
str(string): text, written between quotes. Example:“Briyan”.int(integer): whole numbers. Example:25.float: decimal numbers, using a dot not a comma. Example:19.5.bool(boolean): onlyTrueorFalse. The first letter is capital.list: a group of values inside square brackets. Example:[“apel”, “mangga”, “jeruk”].
nama = "Briyan" # str
umur = 25 # int
harga = 19.5 # float
lulus = True # bool
hobi = ["baca", "lari"] # list
Check a data type with type(). For example, type(umur) gives <class ‘int’>.
Take one item from a list by its position (index), starting from 0. hobi[0] is “baca”, hobi[1] is “lari”.
if / else
if runs code only when its condition is true. else runs other code when the condition is false. This is called branching.
umur = 20
if umur >= 18:
print("Boleh masuk")
else:
print("Belum boleh")
Common comparison operators: == (equal to), != (not equal to), > (greater than), < (less than), >= and <=.
Warning: to compare, use == (two equals signs). One equals sign (=) means assigning a value, not comparing. Use the wrong one and the condition becomes always true.
Second warning: Python uses indentation (spaces at the start of a line) to mark a code block. Lines inside if must be indented, usually 4 spaces. Inconsistent indentation makes the program fail. Do not mix tabs and spaces in one file.
for loop
A loop repeats code without writing it many times. Use for when the repeat count is already clear. range(1, 6) gives the numbers 1 to 5 (the last number is not included).
for i in range(1, 6):
print("Hitungan ke-", i)
The result:
Hitungan ke- 1
Hitungan ke- 2
Hitungan ke- 3
Hitungan ke- 4
Hitungan ke- 5
for can also walk through a list, one item at a time:
for buah in ["apel", "mangga", "jeruk"]:
print(buah)
while loop
while repeats code while its condition stays true. Use it when the repeat count is not clear at the start.
angka = 1
while angka <= 3:
print(angka)
angka = angka + 1
Warning: make sure the condition can become false. If not, the loop runs forever (an infinite loop) and the program hangs. Press Ctrl+C in the terminal to stop it.
Functions
A function is a named block of code you can call many times. Write it once, use it anywhere. Create a function with the keyword def, then a name and parentheses. A function can take inputs (parameters) and give back a result (return).
def sapa(nama):
return "Halo, " + nama + "!"
print(sapa("Briyan")) # Halo, Briyan!
print(sapa("Kirana")) # Halo, Kirana!
Call a function by writing its name then parentheses. Fill the parentheses with the values to send. Forgetting the parentheses means the function does not run, you only name it.
Input and output
Show text on screen with print(). Ask the user for input with input(). The text inside the input() parentheses shows as a question.
nama = input("Siapa namamu? ")
print("Halo, " + nama + "!")
Warning: input() always returns text (str), even when numbers are typed. To calculate, convert first with int() (whole numbers) or float() (decimals). Without converting, “10” + “4” gives “104” (texts joined), not 14.
a = int(input("Angka pertama: "))
b = int(input("Angka kedua: "))
print(a + b) # 14 when a = 10 and b = 4
Common mistakes
- Inconsistent indentation: mixing tabs and spaces, or different space counts in one block.
- Using
pythonwhen Python 2 is installed, so Python 3 code fails. - Comparing with
=, when it should be==. - Forgetting the closing quote on a string.
- Adding
input()results withoutint(), so texts join instead. - Misspelling a variable name because of a different capital letter.
If you get stuck, ask Muse (yue) to explain the line that fails. Paste the error message from the terminal so the explanation fits.
Complete example program: greeting and mini calculator
Put it all together in one small program. This program asks for the user’s name, then greets them. Then it asks for two numbers and shows the add, subtract, multiply, and divide results.
Copy the code below into a file called sapa_kalkulator.py, then run it with python3 sapa_kalkulator.py.
nama = input("Siapa namamu? ")
print("Halo, " + nama + "!")
a = int(input("Angka pertama: "))
b = int(input("Angka kedua: "))
print("Tambah:", a + b)
print("Kurang:", a - b)
print("Kali:", a * b)
print("Bagi:", a / b)
Example run, when the name is Briyan and the numbers are 10 and 4:
Siapa namamu? Briyan
Halo, Briyan!
Angka pertama: 10
Angka kedua: 4
Tambah: 14
Kurang: 6
Kali: 40
Bagi: 2.5
How it works: input() reads the name and numbers from the user. int() turns the number texts into whole numbers so they can be calculated. The operators +, -, *, and / do the four operations. Division always gives a decimal (float), so 10 / 4 is 2.5.
Comments