Registered non-governmental non-profit organisation certificate No. 1052p

Articles

Python: your first steps

15 min read

Python from scratch: installation, print and input, variables, conditions, loops, lists, functions, reading error messages and a quiz project.

Want to learn to program but not sure where to start? For many people the easiest first language is Python. In this guide we explain what Python is and why it suits beginners, install it on your computer (or try it in the browser without installing anything), write a first program and work through the core ideas with examples: variables and data types, getting input from the user, arithmetic, conditions, loops, lists and functions. Then we learn to read error messages, build a simple quiz program step by step and finish with practice tasks and a checklist. No prior experience is needed: being comfortable using a computer is enough.

What Python is and why it suits beginners

Python is a general-purpose programming language. It is used for the server side of websites, data analysis, automating everyday work, artificial intelligence and educational software. Python is free, runs on all major operating systems and has a large community around the world.

Why Python is a comfortable place to start:

  • Readable syntax. Python code looks close to plain English sentences. There are no extra braces or semicolons.
  • Quick results. You write one line and see the result straight away. That helps you stay motivated.
  • Wide use. Once you know the basics, you can move into data analysis, web development or automation, and the language stays the same.
  • Plenty of learning material. Answers to almost any question are easy to find, and the error messages are written clearly.

If you are still wondering what programming involves and which direction to choose, read our article on getting started with programming first.

Installation and your first program

Installing on Windows

  1. Open python.org in your browser and download the latest stable version for Windows from the Downloads section.
  2. Run the installer. At the bottom of the first window there is a checkbox labelled Add python.exe to PATH: make sure you tick it. Without it, the command line will not “recognise” Python.
  3. Click Install Now and wait for the installation to finish.
  4. Open Command Prompt (or Terminal) from the Start menu and type:
python --version

If a version number appears, everything is fine. For newer Python versions, python.org may also offer a new Windows installer called the “Python install manager”; you can follow its instructions instead. What matters is that the command above works at the end.

macOS and Linux

  • macOS. Download the macOS installer from python.org and install it like any other app. In Terminal the command is python3: python3 --version.
  • Linux. Most distributions come with Python already installed. Check with python3 --version in the terminal. If it is missing, on Ubuntu and similar systems you can install it with sudo apt install python3.

Trying it in the browser without installing

If you are on a work computer or are not allowed to install software, use an online environment. Google Colab, for example, is a free service you sign in to with a Google account: you open a new notebook, type code into a cell and run it with Shift + Enter. There are other online Python interpreters too. They are perfectly adequate for the first few weeks, but for serious study it is better to install Python on your own computer.

Your first program

Python comes with a simple editor called IDLE. Open it, choose File → New File and type:

print("Hello, world")
print("My name is Dilnoza")

Save the file as salom.py and choose Run → Run Module (F5). Two lines appear on the screen. print() is a function that displays whatever is inside the brackets. Text goes inside quotation marks. Later you can switch to a more convenient editor such as Visual Studio Code, but IDLE is enough to get started.

Variables, data types and input

Variables

A variable is a name given to a value. Think of it as a labelled box you put something into:

name = "Jasur"
age = 19
height = 1.78
is_student = True

print(name)
print(age)

The = sign does not mean “equals” as in maths; it means “attach the value on the right to the name on the left”.

Four basic types

  • str (string): text, such as "Jasur" or "Tashkent". Always in quotation marks.
  • int (integer): whole numbers such as 19, -5 or 2026.
  • float (floating-point number): 1.78, 0.5. The decimal part is separated by a full stop, not a comma.
  • bool (Boolean): only True or False, with a capital letter.

You can find out a value’s type with the type() function: print(type(age)) displays <class 'int'>.

Getting input from the user

The input() function returns the text the user typed on the keyboard. An important point: it always returns a string (str), even if the user types a number. To calculate with it, convert it to a number with int() or float():

name = input("What is your name? ")
birth_year = int(input("Year of birth: "))

age = 2026 - birth_year
print("Hello,", name)
print("This year you turn", age)

If you pass several values to print() separated by commas, a space is added between them automatically. Another handy way to put a value into text is an f-string: print(f"Hello, {name}"). The name inside the curly brackets is replaced by its value.

Arithmetic and conditions

Arithmetic operations

a = 17
b = 5

print(a + b)   # 22 - addition
print(a - b)   # 12 - subtraction
print(a * b)   # 85 - multiplication
print(a / b)   # 3.4 - division, the result is always a float
print(a // b)  # 3 - whole part
print(a % b)   # 2 - remainder
print(a ** 2)  # 289 - raising to a power

Note that 10 / 2 gives 5.0, not 5: ordinary division always returns a float. The order of operations is the same as in maths: multiplication and division first, then addition and subtraction. If in doubt, add brackets.

Conditions: if, elif, else

For a program to behave differently depending on the situation, you need conditions. For example, let us give a grade based on a test result (the marks are illustrative):

score = int(input("Test score (0-100): "))

if score >= 86:
    print("Excellent")
elif score >= 71:
    print("Good")
elif score >= 56:
    print("Satisfactory")
else:
    print("More preparation needed")

Python checks the conditions from top to bottom and runs the first one that is true. Notice that each condition ends with a colon :, and the lines inside are indented by 4 spaces. In Python this indentation is not decoration: it is the rule that shows which block a line belongs to.

Comparison operators: == (equal to), != (not equal to), >, <, >=, <=. A single = assigns a value, while a double == compares; this is where beginners slip up most often. Conditions can be combined with and, or and not: if age >= 18 and has_passport:.

Loops and lists

for and range

A loop repeats the same action many times. range(1, 6) gives the numbers 1 to 5 (6 is not included):

for day in range(1, 6):
    print(f"Day {day}: 30 minutes of practice")

range(5), on the other hand, gives 0 to 4. If you do not give a starting number, counting begins at zero, which is normal in programming.

while

A while loop repeats as long as a condition is true. It is useful when you do not know in advance how many repetitions you need:

password = ""
while password != "apple123":
    password = input("Enter the password: ")
print("Welcome")

Be careful: if the condition never becomes false, the loop runs forever. To stop such a program, press Ctrl + C.

Lists (list)

A list stores several values in order. Items go inside square brackets, separated by commas, and are numbered from zero:

fruits = ["apple", "pomegranate", "grape"]

print(fruits[0])      # apple
print(fruits[-1])     # grape - the last item
print(len(fruits))    # 3 - number of items

fruits.append("quince")       # add to the end
fruits.remove("pomegranate")  # remove by value
fruits[0] = "pear"            # replace an item
print("grape" in fruits)      # True - check membership

for fruit in fruits:
    print(fruit)

Useful functions for lists of numbers: sum() adds up the items, min() and max() give the smallest and largest values, and sorted() returns a sorted copy. For example, with steps walked over a few days (illustrative numbers) steps = [5200, 8100, 4300], the expression print(sum(steps) / len(steps)) displays the average.

Functions and tidy code

def and return

A function is a named, reusable piece of code. It is created with the word def, and return sends back the result:

def average(numbers):
    """Return the average of the numbers in a list."""
    return sum(numbers) / len(numbers)


def greet(name):
    print(f"Hello, {name}. Welcome to the lesson")


grades = [5, 4, 5, 3]
print(average(grades))   # 4.25
greet("Sardor")

print() only displays a result on the screen, while return hands it back to another part of the program, where you can store it in a variable or use it in a calculation. If you find yourself writing the same code in two or three places, it is time to turn it into a function.

Rules for clean code

  • Clear names. Not x or a1, but total_score and birth_year. Names use Latin letters, lower case, with words separated by underscores. English names are the usual convention, though Uzbek names in Latin script work too; what matters is consistency.
  • Comments. Python ignores any text after the # sign. Use comments to explain not “what” the code does but “why” it is written that way.
  • 4 spaces. Every nested block is indented by 4 spaces. Do not mix tabs and spaces; many editors insert 4 spaces automatically when you press Tab.
  • Blank lines. One between logical parts, two between functions.

Reading errors and common mistakes

An error message is not a punishment; it is Python telling you where the problem is. Read it from the bottom up: the last line gives the error type and reason, and above it are the file name and line number. There is more on handling errors in the glossary entry on bugs and debugging.

SyntaxError: the writing rules are broken

if score > 50
    print("Passed")

Python reports SyntaxError: expected ':' because the colon at the end of the condition is missing. The fix: if score > 50:. An unclosed quotation mark or bracket causes the same error.

NameError: name not found

pirnt("Hello")

Result: NameError: name 'pirnt' is not defined. Newer versions even suggest Did you mean: 'print'?. The cause is a typo in the name or using a variable before it has been created. Python is case-sensitive: Name and name are two different names.

IndentationError: indentation problem

for i in range(3):
print(i)

Result: IndentationError: expected an indented block. Indent the print(i) line inside the loop by 4 spaces.

TypeError: incompatible types

age = 25
print("Age: " + age)

Result: TypeError: can only concatenate str (not "int") to str: you cannot add a number to a string with +. The fix: print("Age:", age) or print("Age: " + str(age)).

Other common mistakes

  • Forgetting to convert the result of input() with int(): "5" + "3" gives "53", not 8.
  • Typing letters instead of a number: int("five") → ValueError. This is not a bug in the code but a problem with the input; later you will learn to check it.
  • Mixing up = and == in a condition.
  • Counting list indexes from one: in a three-item list, fruits[3] → IndexError.
  • Running a file without saving it and being puzzled by the old result.

A small project: a quiz, step by step

Let us bring everything together and write a three-question quiz. Each correct answer earns 1 point.

Step 1. One question. input() and if are enough. .strip() removes extra spaces and .lower() converts the text to lower case, so “Tashkent”, “tashkent ” and “TASHKENT” all count as the same:

reply = input("What is the capital of Uzbekistan? ")
if reply.strip().lower() == "tashkent":
    print("Correct")
else:
    print("Wrong")

Step 2. Several questions and a score. We keep the questions in a list: each item is a nested list of a question and its answer. A for loop asks them one by one.

Step 3. A function. We move asking the question and checking the answer into a separate function.

Step 4. A final verdict. Depending on the result, we display a comment using if/elif/else. The finished program:

# Quiz: 1 point for every correct answer

questions = [
    ["What is the capital of Uzbekistan?", "tashkent"],
    ["How many days are there in a week?", "7"],
    ["Which Python function displays text on the screen?", "print"],
]


def ask(question, answer):
    """Ask the question and return True if the answer is correct."""
    reply = input(question + " ")
    return reply.strip().lower() == answer


score = 0
for item in questions:
    if ask(item[0], item[1]):
        print("Correct")
        score = score + 1
    else:
        print("Wrong. The correct answer is:", item[1])

print(f"Result: {score} / {len(questions)} points")

if score == len(questions):
    print("Excellent, all correct")
elif score > 0:
    print("Not bad, try again")
else:
    print("Review the questions and try again")

Run the program, give some wrong answers on purpose and check that every branch works. Then add your own questions: adding a line to the list is all it takes, and the rest of the code stays the same. That is the power of lists and functions.

Practice, checklist and next steps

Practice tasks

  1. Introductions. Ask the user for their name and city and display a sentence such as “Hello, Aziza. Samarkand is a beautiful city”.
  2. Calculator. Ask for two numbers and display their sum, difference, product and quotient.
  3. Even or odd. Use % and if to decide whether the number entered is even or odd.
  4. Times table. For a number the user enters, display its times table from 1 to 10 using for.
  5. Daily expenses. Put a week of expenses (illustrative numbers) into a list and use a function to work out the total, the average and the largest expense.

Checklist

  • Python is installed and python --version works (or an online environment is ready).
  • I know the difference between print() and input(), and I convert the result of input() with int().
  • I can tell str, int, float and bool apart.
  • I do not forget the colon and the 4 spaces in if/elif/else.
  • I can use for, range() and while, and I can leave an endless loop with Ctrl + C.
  • I know lists are numbered from zero, and I use append, remove and len.
  • I write functions with def and return results with return.
  • I read error messages from the bottom up and look at the line number.

Next steps

Once you have the basics, move on to dictionaries (dict), working with files, modules and catching errors with try/except. Write code every day, even a little: half an hour of regular practice a day does more good than one long session a week. Put small projects (a quiz, a list, a counter) on GitHub and gradually build a portfolio. As a next direction you can choose web development or working with data: Python is one of the main tools in both.

If you would like to study Python and programming systematically with a teacher, take a look at our association’s free programming and data analytics courses and our other training programmes. When you are ready, submit an application and our specialists will get in touch.

Back to articles

More articles

14 min read

Using AI tools responsibly at work

What AI chat assistants are good for at work, how to write a good prompt, how to check the output and which data never to type in.

15 min read

Algorithmic thinking: the step before coding

Breaking problems down, patterns and abstraction, conditions and loops, pseudocode and flowcharts, simple tasks and tracing by hand, plus practical exercises.

Start learning today

Enrollment is open. Leave an application — our specialists will contact you and help you choose the right field.

Message us on Telegram