Introduction

Python is a high-level, general-purpose and a very popular programming language. Python programming language (latest Python 3) is being used in web development, Machine Learning applications, along with all cutting edge technology in Software Industry. Python Programming Language is very well suited for Beginners, also for experienced programmers with other programming languages like C++ and Java.

Below are some facts about Python Programming Language:

Download and Install

Here we will be discussing how to get the answer to all questions related to installing Python on Windows/Linux/macOS. Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.10.4, we can simply call it Python3.

In this Python tutorial on Installation and Setup, you’ll see how to install Python on Windows, Linux and macOS.

How to install Python on Windows?

Since windows don’t come with Python preinstalled, it needs to be installed explicitly. Follow the steps below:

How to install Python on Linux?

If Python is not already installed on your Linux system, or you want to install an updated version, follow the steps below:

How to install Python on macOS?

Getting Started

In order to start Python programming, we need to have an interpreter to interpret and run our programs. There are certain online interpreters like https://ide.geeksforgeeks.org/ that can be used to run Python programs without installing an interpreter. Python IDLE is the Python Integration Development Environment (IDE) that comes with the Python distribution by default and helps you experiment with Python quickly in a trial-and-error manner. For each operating system:

Hello World

The following shows you step by step how to launch the Python IDLE and use it to execute the Python code:

Python Keywords

Keywords in Python are reserved words that can not be used as a variable name, function name, or any other identifier. Let's check each one:

Statements

Instructions written in the source code for execution are called statements. There are different types of statements in the Python programming language like Assignment statements, Conditional statements, Looping statements, etc. These all help the user to get the required output. For example, n = 50 is an assignment statement.

Multi-Line Statements: Statements in Python can be extended to one or more lines using parentheses (), braces {}, square brackets [], semi-colon (;) or continuation character slash (\).

Indentation

A block is a combination of all these statements. Block can be regarded as the grouping of statements for a specific purpose. Most of the programming languages like C, C++, and Java use braces { } to define a block of code. One of the distinctive features of Python is its use of indentation to highlight the blocks of code. Whitespace is used for indentation in Python. All statements with the same distance to the right belong to the same block of code. If a block has to be more deeply nested, it is simply indented further to the right.

To indicate a block of code in Python, you must indent each line of the block by the same whitespace.

Variables

A variable is a named location used to store data in the memory. It is helpful to think of variables as a container that holds data that can be changed later in the program.

Methods to assign values to variables

Constants

A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as containers that hold information which cannot be changed later.

In Python, constants are usually declared and assigned in a module. Inside the module, constants are written in all capital letters and underscores separating the words. Example below:

import constant

>> PI = 3.14>> GRAVITY = 9.8>> print(constant.PI) >> print(constant.GRAVITY)

Output:

3.149.8

Note: In reality, we don't use constants in Python. Naming them in all capital letters is a convention to separate them from variables, however, it does not actually prevent reassignment.

Operators

Python Operators in general are used to perform operations on values and variables. These are standard symbols used for the purpose of logical and arithmetic operations. Following, we will look into different types of Python operators.

Arithmetic Operators

Arithmetic operators are used to performing mathematical operations like addition, subtraction, multiplication, and division.

Operator Description
+ Addition: adds two operands
- Subtraction: subtracts two operands
* Multiplication: multiplies two operands
/ Division (float): divides the first operand by the second
// Division (floor): divides the first operand by the second
% Modulus: returns the remainder when the first operand is divided by the second
** Power: Returns first raised to power second

Comparison Operators

Comparison of Relational operators compares the values. It either returns True or False according to the condition.

Operator Description
> Greater than: True if the left operand is greater than the right
< Less than: True if the left operand is less than the right
== Equal to: True if both operands are equal
!= Not equal to – True if operands are not equal
>= Greater than or equal to True if the left operand is greater than or equal to the right
<= Less than or equal to True if the left operand is less than or equal to the right
is x is the same as y
is not x is not the same as y

Logical Operators

Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine conditional statements.

Operator Description
and Logical AND: True if both the operands are true
or Logical OR: True if either of the operands is true
not Logical NOT: True if the operand is false

Bitwise Operators

Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on binary numbers.

Operator Description
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
^ Bitwise XOR
>> Bitwise right shift
<< Bitwise left shift

Assignment Operators

Assignment operators are used to assign values to the variables.

Operator Description
= Assign value of right side of expression to left side operand
+= Add AND: Add right-side operand with left side operand and then assign to left operand
-= Subtract AND: Subtract right operand from left operand and then assign to left operand
*= Multiply AND: Multiply right operand with left operand and then assign to left operand
/= Divide AND: Divide left operand with right operand and then assign to left operand
%= Modulus AND: Takes modulus using left and right operands and assign the result to left operand
//= Divide(floor) AND: Divide left operand with right operand and then assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value using operands and assign value to left operand
&= Performs Bitwise AND on operands and assign value to left operand
|= Performs Bitwise OR on operands and assign value to left operand
^= Performs Bitwise xOR on operands and assign value to left operand
>>= Performs Bitwise right shift on operands and assign value to left operand
<<= Performs Bitwise left shift on operands and assign value to left operand

Identity Operators

Identity operators are used to check if two values are located on the same part of the memory. Two variables that are equal do not imply that they are identical.

Operator Description
is True if the operands are identical
is not True if the operands are not identical

Membership Operators

Membership operators are used to test whether a value or variable is in a sequence.

Operator Description
in True if value is found in the sequence
not in True if value is not found in the sequence
Data Types

Every value in Python has a datatype. Since everything is an object in Python programming, data types are actually classes and variables are instance (object) of these classes.

There are various data types in Python. Some of the important types are listed below:

Python Numbers

Integers, floating point numbers and complex numbers fall under Python numbers category. They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to. Similarly, the isinstance() function is used to check if an object belongs to a particular class.

>> a = 5>> print(a, "is of type", type(a))>> a = 2.0 >> print(a, "is of type", type(a))>> a = 1+2j>> print(a, "is complex number?", isinstance(1+2j,complex))

Output:

5 is of type <class 'int'>2.0 is of type <class 'float'>(1+2j) is complex number? True

Integers can be of any length, it is only limited by the memory available.

A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

Python Lists

Lists are one of the most powerful tools in python. They are just like the arrays declared in other languages. But the most powerful thing is that list need not be always homogeneous. A single list can contain strings, integers, as well as objects. Lists can also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared.

Declaring a list is pretty straight forward. Items separated by commas are enclosed within brackets [ ].The index starts from 0 (zero) in Python.

>> a = [1, 2.2, 'python']

Python Tuple

A tuple is a sequence of immutable Python objects. Tuples are just like lists with the exception that tuples cannot be changed once declared. Tuples are usually faster than lists. It is defined within parentheses () where items are separated by commas ,.

>> t = (5,'program', 1+3j)

Python Strings

A string is a sequence of characters. It can be declared in python by using double-quotes (""). Strings are immutable, i.e., they cannot be changed.

>> s = "This is a string">> print(s)>> s = '''A multiline >> string'''>> print(s)

Output:

This is a stringA multilinestring

Python Set

Set is an unordered collection of unique items. Set is defined by values separated by comma inside braces { }. Items in a set are not ordered.

The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. We can perform set operations like union, intersection on two sets. Sets have unique values. They eliminate duplicates.

Set items cannot be accessed by referring to an index, since sets are unordered the items has no index. But you can loop through the set items using a for loop, or ask if a specified value is present in a set, by using the in keyword.

>> a = {5,2,3,1,4}>> print("a = ", a)

Output:

a = {1, 2, 3, 4, 5}

Python Dictionary

Dictionary is an unordered collection of key-value pairs. It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value.

Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.

In Python, dictionaries are defined within braces {} with each item being a pair in the form key: value. Key and value can be of any type. We use key to retrieve the respective value. But not the other way around.

>> d = {1: 'value', 'key': 2}>> print("d[1] = ", d[1])

Output:

d[1] = value

Python Arrays

An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding an offset to a base value, i.e., the memory location of the first element of the array (generally denoted by the name of the array).

Array can be handled in Python by a module named array. They can be useful when we have to manipulate only a specific data type values. A user can treat lists as arrays. However, user cannot constraint the type of elements stored in a list. If you create arrays using the array module, all elements of the array must be of the same type.

In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array. The index must be an integer.

# importing array moduleimport array as arr

# array with int type>> a = arr.array('i', [1, 2, 3, 4, 5, 6])# accessing element of array>> print("Access element is: ", a[0])

Output:

Access element is: 1
Functions

Python Functions are very easy to write in python and all non-trivial programs will have functions. Function names have the same rules as variable names.

The function is a block of related statements designed to perform a computational, logical, or evaluative task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Creating a Function

We can create a Python function using the def keyword.

def fun():print("Hello, World!")

After creating a function we can call it by using the name of the function followed by parenthesis containing parameters of that particular function.

def fun():print("Hello, World!")
fun()

Output:

Hello, World!

Note: In python, the function definition should always be present before the function call. Otherwise, we will get an error.

Arguments of a Function

Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma.

Python supports various types of arguments that can be passed at the time of the function call such as: default, keyword or variable-length.

Docstring

The first string after the function is called the Document string or Docstring in short. This is used to describe the functionality of the function. The use of docstring in functions is optional but it is considered a good practice.

def greet(name):"""This function greets to the person passed in asa parameter""" print("Hello, " + name + ". Good morning!")

The return statement

The function return statement is used to exit from a function and go back to the function caller and return the specified value or data item to the caller. It can consist of a variable, an expression, or a constant which is returned to the end of the function execution. If none of the above is present with the return statement a None object is returned.

def square_value(num):return num**2
>> print(square_value(2))

Output:

4

Scope and Lifetime of variables

Scope of a variable is the portion of a program where the variable is recognized. Parameters and variables defined inside a function are not visible from outside the function. Hence, they have a local scope.

The lifetime of a variable is the period throughout which the variable exists in the memory. The lifetime of variables inside a function is as long as the function executes. They are destroyed once we return from the function. Hence, a function does not remember the value of a variable from its previous calls.

Anonymous functions

In Python, an anonymous function means that a function is without a name. As we already know the def keyword is used to define the normal functions and the lambda keyword is used to create anonymous functions.

cube_v2 = lambda x : x*x*x>> print(cube_v2(7))

Output:

343

Python Function within Functions

A function that is defined inside another function is known as the inner function or nested function. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.

References