Getting started with Python

Submitted by sylvia.wong@up… on Mon, 06/27/2022 - 18:42
Sub Topics

Python is one of the most requested programming languages for tech companies, and while it is popular now, it did not become widely used until years after it was created.

Python was designed by Guido van Rossum, and it was introduced in 1991. Python 2.0 was released around the end of 2000, and the language became popular because of its adaptability and broad use. Python is now on its third iteration and is used by most of the world's top tech companies.

Learning Python can help you become a software developer, data scientist, or cybersecurity expert.

There are several reasons behind Python's popularity. The most common reasons are that its syntax is easy to read, it is versatile, and there are a lot of libraries and frameworks that extend its functionality. Python developers can expect a good salary, and there is a large, supportive community of Python developers.

Key reasons to learn python include

  • Python is a versatile programming language that can be used for automation, web development, machine learning, and more.
  • Python is an easy programming language to learn, with a syntax that is easy to read.
  • Python has an extensive array of libraries and frameworks that extend its functionality.
  • Python developers are highly in demand and can expect a decent salary.

Python is an interpreted language like PHP or JavaScript, meaning that source code written in Python is converted into bytecode before being executed by the Python virtual machine. This contrasts with major compiled languages, such as C and C++, where the code must be built and linked before it can be executed. This also means that a Python virtual machine must be installed on the system you intend to run your Python code on. For learning purposes, some online IDEs are available that allow you to run Python code in your browser.

During this topic, you will be presented with interactive examples as Repls from Replit.com.

Read more information on installing Python on your own system, following the instruction provided.

Python command

Once Python is installed, you will be able to run Python scripts using the python command followed by a path to a script. You will also have access to the Python shell, which allows you to execute single Python commands and see the results without having to write the code in a file.

The Python shell can be accessed from within the Windows command-line, macOS terminal or often from within an IDE using the command “python”.

The Python prompt is usually indicated with three greater-than symbols and may appear similar to the image below.

During this module, you will be presented with examples intended to be entered line by line into the python shell.

Python notebooks

Python notebooks are web application that contain live code, equations, visualisations, and text. Notebooks are often used to create and share interactive data analysis and visualisation, AI, and machine learning projects, that are powered by Python.

Some popular Notebook platforms include:

Python Comments

Just like any other programming language, commenting your code is important. In Python, a comment is prefixed using a hash symbol # before each line.

It is also possible to create multiline comments by using triple quotes “”” at the beginning and end of the comment. This works because Python will ignore string literals not assigned to a variable.

 

Python Indentation

If you have previously learned other programming languages, you will be familiar with code indentation as an important part of maintaining readability. In Python, indentation is even more important as it is part of the syntax for defining blocks of code.

In other languages, each statement or expression is finished using a semi-colon; and code blocks, like the executable part of an if statement or function are enclosed within curly braces { … }.

In Python, code blocks are indented, and no semi-colons are used at the end of each statement.

 

Variables, Data Types and Operations

Operations

Operators are used to perform operations on variables and values.

Basic mathematical calculations can be performed using arithmetic operators. Addition, subtraction, multiplication, and division are completed using the symbols you might expect.

Mathematical operations and expressions

Basic mathematical calculations can be performed using arithmetic operators. Addition, subtraction, multiplication, and division are completed using the symbols you might expect.

Operator Name Example
+ Addition 7+3, x+y or y+3
- Subtraction 7-3, x-y or y-3
* Multiplication 7*3, x*y or y*3
/ Division 7/3, x/y or y/3

Additional operators include:

Operator Name description
% Modulus remainder of the Euclidean division of two numbers
** Exponentiation raising one number to the power of another
// Floor division normal division operation except that it returns the largest possible integer.

Math package

Variables

Variables are names that represent a value stored in the computer’s memory. They are used to access and manipulate data stored in memory.

Garbage collection is the removal of values that are no longer referenced by variables and is carried out by the Python interpreter.

A variable can refer to an item of any type. A variable that has been assigned to one type can be reassigned to another type.

A diagram showing different types of variables

Variables and data assignment

Assignment statements are used to create variables and make references data.

Syntax: variable = expression

Example: age = 29

the equal sign (=) is an assignment operator.

In an assignment statement, the variable receiving value must be on the left side. Variables can be passed as arguments to functions. Variable names should not be enclosed in quote marks. You can only use a variable if a value is assigned to it.

Variables can reference different values while a program is running.

Variable naming

Rules for naming variables in Python:

  • Variable names cannot be a Python keyword
  • Variable names cannot contain spaces
  • The first character must be a letter or an underscore
  • After the first character you may use letters, digits, or underscores
  • Variable names are case sensitive
  • Variable names should reflect their use.

Data Types

Data types categorize values in memory. For example, int for integer, float for real number, str used for storing strings in memory.

A numeric literal is a number written in a program with no decimal point it is considered an int (integer), otherwise, it is considered a float. Some operations behave differently depending on data type.

The following video introduces Python variables and datatypes, with some common naming conventions.

A developer working on a laptop

Operators

Operators are special symbols used to perform operations (computations) on variables and values.

Basic mathematical calculations can be performed using arithmetic operators. Addition, subtraction, multiplication, and division are completed using the symbols you might expect.

There are 7 common types of operators used in Python.

  • Arithmetic Operators
  • Logical Operators
  • Assignment Operators
  • Relational Operators
  • Bitwise Operators
  • Identity Operators
  • Membership Operators

Let’s discuss some of these operators stating with Arithmetic and Logical Operators

Arithmetic operators and expressions

Python has so many built-in operators to perform different arithmetic and logical operations. Arithmetic operators are used to perform mathematical operations. See some examples below:

Table 1

Operator Name Example
+ Addition 7+3, x+y or y+3
- Subtraction 7-3, x-y or y-3
* Multiplication 7*3, x*y or y*3
/ Division 7/3, x/y or y/3

Additional operators include:

Table 2

Operator Name Description
% Modulus remainder of the Euclidean division of two numbers
** Exponentiation raising one number to the power of another
// Floor division normal division operation except that it returns the largest possible integer.

You can run the following examples in your replit notebook:

 

Logical Operators

Logical operators are used to check whether an expression is True or False. For example, you can use them test boolean expression or object, especially when you need to make logical decisions in your program.

Table 3

Operator Example Description
and x and y Logical AND: True only if both the operands are True
or x or y Logical OR: True if at least one of the operands is True
not not x Logical NOT: True if the operand is  False  and vice-versa.

Bitwise Operators

Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. Let’s see some examples. We are using operands x and y, where x = 10 (00001010) and y = 4 (00000100). The following operators are supported:

Table 4

Operator Example Description
& x & y = 0 (0000 0000) Bitwise AND
| x | y =  14  (0000 1110) Bitwise OR
~ ~x = -11 (1111 0101) Bitwise Not
^ x^y = 14 (0000 1110) Bitwsue Xor
>> x >>2 = 2 (0000 0010) Bitwise right shift

For example, run the following examples in your replit notebook to see the results (1 is 01 in binary and 2 is 10 – we want to apply bitwise operators in Python):

 

Relational Operators:

Relational operators in Python are used to compare values. See some examples below with descriptions:

Table 5

Operator Example Description
< x < y x is less than y
> x > y x is greater than y
<= x <= y x is less than or equal to y
>= x >= y x is greater than or equal to y
== x == y x is equal to y
!= x != y x is not equal to y

Membership Operators

In Python, membership operators are mainly useful to test for membership in a sequence such as lists, strings or tuples, set and dictionary. See examples below:

 

Table 6

Operator Example Description
in print(y in x) in membership operator returns true if value/variable is found in the sequence and returns false otherwise
not in print( y not in x) not in membership operator returns true if value/variable is not found in the sequence and returns false otherwise

Precedence of Python Operator

&Python expressions are made up of variables, operators, values, etc. When the Python interpreter encounters an expression with many operations, each operation is evaluated in accordance with an ordered hierarchy known as operator precedence.

Python Operators Precedence Table

Listed below is the table of operator precedence in Python, increasing from top to bottom and decreasing from bottom to top:

Table 7

Operator Description
:= Assignment expression
lambda Lambda expression
if-else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
<, <=, >, >=, Relational or comparison operators
!=, == Equality operators
in, not in, is, is not, Identity operators, membership operators
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Left and right Shifts
+, – Addition and subtraction
*, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
+x, -x, ~x Unary plus, Unary minus, bitwise NOT
** Exponentiation
await x Await expression
x[index], x[index], x(arguments…), x.attribute Subscription, slicing, call, attribute reference
() Parentheses (Highest precedence)

Let's consider a simple example:

Suppose we want to construct an if...else block which runs if when lunch is either fruit or sandwich and only if money is more than or equal to 2.

 

As you can see, the if block was evaluated to be True even though money was set to 0 (less than 2). This is because the precedence of and is higher than that of or ( see the precedence table). If we evaluate the and side first (meal == "sandwich" and money >= 2), we have a logical false. We are left with meal == "fruit" or false, if we evaluate this, it will be True, hence why we have the result.

This is not the result we want, so we can modify the output by adding parentheses (), which would change the order of precedence:

 

The parentheses () have higher order of precedence to and , hence , it will be evaluated first.

Order of Operations for Arithmetic Operators

The abbreviation BEDMAS can be used to recall the arithmetic operators' order of operations. The words that make up the acronym let us know which operator comes first:

B= Bracket

E = Exponentiation

D = Division

M = Multiplication

A = Addition

S = Subtraction

By using the acronym, we can see that in Python, the operator with brackets comes before the exponentiation operation. The same logic applies to each of the operators, down to the subtraction operator.

In the case of tie means, if two operators whose precedence is equal appear in the expression, then the associativity rule is followed.

Associativity Rule of Python Operators

As shown in table 7, more than one operator exists in the same precedence order or group. The precedence for these operators is the same.

Associativity helps in determining the sequence of operations when two operators have the same precedence.

When multiple operators share the same precedence in an expression, associativity determines the order in which those operators are evaluated. Almost all the operators have left-to-right associativity.

Let us see an example:

 

For instance, floor division and multiplication have the same precedence. Because of this, the left one gets evaluated first if both of them are contained in an expression.

Non associative operators

In Python, some operators lack associativity, including assignment operators and comparison operators. Sequences of this type of operator have their own rules and cannot be expressed as associative.

For example, x < y < z neither means (x < y) < z nor x < (y < z).

x < y < z is equivalent to x < y and y < z, and is evaluated from left-to-right.

In addition, while chaining of assignments like x = y = z = 1 is perfectly valid, x = y = z+= 2 will result in error.

Note that Exponent operator ** has right-to-left associativity in Python.

See the compiled examples below.

Module Linking
Main Topic Image
A close up of a screen with code displayed
Is Study Guide?
Off
Is Assessment Consultation?
Off