Dr. Roger Ianjamasimanana

Getting started with Python programming

By Dr. Roger Ianjamasimanana

1. Getting started with Python

To motivate you to get started using Python, you may want to know what makes Python popular and explore its historical overview.

2. Installing Python

Before you start programming, you need to install Python on your computer:

  • Visit the official Python website to download the latest version.
  • Follow the installation steps. Ensure you check the box labeled "Add Python to PATH" during installation.

3. Using the Python console

After installing Python, you can interact with it directly using the Python console. The console is an interactive environment where you type Python commands, and the results are displayed instantly. It’s a powerful tool for beginners to practice Python and for developers to test small code snippets quickly.

3.1 How to open the Python console

  • On Windows:
    1. Press Win + R to open the Run dialog.
    2. Type cmd and press Enter to open the command prompt.
    3. Type python and press Enter. If Python is installed correctly, you will see the Python version and a prompt (>>>).
  • On macOS:
    1. Open the Terminal app from Applications > Utilities or by pressing Cmd + Space and searching for "Terminal."
    2. Type python3 and press Enter.
  • On Linux:
    1. Open the terminal (shortcut keys vary by distribution, e.g., Ctrl + Alt + T for Ubuntu).
    2. Type python3 and press Enter to start the Python console.

3.2 Using the Python console

Once you are inside the console, you can use it like a calculator. Simply type a mathematical expression and press Enter, then Python will evaluate them instantly. For example:

  • >> 5 + 3 # This adds 5 and 3, resulting in 8.
  • >> 10 - 7 # This subtracts 7 from 10, resulting in 3.
  • >> 4 * 6 # This multiplies 4 and 6, resulting in 24.
  • >> 20 / 5 # This divides 20 by 5, resulting in 4.0.

Each command is executed immediately after you type Enter, and the result is displayed on the next line. The Python console is an excellent way to explore basic programming concepts. In the above examples, we have commented our syntax using '#'. Comments are lines in your code that are ignored by the Python interpreter. They are used to explain what the code does to make it easier for others (and yourself) to understand what the program does. In Python, a comment starts with the # symbol.

3.3 Using an IDE or code editor

While the console is great for quick tests, most developers prefer using an Integrated Development Environment (IDE) or code editor for writing and managing Python programs. These tools provide additional features like syntax highlighting, debugging, and autocomplete, making them more efficient for development.

Here are some popular IDEs and editors for Python:

  • Visual Studio Code: A lightweight and highly customizable editor with Python extensions for autocomplete, debugging, and linting.
  • PyCharm: A full-featured IDE specifically designed for Python development. It includes advanced debugging tools, code analysis, and support for frameworks like Django and Flask.
  • Spyder: A scientific Python IDE ideal for data analysis and machine learning, with built-in tools for plotting and data exploration.
  • Jupyter Notebook: A web-based environment that allows you to write and execute Python code in interactive cells, often used for data analysis and visualization.
  • Sublime Text: A lightweight and fast text editor that supports Python and many other programming languages.

Choose the tool that best suits your needs. If you’re new to programming, Visual Studio Code is a great choice for its simplicity and flexibility.

If you like to do it the old way, you can also use vim, which I personally like and use for my code editing.

4. Declaring variables in python

In Python, variables are used to store values that can be reused later in your program. Variables are like labeled boxes that hold information.

How to declare variables in Python?

In many programming languages, you need to specify the type of variable when you declare it (e.g., integer, string). Python simplifies this process:

  • You don’t need to declare a variable's type explicitly. Python automatically determines the type based on the value you assign.
  • You create a variable by assigning it a value using the = operator. For example: a = 10 creates a variable named a and assigns it the value 10.

Examples:

Variable names in Python must follow these rules:

  • They can contain letters, numbers, and underscores (_), but cannot start with a number.
  • They are case-sensitive: Variable and variable are different.
  • They should not use Python keywords like if, else, or print.

4.1 Reserved keywords

In Python, certain words are reserved as keywords and cannot be used for variable or function names. These keywords are integral to the syntax and structure of the language and must be used exactly as defined.

Keywords
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield

4.2 Soft keywords

Soft keywords were introduced in Python 3.10. They are identifiers that only act as keywords in specific contexts. This allows them to be used as normal variable or function names in other situations, ensuring compatibility with existing code. These keywords enhance Python's syntax without breaking backward compatibility.

Soft keywords
match case type _

Note that the match and case keywords are part of the match statement introduced in Python 3.10. As of Python 3.12, type is also treated as a soft keyword under certain conditions.

Python offers a keyword module that allows you to interact with and inspect Python keywords programmatically. This module includes two particularly useful features:

  • kwlist: this provides a complete list of all keywords in the current version of Python you’re using.
  • iskeyword(): this checks if a given string is a Python keyword.

Using keyword.kwlist:

The kwlist attribute in the keyword module lists all the keywords available in your Python environment. You can also use it to determine the total number of keywords defined in your current Python version.

Here's an example:

Using iskeyword():

The iskeyword() function checks if a specific string is a reserved keyword. This can be useful for ensuring that variable names do not conflict with Python’s reserved words.

Here’s how you might use this function:

5. Writing and running a Python code

You can also write Python programs in a file and run them instead of using the console. Here’s how to do this:

  1. Create a text file and save it with the .py extension (e.g., example.py).
  2. Write your Python code in the file. For instance: a = 5; b = 3; print(a + b)
  3. Run the file in the terminal by typing: python example.py

6. Arithmetic operations in Python

Python supports basic arithmetic operations such as addition, subtraction, multiplication, division, and more. Here are some examples:

Operator Operation Description Example
+ Addition Adds two numbers. 5 + 3 = 8
- Subtraction Subtracts the second number from the first. 10 - 7 = 3
* Multiplication Multiplies two numbers. 4 * 6 = 24
/ Division Divides the first number by the second and returns a floating-point result. 20 / 5 = 4.0
// Floor Division Divides the first number by the second and returns the largest integer less than or equal to the result. 20 // 6 = 3
% Modulo Returns the remainder of the division of the first number by the second. 10 % 3 = 1
** Exponentiation Raises the first number to the power of the second. 2 ** 3 = 8

8. Summary

In this lesson, you learned about Python basics, the Python console, variable declaration, and arithmetic operations. With this knowledge, you’re ready to explore more complex programming concepts.

feature-top
Readers’ comment
feature-top
Log in to add a comment
🔐 Access