Python Introduction · Examples
Beginner

Python Introduction Examples

Short, runnable programs that show what is python? in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the What Is Python? lesson.

1Hello, world

The traditional first program: one line, one function call.

Hello, world
print("Hello, world!")
print("Python is running in your browser.")
Expected outputHello, world!
Python is running in your browser.

2Python as a calculator

Arithmetic works directly inside print(), which is handy for checking a quick sum.

Python as a calculator
price = 19.99
quantity = 3
print(price * quantity)
print(round(price * quantity, 2))
print(100 - 15)
print(2 ** 8)
Expected output59.97
59.97
85
256

3Repeating work with a loop

A loop does the same job for every item, so ten items cost the same effort as three.

Repeating work with a loop
tasks = ["wash dishes", "buy milk", "call Asha"]
for number, task in enumerate(tasks, start=1):
    print(number, "-", task)
Expected output1 - wash dishes
2 - buy milk
3 - call Asha

4Converting units

A small script that saves you from doing repeated conversions by hand.

Converting units
kilometres = 42.195
miles = kilometres * 0.621371
print("Marathon:", kilometres, "km")
print("That is about", round(miles, 1), "miles")
Expected outputMarathon: 42.195 km
That is about 26.2 miles

5Text can be calculated too

Strings can be joined with + and repeated with *, so Python is not only about numbers.

Text can be calculated too
title = "Python"
print("I am learning " + title)
print("ha" * 3)
print(len(title))
Expected outputI am learning Python
hahaha
6

6A decision in three lines

Programs can choose what to do. This preview of if shows how readable Python stays.

A decision in three lines
temperature = 31
if temperature > 30:
    print("It is hot, drink water.")
else:
    print("Nice weather.")
Expected outputIt is hot, drink water.

Practise next

What Is Python? exercises → Back to the lesson

Python Syntax examplesPython Variables examplesPython Input and Output examples