Python
Python
2. Input/Output
A parallelogram denotes any function of input/output type. Program instructions that take input from input
devices and display output on output devices are indicated with parallelogram in a flowchart.
3. Action/Process
A box represents arithmetic instructions, specific action or operation that occurs as a part of the process.
All arithmetic processes such as adding, subtracting, multiplication and division are indicated by
action/process symbol.
4. Decision
Diamond symbol represents a decision point. Decision based operations such as yes/no question or
true/false are indicated by diamond in flowchart.
5. On-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors
to avoid any confusions. connectors are used to indicate a jump from one part of the flowchart to another
without drawing long or complicated lines. On-Page Connector is represented by a small circle
6. Off-Page Connector/Reference
Whenever flowchart becomes complex or it spreads over more than one page, it is useful to use connectors
to avoid any confusions. connectors are used to indicate a jump from one part of the flowchart to another
without drawing long or complicated lines. Off-Page Connector is represented by a pentagon.
7. Flow lines
Flow lines indicate the exact sequence in which instructions are executed. Arrows represent the direction
of flow of control and relationship among different symbols of flowchart.
else
HIGH = MID – 1
There are no rules to writing algorithms There are certain rules for writing pseudocode
This is a way of visually representing data, these are These are fake codes as the word pseudo means
nothing but the graphical representation of the fake, using code like structure but plain English
algorithm for a better understanding of the code text instead of programming language
Interactive and Script Mode: As a software engineer diving into Python programming, understanding the
different modes of running Python code is crucial. Python offers both Interactive Mode and Script Mode, each
serving distinct purposes in the development process. Today, we’ll explore what Python Interactive Mode is,
how to use it effectively, when it’s beneficial, and compare it to Script Mode for running Python code saved in
a file.
Interactive Mode
What is Python Interactive Mode? Python Interactive Mode, often referred to as the Python REPL (Read-
Eval-Print Loop), provides an interactive environment for executing Python code line by line. It allows
developers to experiment, test code snippets, and quickly get feedback without the need for a complete script
or program.
To access Python Interactive Mode, open a terminal or command prompt on your machine.
Once in the Python Interactive Mode, you can start entering Python code directly. Each line is executed
as soon as you press Enter.
Use the interactive environment to experiment with code snippets, test functions, and explore Python
features without the need to save a script.
1- Quick Prototyping:
Python Interactive Mode is excellent for quickly prototyping ideas and testing small code snippets. It
provides immediate feedback, allowing you to iterate rapidly.
For software engineers, Interactive Mode is a valuable learning tool. It allows you to explore Python
syntax, experiment with language features, and see the results in real-time.
When debugging or testing small portions of code, Interactive Mode allows you to interactively evaluate
expressions and observe variable values.
Python Script Mode involves running Python code saved in a file with a .py extension. This mode is suitable
for larger programs and scripts where code is organized into a file rather than entered interactively.
How to Use Python Script Mode
Open your preferred text editor and create a new file with a .py extension. For example, myscript.py.
Add your Python code to the script file. It can include functions, classes, or any Python code structure.
# myscript.py
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Open a terminal, navigate to the directory containing your script, and use the py (Windows)
or python3 (Mac / Linux) command followed by the script filename to run it.
python myscript.py
For developing more extensive projects, applications, or scripts, Script Mode is the preferred choice. It
allows you to organize code into modular structures and maintainability.
2- Reusability:
Code written in script files can be reused across multiple executions. This is especially valuable when
creating libraries, modules, or packages.
Script Mode is essential for tasks that require automation or reproducibility. Running a script ensures
consistent execution of a set of instructions.
Interactive Mode vs. Script Mode
Pros:
Cons:
Pros:
Cons:
1. Slower Feedback: Typically involves writing, saving, and executing code, leading to slower feedback
compared to Interactive Mode.
When learning Python or experimenting with new concepts, begin with Interactive Mode for its
immediate feedback and learning benefits.
Consider using both modes complementarily in your workflow. Use Interactive Mode for quick tests and
exploration, and Script Mode for developing larger projects.
Many IDEs, including VS Code, offer a combination of both modes within a single interface. Explore the
features of your chosen IDE to maximize productivity.
Conclusion
Understanding Python Interactive Mode and Script Mode is essential for software engineers navigating the
world of Python programming. Each mode serves distinct purposes, with Interactive Mode offering
immediate feedback for exploration and experimentation, and Script Mode providing organization and
reusability for larger projects. By incorporating both modes into your development workflow, you’ll gain a
comprehensive understanding of Python and enhance your proficiency as a software engineer.
Indentation:
In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are considered
part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the beginning of each
line.
For Example:
if 10 > 5:
print("This is true!")
print("I am tab indentation")
Output
This is true!
I am tab indentation
I have no indentation
The first two print statements are indented by 4 spaces, so they belong to the if block.
The third print statement is not indented, so it is outside the if block.
If we Skip Indentation, Python will throw error.
if 10>5:
print("GeeksforGeeks")
Indentation in Conditional Statements
The lines print(‘GeeksforGeeks…’) and print(‘retype the URL.’) are two separate code blocks. The two
blocks of code in our example if-statement are both indented four spaces. The final print( ‘All set!’) is not
indented, so it does not belong to the else block.
a = 20
if a >= 18:
print('GeeksforGeeks...')
else:
print('retype the URL.')
print('All set !')
Output
GeeksforGeeks...
All set !
Indentation in Loops
To indicate a block of code in Python, we must indent each line of the block by the same whitespace. The
two lines of code in the while loop are both indented four spaces. It is required for indicating what block
of code a statement belongs to.
j=1
while(j<= 5):
print(j)
j=j+1
Output
1
2
3
4
5
Comments:
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the
program.
Comments enhance the readability of the code.
Comment can be used to identify functionality or structure the code-base.
Comment can help understanding unusual or tricky scenarios handled by the code to prevent accidental
removal or changes.
Comments can be used to prevent executing any specific part of your code, while making changes or
testing.
Comments in Python
# sample comment
name = "geeksforgeeks"
print(name)
Output
geeksforgeeks
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different ways through
which we can write multiline comments.
Multiline comments using multiple hashtags (#)
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be considered
as a single-line comment.
These are some of the tips you can follow, to make your comments effective are:
1. Comments should be short and precise.
2. Use comments only when necessary, don't clutter your code with comments.
3. Avoid writing generic or basic comments.
4. Write comments that are self explanatory.
Error messages:
Errors are problems in a program that causes the program to stop its execution. On the other hand,
exceptions are raised when some internal events change the program's normal flow.
Syntax Errors in Python
Syntax error occurs when the code doesn't follow Python's rules, like using incorrect grammar in English.
Python stops and points out the issue before running the program.
Example 1 : In this example, this code returns a syntax error because there is a missing colon (:) after the
if statement. The correct syntax requires a colon to indicate the start of the block of code to be executed if
the condition is true.
a = 10000
if a > 2999
print("Eligible")
Output
Example 2: This code returns a syntax error because parentheses around the condition in an if statement
are not required in Python. While optional, their unnecessary use can lead to incorrect syntax.
if(a<3):
print("gfg")
Output
Syntax
error
Python Logical Errors (Exception)
Logical errors are subtle bugs in the program that allow the code to run, but produce incorrect or
unintended results. These are often harder to detect since the program doesn’t crash, but the output is not
as expected.
Characteristics of Logical Errors
No Syntax Error: The code runs without issues.
Unexpected Output: The results produced by the program are not what the programmer intended.
Difficult to Detect: These errors can be tricky to spot since there’s no obvious problem with the code
itself.
Causes: Faulty logic, incorrect assumptions, or improper use of operators.
Example:
a = [10, 20, 30, 40, 50]
b=0
for i in a:
b += i
res = b / len(a) - 1
print(res)
Output
29.0
Explanation: Expected output is that the average of a should be 30, but the program outputs 29.0. The
logical error occurs because the formula b/ len(a) - 1 incorrectly subtracts 1, leading to an incorrect result.
The correct formula should be b / len(a).
Common Builtin Exceptions
Some of the common built-in exceptions are other than above mention exceptions are:
Exception Description
TypeError It occurs when a function and operation are applied in an incorrect type.
Error Handling
Python provides mechanisms to handle errors and exceptions using the try, except, and finally blocks. This
allows for graceful handling of errors without crashing the program.
Example 1: This example shows how try, except and finally handle errors. try runs risky code, except
catches errors and finally runs always.
try:
print("code start")
print(1 / 0)
except:
print("an error occurs")
finally:
print("GeeksForGeeks")
Output
code start
an error occurs
GeeksForGeeks
Explanation:
try block runs code, raising an exception if any occurs (e.g., 1 / 0 raises ZeroDivisionError).
except block catches exceptions, printing "an error occurs" in case of an error.
finally block always executes, printing "GeeksForGeeks" to signal the end of execution.
Example 2: This example shows how try and except handle custom errors. try checks a condition, raises a
ValueError if it fails and except catches and prints the error message.
try:
a = 1999
if a < 2999:
except ValueError as e:
print(e)
Output
please add money
Explanation:
try block sets a = 1999 raises a ValueError if a < 2999, otherwise prints "Eligible".
except block catches the ValueError and prints "please add money".
Variables:
In Python, variables are used to store data that can be referenced and manipulated during program
execution. A variable is essentially a name that is assigned to a value. Unlike many other programming
languages, Python variables do not require explicit declaration of type. The type of the variable is inferred
based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
Example:
Output
5
Samantha
In this article, we’ll explore the concept of variables in Python, including their syntax, characteristics and
common operations.
Table of Content
Rules for Naming Variables
Assigning Values to Variables
Multiple Assignments
Type Casting a Variable
Getting the Type of Variable
Object Reference in Python
Delete a Variable Using del Keyword
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
Variable names can only contain letters, digits and underscores (_).
A variable name cannot start with a digit.
Variable names are case-sensitive (myVar and myvar are different).
Avoid using Python keywords (e.g., if, else, for) as variable names.
Valid Example:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Basic Assignment
Variables in Python are assigned values using the = operator.
x=5
y = 3.14
z = "Hi"
Dynamic Typing
Python variables are dynamically typed, meaning the same variable can hold different types of values
during execution.
x = 10
x = "Now a string"
Multiple Assignments
Python allows multiple variables to be assigned values in a single line.
a = b = c = 100
print(a, b, c)
Output
100 100 100
We can assign different values to multiple variables simultaneously, making the code concise and easier to
read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type into another. Python provides
several built-in functions to facilitate casting, including int(), float() and str() among others.
Basic Casting Functions
int() - Converts compatible values to an integer.
float() - Transforms values into floating-point numbers.
str() - Converts any data type into a string.
Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output
10
5.0
25
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
When x = 5 is executed, Python creates an object to represent the value 5 and makes x reference this
object.
Now, if we assign another variable y to the variable x.
y=x
Explanation:
Python encounters the first statement, it creates an object for the value 5 and makes x reference it. The
second statement creates y and references the same object as x, not x itself. This is called a Shared
Reference, where multiple variables reference the same object.
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and makes x reference this new object.
Explanation:
The variable y remains unchanged, still referencing the original object 5.
If we now assign a new value to y:
y = "Computer"
Python creates yet another object for "Computer" and updates y to reference it.
The original object 5 no longer has any references and becomes eligible for garbage collection.
Key Takeaways:
Python variables hold references to objects, not the actual objects themselves.
Reassigning a variable does not affect other variables referencing the same object unless explicitly
updated.
Delete a Variable Using del Keyword
We can remove a variable from the namespace using the del keyword. This effectively deletes the variable
and frees up the memory it was using.
Example:
# Assigning value to variable
x = 10
print(x)
Operator
and, or, not, is, in
Keywords
Control Flow if, else, elif, for, while, break, continue, pass, try, except, finally, raise, ass
Keywords ert
Function and
def, return, lambda, yield, class
Class
Context
with, as
Management
Import and
import, from
Module
Scope and
global, nonlocal
Namespace
Async
async, await
Programming
print(keyword.kwlist)
Output
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else',
'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',...
Identifiers in Python
User-defined names for variables, functions, classes, modules, etc.
Can include letters, digits, and underscores (_).
Case-sensitive → num, Num, and NUM are different identifiers.
Python provides str.isidentifier() to check if a string is a valid identifier.
Rules for Naming Python Identifiers
It cannot be a reserved python keyword.
It should not contain white space.
It can be a combination of A-Z, a-z, 0-9, or underscore.
It should start with an alphabet character or an underscore ( _ ).
It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
var1
_var1
_1_var
var_1
Invalid Identifiers
!var1
1var
1_var
var#1
var 1
Python Keywords and Identifiers Examples
Example 1: Example of and, or, not, True, False keywords.
print("example of True, False, and, or, not keywords")
Output
example of True, False, and, or, not keywords
True
True
True
Example 2: Example of a break, continue keywords and identifier.
# execute for loop
for i in range(1, 11):
Output
1
2
3
4
5
Example 3: example of for, in, if, elif, and else keywords.
# run for loop
for t in range(1, 5):
# print one of t ==1
if t == 1:
print('One')
# print two if t ==2
elif t == 2:
print('Two')
else:
print('else block execute')
Output
One
Two
else block execute
else block execute
Example 4: Example of def, if, and else keywords.
# define GFG() function using def keyword
def GFG():
i=20
# check i is odd or not
# using if and else keyword
if(i % 2 == 0):
print("given number is even")
else:
print("given number is odd")
Output
given number is even
Example 5: Example of try, except, raise.
def fun(num):
try:
r = 1.0/num
except:
print('Exception raises')
return
return r
print(fun(10))
print(fun(0))
Output
0.1
Exception raises
None
Example 6: Example of a lambda keyword.
# define a anonymous using lambda keyword
# this lambda function increment the value of b
a = lambda b: b+1
Output
2
3
4
5
6
Example 7: use of return keyword.
# define a function
def fun():
# declare a variable
a=5
# return the value of a
return a
# call fun method and store
# it's return value in a variable
t = fun()
# print the value of t
print(t)
Output
5
Example 8: use of a del keyword.
# create a list
l = ['a', 'b', 'c', 'd', 'e']
del l[2]
Output
['a', 'b', 'c', 'd', 'e']
['a', 'b', 'd', 'e']
Example 9: use of global keyword.
# declare a variable
gvar = 10
# create a function
def fun1():
# print the value of gvar
print(gvar)
# declare fun2()
def fun2():
# declare global value gvar
global gvar
gvar = 100
# call fun1()
fun1()
# call fun2()
fun2()
Output
10
Example 10: example of yield keyword.
def Generator():
for i in range(6):
yield i+1
t = Generator()
for i in t:
print(i)
Output
1
2
3
4
5
6
Example 11: Use of assert keyword.
def sumOfMoney(money):
assert len(money) != 0,"List is empty."
return sum(money)
money = []
print("sum of money:",sumOfMoney(money))
Output:
AssertionError: List is empty.
Example 12: Use of pass keyword
class GFG:
pass
g = GFG
Example 13: Use of finally keyword
def divide(a, b):
try:
c = a/b
print("Inside try block")
except:
print("Inside Exception block")
finally:
print("Inside finally block")
divide(3,2)
divide(3,0)
Output
Inside try block
Inside finally block
Inside Exception block
Inside finally block
Example 14: Use of import keyword
import math
print("factorial of 5 is :", math.factorial(5))
Output
factorial of 5 is : 120
Example 15: Use of is keyword
x = 10
y = 20
z=x
print(x is z)
print(x is y)
Output
True
False
Example 16: Use of from keyword
from math import gcd
print("gcd of 345 and 675 is : ", gcd(345, 675))
Output
gcd of 345 and 675 is : 15
Example 17: Use of async and await keyword
# code
import asyncio
if __name__ == "__main__":
main()
Output
120
The async and await keywords make it easy to write asynchronous code in Python. They allow you to
write code that runs concurrently with other tasks, which can improve the performance of your programs.
This program defines two functions: factorial() and main(). The factorial() function is an asynchronous
function, which means it can run concurrently with other tasks. The await keyword is used to suspend the
execution of the factorial() function until it completes. The main() function simply calls the factorial()
function and prints the result.
Data types:
Data types in python are classification or categorization of data items. It represents kind of value that tells
what operations can be performed on a particular data. Since everything is an object in Python programming,
Python data types are classes and variables are instances (objects) of these classes.
The following are standard or built-in data types in Python:
Numeric - int, float, complex
Sequence Type - string, list, tuple
Mapping Type - dict
Boolean - bool
Set Type - set, frozenset
Binary Types - bytes, bytearray, memoryview
Below code assigns variable 'x' different values of few Python data types - int, float, list, tuple and string.
Each assignment replaces previous value, making 'x' take on data type and value of most recent assignment.
x = 50 # int
x = 60.5 # float
x = "Hello World" # string
x = ["geeks", "for", "geeks"] # list
x = ("geeks", "for", "geeks") # set
1. Numeric Data Types
Python numbers represent data that has a numeric value. A numeric value can be an integer, a floating
number or even a complex number. These values are defined as int, float and complex classes.
Integers - value is represented by int class. It contains positive or negative whole numbers (without
fractions or decimals). There is no limit to how long an integer value can be.
Float - value is represented by float class. It is a real number with a floating-point representation. It is
specified by a decimal point. Optionally, character e or E followed by a positive or negative integer may
be appended to specify scientific notation.
Complex Numbers - It is represented by a complex class. It is specified as (real part) + (imaginary
part)j. For example - 2+3ja = 5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
2. Sequence Data Types
The sequence Data Type is ordered collection of similar or different Python data types. Sequences allow
storing of multiple values in an organized and efficient fashion. There are several sequence data types of
Python:
String Data Type
Python Strings are arrays of bytes representing Unicode characters. In Python, there is no character data
type, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes or even triple quotes. We can access
individual characters of a String using index.
s = 'Welcome to the Geeks World'
print(s)
Output
Welcome to the Geeks World
<class 'str'>
e
l
d
List Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible
as items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing sequence inside the square brackets[].
# Empty list
a = []
Output
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]
Access List Items
In order to access the list items refer to index number. In Python, negative sequence indexes represent
positions from end of the array. Instead of having to compute offset as in List[len(List)-3], it is enough to
just write List[-3]. Negative indexing means beginning from end, -1 refers to last item, -2 refers to second-
last item, etc.
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])
Output
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Tuple Data Type
Tuple is an ordered collection of Python objects. The only difference between a tuple and a list is that tuples
are immutable. Tuples cannot be modified after it is created.
Creating a Tuple in Python
In Python, tuples are created by placing a sequence of values separated by a ‘comma’ with or without the use
of parentheses for grouping data sequence. Tuples can contain any number of elements and of any datatype
(like strings, integers, lists, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element in the
parentheses is not sufficient, there must be a trailing ‘comma’ to make it a tuple.
# initiate empty tuple
tup1 = ()
Output
Tuple with the use of String: ('Geeks', 'For')
Note - The creation of a Python tuple without the use of parentheses is known as Tuple Packing.
Access Tuple Items
In order to access tuple items refer to the index number. Use the index operator [ ] to access an item in a
tuple.
Output
1
5
3
3. Boolean Data Type in Python
Python Boolean Data type is one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true) and those equal to False are falsy (false). However non-Boolean objects can be
evaluated in a Boolean context as well and determined to be true or false. It is denoted by class bool.
Example: First two lines will print type of the boolean values True and False, which is <class 'bool'>. Third
line will cause an error, because true is not a valid keyword. Python is case-sensitive, which means it
distinguishes between uppercase and lowercase letters.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
4. Set Data Type in Python
In Python Data Types, Set is an unordered collection of data types that is iterable, mutable, and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such as strings, lists
and mixed values
# initializing empty set
s1 = set()
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
Output
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}
Access Set Items
Set items cannot be accessed by referring to an index, since sets are unordered the items have no index. But
we 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 the keyword.
set1 = set(["Geeks", "For", "Geeks"])
print(set1)
Output
{'Geeks', 'For'}
Geeks For True
5. Dictionary Data Type
A dictionary in Python is a collection of data values, used to store data values like a map, unlike other
Python Data Types, a Dictionary holds a key: value pair. Key-value is provided in dictionary to make it
more optimized. Each key-value pair in a Dictionary is separated by a colon : , whereas each key is separated
by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and
must be immutable. The dictionary can also be created by the built-in function dict().
Note - Dictionary keys are case sensitive, the same name but different cases of Key will be treated distinctly.
# initialize empty dictionary
d = {}
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Accessing Key-value in Dictionary
In order to access items of a dictionary refer to its key name. Key can be used inside square brackets. Using
get() method we can access dictionary elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output
For
Geeks
Arithmetic Operators
Python operators are fundamental for performing mathematical calculations. Arithmetic operators are
symbols used to perform mathematical operations on numerical values. Arithmetic operators include
addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Operator Description Syntax
val1 = 2
val2 = 3
Subtraction Operator
In Python, - is the subtraction operator. It is used to subtract the second value from the first value.
val1 = 2
val2 = 3
# using the subtraction operator
res = val1 - val2
print(res)
Output:
-1
Multiplication Operator
Python * operator is the multiplication operator. It is used to find the product of 2 values.
val1 = 2
val2 = 3
Division Operator
In Python programming language Division Operators allow us to divide two numbers and return a
quotient, i.e., the first number or number at the left is divided by the second number or number at the right
and returns the quotient.
There are two types of division operators:
1. Float division
2. Floor division
Float division
The quotient returned by this operator is always a float number, no matter if two numbers are integers. For
example:
Example:
print(5/5)
print(10/2)
print(-10/2)
print(20.0/2)
Output
1.0
5.0
-5.0
10.0
Integer division( Floor division)
The quotient returned by this operator is dependent on the argument being passed. If any of the numbers is
float, it returns output in float. It is also known as Floor division because, if any number is negative, then
the output will be floored. For example:
Example:
print(10//3)
print (-5//2)
print (5.0//2)
print (-5.0//2)
Output
3
-3
2.0
-3.0
Modulus Operator
The % in Python is the modulus operator. It is used to find the remainder when the first operand is
divided by the second.
val1 = 3
val2 = 2
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators, and
sometimes parenthesis. The result of this type of expression is also a numeric value. The operators used in
these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic
operators in Python:
+ x+y Addition
- x-y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation
Example:
Let's see an exemplar code of arithmetic expressions in Python :
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.
Example:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides
of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared
as per relational operator and produce a boolean output in the end. These expressions are also called
Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often. Here are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
Example:
Let's have a look at an exemplar code :
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit
level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
But when we combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.
It's a quite simple process to get the result of an expression if there is only one operator in an expression.
But if there is more than one operator in an expression, it may give different results on basis of the order
of operators executed. To sort out these confusions, the operator precedence is defined. Operator
Precedence simply defines the priority of operators that which operator is to be executed first. Here we see
the operator precedence in Python, where the operator higher in the list has more precedence or priority:
Precedence Name Operator
1 Parenthesis ()[]{}
2 Exponentiation **
8 Bitwise XOR ^
Precedence Name Operator
9 Bitwise OR |
11 Equality Operators == !=
12 Assignment Operators = += -= /= *=
So, if we have more than one operator in an expression, it is evaluated as per operator precedence. For
example, if we have the expression "10 + 3 * 4". Going without precedence it could have given two
different outputs 22 or 52. But now looking at operator precedence, it must yield 22. Let's discuss this with
the help of a Python program:
# Multi-operator expression
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python expression.
Built in Functions:
Python is the most popular programming language created by Guido van Rossum in 1991. It is used for
system scripting, software development, and web development (server-side). Web applications can be
developed on a server using Python. Workflows can be made with Python and other technologies.
Database systems are connectable with Python. Files can also be read and changed by it. Big data
management and advanced mathematical operations can both be done with Python.
The syntax of Python is straightforward and resembles that of English. Python's syntax enables
programmers to create programmes with fewer lines of code than they would be able to with certain other
languages. Python operates on an interpreter system, allowing for the immediate execution of written
code.
Python provides a lot of built-in functions that ease the writing of code. In this article, you will learn
about Python's built-in functions, exploring their various applications and highlighting some of the most
commonly used ones.
Python Built-in Functions List
Here is a comprehensive list of Python built-in functions:
Function Name Description
Return true if all the elements of a given iterable( List, Dictionary, Tuple, set,
Python all() Function etc) are True else it returns False
Python anext() Function used for getting the next item from an asynchronous iterator
Python bool() Function Return or convert a value to a Boolean value i.e., True or False
Python breakpoint() It is used for dropping into the debugger at the call site during runtime for
Function debugging purposes
Python bytearray() Returns a byte array object which is an array of given bytes
Function
Python dir() Function Returns a list of the attributes and methods of any object
Python divmod() Takes two numbers and returns a pair of numbers consisting of their quotient
Function and remainder
Python enumerate() Adds a counter to an iterable and returns it in a form of enumerating object
Function
Python exec() Function Used for the dynamic execution of the program
Filters the given sequence with the help of a function that tests each element
Python filter() Function in the sequence to be true or not
Function
Python globals() Returns the dictionary of the current global symbol table
Function
Python hasattr() Check if an object has the given named attribute and return true if present
Function
Python help() Function Display the documentation of modules, functions, classes, keywords, etc
Python hex() Function Convert an integer number into its corresponding hexadecimal form
Python locals() Function Returns the dictionary of the current local symbol table
Python max() Function Returns the largest item in an iterable or the largest of two or more arguments
Python next() Function Receives the next item from the iterator
Python ord() Function Returns the Unicode equivalence of the passed argument
Python reversed() Returns an iterator that accesses the given sequence in the reverse order
Function
Rounds off to the given number of digits and returns the floating-point
Python round() Function number
Function Name Description
Python sorted() Returns a list with the elements in a sorted manner, without modifying the
Function original sequence
Returns the __dict__ attribute for a module, class, instance, or any other
Python vars() Function object
Example :In this example, we are creating a Math Operation Package to organize Python code into a
structured package with two sub-packages: basic (for addition and subtraction) and advanced (for
multiplication and division). Each operation is implemented in separate modules, allowing for modular,
reusable and maintainable code.
math_operations/__init__.py:
This __init__.py file initializes the main package by importing and exposing the calculate function and
operations (add, subtract, multiply, divide) from the respective sub-packages for easier access.
# Initialize the main package
from .calculate import calculate
from .basic import add, subtract
from .advanced import multiply, divide
math_operations/calculator.py:
This calculate file is a simple placeholder that prints "Performing calculation...", serving as a basic
demonstration or utility within the package.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py:
This __init__.py file initializes the basic sub-package by importing and exposing the add and subtract
functions from their respective modules (add.py and sub.py). This makes these functions accessible when
the basic sub-package is imported.
# Export functions from the basic sub-package
from .add import add
from .sub import subtract
math_operations/basic/add.py:
def add(a, b):
return a + b
math_operations/basic/sub.py:
def subtract(a, b):
return a - b
In the same way we can create the sub package advanced with multiply and divide modules. Now, let's
take an example of importing the module into a code and using the function:
from math_operations import calculate, add, subtract