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:
- Python is currently the most widely used multi-purpose, high-level programming language.
- Python allows programming in Object-Oriented and Procedural paradigms.
- Free and Open Source: Redistributable.
- High-level Language: no need to take care about low-level details such as managing the memory used by the program.
- Python programs generally are smaller than other programming languages like Java.
- Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook, Instagram, Dropbox, Uber… etc.
- The biggest strength of Python is huge collection of standard library.
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:
- Step 1: First and foremost step is to open a browser and open https://www.python.org/downloads/windows/.
- Step 2: Underneath the Python Releases for Windows find the Latest Python 3 Release – Python 3.10.5.
- Step 3: On this page move to Files and click on Windows installer for 64-bit or for 32-bit.
- Step 4: Run the Python Installer for how to install python on windows downloads folder (Make sure to mark Add Python 3.10 to PATH).
- After installation is complete click on Close. Python is installed!
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:
- Step 1: First, install development packages required to build Python. The following command could be used to install the latest version of Python on almost every Linux system:
- Step 2: Visit the official Python website https://www.python.org/ and download the latest version of Python 3. After the download is complete, you hav a .tar.xz archive file (a "tarball") containing the source code of Python.
- Step 3: Extract the tarball either using the extractor application of your choice or the Linux tar command, for example:
- Step 4: Configure the script by executing it in your Linux terminal with:
- Step 5: Start the build process. If you already have a version of Python installed on your system and you want to install the new version alongside it, use this command:
- Step 6: Verify the installation in your terminal:
>> sudo apt-get install python3
>> tar -xf Python-3.?.?.tar.xz
>> cd Python-3.*>> ./configure
>> sudo make altinstall
>> python3 --version
If the output says Python 3.x, Python 3 has been successfully installed!
How to install Python on macOS?
- To install python simple open Terminal app from Application -> Utilities and enter following command:
- After command processing is complete, Python’s version 3 would be installed on your mac.
- To verify the installation enter following commands in your Terminal app:
>> brew install python3
>> python>> pip3
Python is installed on your computer!
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:
- Windows: There are many interpreters available freely to run Python scripts like IDLE (Integrated Development Environment) that comes bundled with the Python software downloaded from http://python.org/.
- Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and Fedora. To check which version of Python you’re running, type “python” in the terminal emulator. The interpreter should start and print the version number.
- macOs: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually install Python 3 from http://python.org/.
The following shows you step by step how to launch the Python IDLE and use it to execute the Python code:
- First, launch the Python IDLE program. A new Python Shell window will display as follows:
- Now, you can enter the Python code after the cursor >>> and press Enter to execute it:

>> print('Hello, World!')
Output:
Hello, World!
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:
- True: This keyword is used to represent a boolean true. If a statement is true, “True” is printed.
- False: This keyword is used to represent a boolean false. If a statement is false, “False” is printed.
- None: This is a special constant used to denote a null value or a void. It’s important to remember, 0, any empty container(e.g empty list) does not compute to None.
- and: This a logical operator in python. “and” Return the first false value. If not found return last.
- or: This a logical operator in python. “or” Return the first True value.if not found return last.
- not: This logical operator inverts the truth value.
- in: This keyword is used to check if a container contains a value. This keyword is also used to loop through the container.
- is: This keyword is used to test object identity, i.e to check if both the objects take the same memory location or not.
- for: This keyword is used to control flow and for looping.
- while: Has a similar working like “for”, used to control flow and for looping.
- break: “break” is used to control the flow of the loop. The statement is used to break out of the loop and passes the control to the statement following immediately after loop.
- continue: “continue” is also used to control the flow of code. The keyword skips the current iteration of the loop but does not end the loop.
- if: It is a control statement for decision making. Truth expression forces control to go in “if” statement block.
- else: It is a control statement for decision making. False expression forces control to go in “else” statement block.
- elif: It is a control statement for decision making. It is short for "else if".
- def: This keyword is used to declare user defined functions.
- return: This keyword is used to return from the function.
- yield: This keyword is used like return statement but is used to return a generator.
- class: This keyword is used to declare user defined classes.
- with: This keyword is used to wrap the execution of block of code within methods defined by context manager. This keyword is not used much in day to day programming.
- as: keyword is used to create the alias for the module imported. i.e giving a new name to the imported module. E.g import math as mymath.
- pass: This is the null statement in python. Nothing happens when this is encountered. This is used to prevent indentation errors and used as a placeholder.
- lambda: This keyword is used to make inline returning functions with no statements allowed internally.
- import: This statement is used to include a particular module into current program.
- from: Generally used with import, from is used to import particular functionality from the module imported.
- try: This keyword is used for exception handling, used to catch the errors in the code using the keyword except. Code in “try” block is checked, if there is any type of error, except block is executed.
- except: As explained above, this works together with “try” to catch exceptions.
- finally: No matter what is result of the “try” block, block termed “finally” is always executed.
- raise: We can raise an exception explicitly with the raise keyword.
- assert: This function is used for debugging purposes. Usually used to check the correctness of code. If a statement is evaluated to be true, nothing happens, but when it is false, “AssertionError” is raised. One can also print a message with the error, separated by a comma.
- del: is used to delete a reference to an object. Any variable or list value can be deleted using del.
- global: This keyword is used to define a variable inside the function to be of a global scope.
- non=local: his keyword works similar to the global, but rather than global, this keyword declares a variable to point to variable of outside enclosing function, in case of nested functions.
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 (\).
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.
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
- Method 1: Direct Initialisation Method
- Method 2: Using Conditional Operator (?:)
In this method, you will directly assign the value in python but in other programming languages like C, C++, you have to first initialise the data type of variable. So, In Python, there is no need of explicit declaration in variables as compare to using some other programming languages. You can start using the variable right away.
# initialising variable directly>> a = 5# printing value of a
>> print("The value of a is: " + str(a))
Output:
The value of a is: 5
This method is also called Ternary operators. Using Conditional Operator, you can write one line code in python. The conditional operator works in a such way that first evaluates the condition, if condition is true , first expression( True_value) will print else evaluates the second expression(False_Value).
# Initialising variables using Conditional Operator>> a = 1 if 20 > 10 else 0# printing
value of a>> print("The value of a is: " + str(a))
Output:
The value of a is: 1
Python is a type-inferred language, so you don't have to explicitly define the variable type. If you assign, for example, a value apple.com to the variable website it automatically knows that apple.com is a string and declares the website variable as a string.
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.
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 |
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
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.
- All the documentation in this page is taken from: