Join Our Free Python Webinar
Lesson 2, Topic 1
In Progress

Introduction To Python Code

Lesson Progress
0% Complete

The Python programming language has a number of fundamental components that are used to write Python code. We will introduce some of these components, namely, objects, classes, functions, and methods. We will also see how the Python code is organized into statements and how it is saved in a script file.

Python Objects

Python objects are generally (not always) used to model, or simulate, the real world. For example, if we have to write Python code for a car racing video game, then we would probably create an object for each player of the game to store his session. This object will store the name of the player, the cars he has won or unlocked throughout the game, the race tracks he has completed, etc. We would also create an object for each car that he wins. This object will store the car’s make and model, its top speed, its photo, etc.

Objects are the most fundamental component of the Python programming language, and almost everything in Python is an object. They are generally used to store data, as displayed in the car racing example above. Once they are created, they can interact with each other to produce a certain output.

The programming model that relies on objects to write code is called object-oriented programming. Object oriented programming, abbreviated as OOP, is a programming approach, or technique, for solving coding problems by breaking them into smaller pieces called objects. The programming languages that use this approach are called object-oriented languages, and Python is one of them.

After knowing the importance of objects in Python, you may wonder how are they created? Here comes the role of classes.

Python Classes

In Python, the creation of objects is a two-step process: we first create a class, then we create objects from it. A class is like a template, or blueprint, from which objects are created: it defines the data that each object will contain, in addition to other information.

When an object is created from a class, we say that the class is instantiated and that the object is an instance of it. When we write Python code, classes are defined once but can be instantiated as much times as the code requires. In other words, we can create any number of objects from a single class.

If we return to the car racing example above, the code of the game would probably contain a class named “Car”, and each time the player wins or unlocks a car, a new object of type “Car” is created:

The “Car” class is considered as the type of the objects that are created from it. For example, in the diagram above, “Car 1” is an object of type “Car”. More generally, a class is called a data type because objects are considered as data items, and the type of these items is naturally the class from which they were created. So, data types are the classification of data items (objects), and every data item (object) in Python must have a data type.

Note: The terms “class” and “data type” will be used interchangeably in this course because they mean exactly the same thing in Python.

There are two categories of data types, or classes, in Python:

  • User-defined data types, which are the data types that you create in your Python programs.
  • Built-in data types, which are the data types created for you by the people who developed the Python programming language.

Python's Built-in Data Types

Python comes with several built-in data types that are extensively used in Python programs. These data types were created for you by the developers of the Python language to facilitate your coding experience. They are called “built-in” because they are built into the Python interpreter. The Python interpreter will be defined in the next section.

Here are the most commonly used built-in data types:

  • Integers, which are negative and positive whole numbers. Examples of integers are: -3 , -1 , 0 , 2 , 5.
  • Floats, which are negative and positive numbers with a fractional part. Examples of floats are: -7.125 , -2.59 , 0.0 , 1.9 , 4.8763.
  • Strings, which are sequences of characters that can contain any combination of these elements: letters, numbers, punctuation marks, and symbols. Examples of strings are: “B” , “Flowers” , “Hello Python!” , “xyz+0123456789”.
  • Boolean values, or simply Booleans, which are the two values: True and False. They are used to represent the two possible truth values: true and false. The letters T and F, of True and False, must be capitalized.
  • Lists
  • Tuples
  • Dictionaries
  • Sets
  • Ranges

There are still other built-in data types in addition to those listed above. All built-in data types will be covered in detail in this course.

The objects of some built-in data types are called literals. For example:

  • The objects 0, 1, and 2 are called integer literals.
  • The objects 0.0, 1.1, and 2.2 are called floating-point literals.
  • The objects “Flowers” and “Python” are called string literals.
  • The objects True and False are called Boolean literals.

Functions

A Python function is a named block of code that performs a specific task by taking some input, processing it, and producing some output.

Python functions are similar in concept to mathematical functions. For example, the function f(x) = 2x+1 takes an input x, performs a calculation, and returns a result. This is the same principle of Python functions but with slight differences.

Similar to data types, there are two categories of functions in Python:

  • User-defined functions, which are the functions that you create in your Python programs.
  • Built-in functions, which are the functions created for you by the developers of the Python language. These functions are built into the Python interpreter. The latest version of Python, version 3.10 as of this writing, provides the following built-in functions:

Once a function is created, it can be executed by giving it some input. When we do this, we say that we are calling, or invoking, the function. Here is the syntax for calling, or invoking, a function:

function(Argument 1, Argument 2, , Argument N)

Where:

  • function is the name of the function to be called or invoked.
  • Argument 1, 2, , N are the function’s input. They specify what information, if any, must be provided in order to execute the function. A function call takes zero or more arguments as an input. These arguments must be comma-separated, and enclosed in parentheses. Even if the function call takes no arguments, the parentheses () after function are still required.

Functions are one of the fundamental components of Python. At the beginning of this course, we will focus on Python’s built-in functions. After that, a whole chapter will be devoted to user-defined functions.

Methods

A Python method is basically a function; both of them perform a specific task by taking some input, processing it, and producing some output. However, the difference between the two consists in the input that they can take. In fact, a method is a function defined inside a class and consequently, its input is restricted to that data type. On the other hand, a function doesn’t have this restriction because it is an independent entity and theoretically, it can take any data type as input.

A Python method is a function defined inside a class.

To better understand methods, we will return to the car racing example. To control the speed of the car, we would probably define two methods named accelerate() and brake() inside the “Car” class. Just like functions, these methods will perform some tasks, however, their input will be restricted to the “Car” data type. We say that these methods are associated with the “Car” data type.

In the Python Classes section it was mentioned that “a class defines the data that each object will contain, in addition to other information”. The term “other information” here means methods, so, a class combines data and methods into one entity. For example, the “Car” class can be defined as follows:

Similar to data types and functions, there are two categories of methods in Python:

  • User-defined methods, which are the methods that you create in your Python programs.
  • Built-in methods, which are the methods associated with built-in data types. These methods are created for you by the developers of the Python language and are built into the Python interpreter.

Python Statements

The structure of Python code resembles that of an English text. In fact, an English text is made up of a series of sentences. Similarly, a Python code is made up of a series of statements. So, from a structural perspective, a statement in Python is similar to a sentence in English.

From a functional perspective, a statement is an instruction that the programmer gives to the computer to perform an operation. For example, classes, functions, and methods are all composed of statements.

A Python statement is a command that instructs the computer to perform an operation. The Python code is a sequence of statements.

Python statements are organized into lines; generally one statement per line:

In the simplest scenario, these statements will be executed in sequence, from top to bottom. For example, in the diagram above, the statement 1 will be executed first, then the statement 2, and so on, until the statement N. This process is called sequential execution and it is characterized by the execution of statements, one after another, in the same order in which they appear in the code.

However, in real-world scenarios, things can be (and usually are) more complex, and the order of execution may not be the same as the order of statements. For example, a block of statements can be executed multiple times, or it can even be skipped.

In all cases, the flow of execution (see the diagram above) will always be the same; from the top of the code to the bottom.

Python Expressions

A Python expression is a piece of code that, when executed, returns a value. This execution is called evaluation. We also say that an expression evaluates to a value. Generally, an expression contains one or more of these elements:

  • Values: these are the values of Python objects. In fact, in Python, every object has a value. Examples of values are integers, floats, strings, Booleans, etc.
  • Operators: Python supports a wide variety of operators. Here are some examples:
    • Arithmetic operators: addition (+), subtraction (-), multiplication (*), division (/), etc.
    • Comparison operators: greater than (>), greater than or equal to (>=), less than (<), less than or equal to (<=), etc.
    • Logical operators: and, or, not.
  • Variables: will be defined later in this course.
  • Functions calls: In Python, a function call always returns a value; therefore, it can be used in an expression or it can form an expression by itself.

There are multiple types of expressions in Python, among them we can cite:

  • Arithmetic expressions, which are expressions that use arithmetic operators and evaluate to a numeric value. A numeric value can be an integer, float, or complex number. Example: 12.5 / (2 * 3.6) + 44.5 – 0.125.
  • Integer expressions, which are expressions that evaluate to an integer value. They are a special case of arithmetic expressions. Example: 1 – 4*5 + 10*10 – 10.
  • Boolean expressions, which are expressions that evaluate to a Boolean value (either True or False). Example: 17 >= 10 or 42 < 8.
  • String expressions, which are expressions that evaluate to a string value. Example: “Hello Python!”.

A Python statement can contain one or more expressions. When this statement is executed, any expression will be replaced by its relative value. For example, an arithmetic expression will be replaced by its result, a function call will be replaced by the value it returns, etc.

A Python statement can also be an expression at the same time, in which case it is called an expression statement. For example, a statement that contains only a function call is an expression statement.

Expressions statements are statements and expressions at the same time.

Note: There are two main differences between Python statements and expressions:

  • Statements can contain expressions whereas expressions cannot contain statements.
  • Statements do not evaluate to a value; they simply perform an operation, whereas expressions always evaluate to a value. The exception to this rule are expression statements which are statements/expressions that evaluate to a value.

Comments

Comments are notes written in English, or in any other language, that are generally used to explain a Python code and/or to specify its purpose. They make the code more readable and developer-friendly.

Comments are non-executable statements. Therefore, they do not affect the output of a Python program, which will produce the same output with or without them. They are for humans to read, not for computers to execute.

Comments can be written in single lines or multiple lines.

Single-Line Comments

A single-line comment is a line of text that starts with the hash sign #, also called the number sign or the pound sign. It is usually a brief note about the code, and can be written in two ways:

  • On a separate line:
# This is a comment.
  • On the same line as the statement, after it. Such a comment is called inline comment:
Statement  # This is an inline comment.

In both cases, Python will ignore all the text after the hash sign # and move to the next statement.

Multiline Comments

A multiline comment is a block of lines that all start with the hash sign # (i.e. a block of single-line comments). It can be used to write a lengthy note about the code:

# The first line of the comment.
# The second line of the comment.
# The third line of the comment.

Multiline comments can also be used to test and fix Python programs. For example, let’s suppose that the output of your program is not as expected, and you are suspecting that a given block of code is causing the issue. In this case, you can comment this block to prevent its execution, then see if the issue is resolved:

# Statement 1
# Statement 2
# Statement 3

Note 1: Python doesn’t provide a separate way to write multiline comments. This is unlike other programming languages which use different syntaxes for single-line and multiline comments. For example, the C++ language uses // for single-line comments and /* */ for multiline:

// This is a single-line comment in C++

/* This is a multiline
comment in C++ */

Note 2: It was mentioned earlier that Python ignores all the text after the hash sign #. We will see later that there are some exceptions to this rule.

Note 3: Comments will be used extensively in this Python course to clarify the newly learned concepts.

Python Scripts

When you want to write Python code, all you need is a text editor. Most modern operating systems come with a built-in text editor, but there are also multiple free ones on the internet. So, open your favorite text editor and start writing Python code. Your first code will contain two statements: a comment and a function call with the print() built-in function. We will run this code later in this course:

# This is my first Python code.

print("Hello Python!")

Copy the above code and paste it on your text editor:

Save this file with a .py extension. For example, you can name it Hello.py:

The file you just created is called a Python script. In fact, a Python script is a text file containing Python code, and by convention, it should have the .py file extension (.py is short for Python). Once created, a script is ready to be executed and here comes the role of the Python interpreter.