0% found this document useful (0 votes)
16 views33 pages

Python Unit 1 Notes by Dr. Yusuf Perwej

The document provides an overview of Python programming, highlighting its features, history, and applications across various fields such as web development, data analysis, and machine learning. It compares Python with C, discusses the Python programming cycle, and emphasizes the importance of clean code and debugging. Additionally, it covers installation, IDEs, and key programming concepts like variables, data types, and control flow statements.

Uploaded by

pg739082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views33 pages

Python Unit 1 Notes by Dr. Yusuf Perwej

The document provides an overview of Python programming, highlighting its features, history, and applications across various fields such as web development, data analysis, and machine learning. It compares Python with C, discusses the Python programming cycle, and emphasizes the importance of clean code and debugging. Additionally, it covers installation, IDEs, and key programming concepts like variables, data types, and control flow statements.

Uploaded by

pg739082
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UCS 1803 PYTHON

Unit 1 “Introduction to Python Programming”


Notes by- Dr. Yusuf Perwej
The PYTHON Programming Language
Python is a general-purpose, high-level, object-oriented programming
language that is used for a variety of tasks, including:
Web development, Data analysis, Software development, Machine learning and
artificial intelligence, Scientific and numeric computing, Business applications,
blockchain, Everyday tasks.
Python is popular with developers and coders because it is easy to learn, efficient,
and can run on many different platforms. Python software is free to download and
integrates well with all types of systems.
Difference between C and Python
Feature C Python
Type of Procedural, middle-level High-level, interpreted,
Language programming language object-oriented language
Compiled (requires a compiler to Interpreted (executes line by
Execution
generate machine code) line using interpreter)
Complex, requires more code
Simple, more readable,
Syntax (e.g., semicolons, data types,
fewer lines of code
braces)
Very fast (close to hardware, Slower than C (interpreted,
Speed
compiled into machine code) higher abstraction)
Manual (programmer must
Memory Automatic (has garbage
allocate & free memory using
Management collection)
malloc, free)
System programming, OS
Web development, AI/ML,
development, embedded
Use Cases data science, automation,
systems, performance-critical
scripting
apps
Small, limited built-in functions Huge standard library
Standard
(needs external libraries for (supports math, string, files,
Libraries
many tasks) networking, etc.)
Feature C Python
Highly portable (same code
Less portable (depends on
Portability runs on multiple platforms
compiler and platform)
without change)
Examples printf("Hello World"); print("Hello World")

History of Python Programming Language


The implementation of Python was started in December 1989 by Guido Van
Rossum at CWI in Netherland.
It was initially designed by Guido van Rossum in February 1991 and developed
code (labelled version 0.9.0) to alt.sources by Python Software Foundation.
In 1994, Python 1.0 was released with new features like lambda, map, filter, and
reduce.
Python 2.0 added new features such as list comprehensions, garbage collection
systems.
On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was
designed to rectify the fundamental flaw of the language.
It was mainly developed to emphasize code readability, and its syntax allows
programmers to express concepts in fewer lines of code.

Features of Python Programming Language


Python is a high-level programming language with many features, including:
 Open source and free: Python is free to use, download, and modify.
 Easy to learn: Python has a simple syntax and is easy to code.
 Portable: Python code can be used on different machines without
changes.
 Large standard library: Python comes with a large standard library that
includes modules for web development, database interaction, and more.
 Interpreted: Python is interpreted, so the source code is executed line by
line.
 Dynamically typed: Python doesn't require declaring the type of a
variable.
 Multi-paradigm: Python supports multiple programming paradigms,
including object-oriented programming, procedural programming, and
functional programming.
 Supports GUI: Python supports graphical user interface programming.
Where we can use PYTHON?
 Web development: Python is used for both server-side and backend web
development.
 Software development: Python is used to create software and apps.
 Data analysis: Python is used to analyze data.
 Machine learning: Python is used in machine learning.
 Automating tasks: Python can be used to automate repetitive tasks.
 Scientific and numeric computing: Python has tools and libraries for
scientific and numeric computing, such as SciPy for mathematics, science,
and engineering.
 Business applications: Python can be used to build business applications,
such as ERP and ecommerce systems.
 Blockchain: Python is a strong language for blockchain development due to
its flexibility, functionality, and security.
 Everyday tasks: Python can be used for everyday tasks, such as organizing
finances.
Python programming cycle-
The Python programming cycle, while generally following the principles of
software development, is distinguished by its interpreted nature, which eliminates
the explicit compilation and linking steps found in traditional compiled
languages. The key steps in a typical Python programming cycle are:
 Problem Analysis and Planning:
Define the problem or task the program needs to address.
Break down the problem into smaller, manageable components.
Design the solution, including the overall structure, algorithms, and data
structures.
 Coding:
Write the Python source code based on the design.
Implement functions, classes, and modules as needed.
 Testing and Debugging:
Run the Python application to observe its behavior.
Test the program with various inputs to identify errors or unexpected behavior.
Debug the code to locate and fix issues.
 Iteration and Refinement:
Based on testing results, refine the code and potentially revisit earlier design
or planning steps.
Repeat the testing and debugging process until the program functions correctly
and meets requirements.
 Deployment (if applicable):
Make the program available for use in its intended environment (e.g., local
machine, server).
 Maintenance:
Address any bugs or issues that arise after deployment.
Implement updates, new features, or performance improvements over time.
 Key Difference from Traditional Compiled Languages:
No Explicit Compile/Link Steps: Python's interpreted nature means the source
code is executed directly by the Python interpreter without requiring separate
compilation into machine code or linking of object files. This leads to a faster
development turnaround time.
Rapid Prototyping: The absence of compilation and linking steps facilitates
rapid prototyping and iterative development, allowing developers to quickly
test changes and observe their effects.

Installing Python-
Python is a free, open-source programming language that is available for
everyone to use. It also has a huge and growing ecosystem with a variety of open-
source packages and libraries. If you would like to download and install Python
on your computer you can do for free at python.org.
Python Installation on Windows
1. Step 1: Select Python Version. ...
2. Step 2: Download Python Executable Installer. ...
3. Step 3: Run Executable Installer. ...
4. Step 4: Add Python to PATH (Optional) ...
5. Step 5: Verify Python Is Installed on Windows. ...
6. Step 6: Verify pip is Installed on Windows. ...
7. Step 7: Install virtualenv (Optional)
Python IDE-
A Python IDE, or Integrated Development Environment, is a software application
that provides a comprehensive set of tools and features specifically designed to
streamline and enhance the process of developing software using the Python
programming language. The Python interpreter is the application network
engineers use to execute scripts when testing basic features. An IDE is all-in-one
software with advanced features that enable engineers to write code efficiently.
Introduction to Clean Code:
Clean Code is a term from software development and addresses the clear,
comprehensible, traceable, logical and disciplined implementation of code. The
goal is to produce software efficiently and effectively, and to design the code so
that it is easily readable, changeable, and expandable.

What is Bad Code? Bad code is code that is poorly written, difficult to understand,
and challenging to maintain. It can be more than just syntax errors or minor bugs
Some signs of bad code: Complex, Poorly structured, Lacking documentation,
Duplicative, Excessive dependencies, unnecessarily complex, Not scalable,
Inconsistent in naming, overly verbose, Untested, Hard to read, has non-intuitive
variable names.

What is Clean Code?


Clean code is written with the intention of helping others understand the purpose of
the code so that they can make changes to it in the future.

 Clear: The code is self-explanatory and communicates its functionality.


 Logical: The code has well-formed instructions that work together.
 Formatted: The code has a consistent presentation with regular spacing,
indentation, and character placement.
 Conventional: The code adheres to language conventions and performs
tasks with expected instructions.
 Identifiable: The names follow a regular structure based on language
conventions.
 Responsible: The code is lawful, trustworthy, and respectful.

Text Editors-
A text editor is a tool that is used to write and edit program. They are usually
lightweight and can be great for learning. However, once your program gets
larger, you need to test and debug your code, that's where IDEs come in.
Some text editors for Python:
IDLE, PyCharm, Sublime Text, Visual Studio Code, Jupyter

What is indentation?
In Python, indentation is the use of spaces or tabs at the beginning of a line of
code to group and organize code.
Indentation is a requirement in Python, not just a convention. It's a key part of
Python's syntax and is used to:
 Define blocks of code: Indentation is used to define blocks of code, such
as loops or functions.
 Determine code flow: Indentation determines the flow of code.
 Improve readability: Indentation makes code more readable and easier
to understand.
 Ensure code cleanliness: Consistent indentation keeps code clean and
organized.
 Facilitate collaboration: Consistent indentation helps developers
collaborate seamlessly.
In other programming languages, like C, C++, and Java, curly braces are used to
define a block of code.

Debugging-
Debugging is the process of finding, isolating and resolving coding errors known
as bugs in software programs. Debugging helps uncover the cause of coding
errors, prevent software function issues and improve the overall performance of
software.
Different between Interpreter & Compiler-
Feature Interpreter Compiler
Translates and executes code Translates the entire program
Execution
line by line into machine code, then executes
Speed of Slower (because it checks Faster (machine code is already
Execution line by line) generated before execution)
Feature Interpreter Compiler
Error Shows errors immediately Shows all errors together after
Detection (after the line is executed) compilation
No separate file created; Produces an independent
Output
executes directly executable file (e.g., .exe)
Memory Uses more memory (stores object
Uses less memory
Usage code)
C, C++, Java (with bytecode +
Examples Python, JavaScript, Ruby
JVM compiler), Go

Syntax Errors, Runtime Errors, Semantic Errors-


Syntax Errors- Syntax errors are mistakes in the source code, such as spelling
and punctuation errors, incorrect labels, and so on, which cause an error message
to be generated by the compiler.
Runtime Error- A runtime error occurs when a program you're using or writing
crashes or produces a wrong output. There are several types of runtime errors,
such as a logic error, a memory leak, a division by zero error, an undefined object
error, an I/O device error, and an encoding error.
Semantic Error- A semantic error in computer science refers to an error that
occurs when special data is inserted into a message during transmission, leading
to a failure in the controlled behavior of the system.
Difference between Syntax Error and Semantic Error
Feature Syntax Error Semantic Error
Error in the grammar/structure of
Error in the logic/meaning
Meaning the code (violates programming of the code (code runs but
language rules). does the wrong thing).
May not be caught by the
Caught by the compiler/interpreter compiler; detected only
Detection
during compilation or parsing. when program runs or
produces wrong output.
Program Program cannot run until syntax Program runs, but output is
Execution errors are fixed. incorrect or unintended.
int x = 10 / 0; // compiles,
Example System.out.println("Hello"; // but runtime error (division
(Java) missing closing parenthesis by zero) OR int age =
"twenty";
Feature Syntax Error Semantic Error
Writing a grammatically
Writing a sentence with wrong
correct sentence with wrong
Analogy grammar (e.g., "He go to school
meaning (e.g., "The sun
yesterday"). rises in the west").

Experimental Debugging-
Debugging is also like an experimental science. Once you have an idea what is
going wrong, you modify your program and try again. If your hypothesis was
correct, then you can predict the result of the modification, and you take a step
closer to a working program.
Formal and Natural Languages-
Natural languages are the languages that people speak, such as English, Spanish,
and French. They were not designed by people (although people try to impose
some order on them); they evolved naturally.
Formal languages are languages that are designed by people for specific
applications.
The Difference between Brackets, Braces, and Parentheses in Python-
Symbol Purpose in Python
Function calls & definitions, grouping expressions, defining
Parentheses()
tuples, creating generators
Brackets [] Creating lists, indexing/slicing sequences, list comprehensions
Braces {} Defining dictionaries (key→value) and sets (unique, unordered)

Input and Output Functions:


In Python, program output is displayed using the print() function, while user
input is obtained with the input() function.
Input Syntax: input(prompt)
Output Syntax: print(prompt)

Example:
name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")
Output:
Enter your name: perwej
Hello, perwej ! Welcome!
Example:
color = input("What color is rose?: ")
print(color)
Output:
What color is rose?: Red
Red

Elements of Python
The basic elements of Python, essential for constructing programs and defining
logic, include:
Variables: Named storage locations used to hold data values.
Literals: Fixed values that appear directly in code, such as numbers
(e.g., 10, 3.14), strings (e.g., "hello"), booleans (e.g., True, False), and None.
Keywords: Reserved words with special meanings in Python,
like if, else, for, while, def, class, etc., which cannot be used as identifiers.
Identifiers: Names given to variables, functions, classes, and other program
entities, following specific naming rules.
Operators: Symbols that perform operations on values and variables, such as
arithmetic operators (+, -, *, /), comparison operators (==, !=, <, >), and logical
operators (and, or, not).
Data Types: Classifications of data that determine the operations that can be
performed on them. Common built-in data types include integers (int), floating-
point numbers (float), strings (str), booleans (bool), lists (list), tuples (tuple),
dictionaries (dict), and sets (set).
Control Flow Statements: Structures that dictate the order of execution in a
program. These include:
Conditionals: if, elif, else statements for executing code blocks based on
conditions.
Loops: for and while loops for repeatedly executing code blocks.
Functions: Reusable blocks of code designed to perform a specific task,
promoting modularity and code reuse.
Classes and Objects: Fundamental concepts of Object-Oriented Programming
(OOP) in Python, allowing the creation of custom data types and encapsulating
data and behavior.
Modules and Packages: Mechanisms for organizing and reusing Python code,
allowing for the import of pre-written functionalities.
Python Variables:
Variables are containers for storing data values. Variables are used as
placeholders for information that can be recalled later in the coding process.
Python has no command for declaring a variable. A variable is created the
moment you first assign a value to it.
Example: Output:
x=5 5
y = "John" John
print(x)
print(y)

Variables do not need to be declared with any particular type, and can even
change type after they have been set.
Example: Output:
x=4 # x is of type int Sally
x = "Sally" # x is now of type str
print(x)

Naming Rules of Variables in Python


Must start with a letter or underscore (_)
✅ Valid: name, _count, x1
❌ Invalid: 1name, @value
Can contain letters, digits, and underscores
✅ student_name, marks2, total_sum
❌ total-sum, marks%
Case-sensitive
age, Age, and AGE are different variables.
Cannot be a Python keyword (reserved word)
❌ You can’t use words like if, while, for, class, def, etc.
No special characters or spaces allowed
✅ userName, num_1
❌ user name, num@1
Variable names should be meaningful (not a strict rule, but good practice)
✅ student_age, total_marks
❌ x, y1, temp123 (hard to understand later)
Data-Types:
Python Data types are the classification or categorization of data items. It
represents the 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 the ‘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

To define the values of various data types of Python and check their data types
we use the type() function.

Numeric Data Types in Python


The numeric data type in Python represents the 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 Python int, Python float and Python complex classes
in Python.
Integers - This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to
how long an integer value can be.
Float - This value is represented by the float class. It is a real number with a
floating-point representation. It is specified by a decimal point. Optionally, the
character e or E followed by a positive or negative integer may be appended to
specify scientific notation.
Complex Numbers - A complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j . For example - 2+3j
Example Output
a=5 <class 'int'>
print(type(a)) <class 'float'>
b = 5.0 <class 'complex'>
print(type(b))
c = 2 + 4j
print(type(c))

Sequence Data Type in Python


The sequence Data Type in Python is the 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:
Python String - Python Strings are arrays of bytes representing Unicode
characters. In Python, there is no character data type Python, 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.
Example-
s = 'Welcome to the Geeks World'
print(s)
print(type(s))
print(s[1])
print(s[2])
print(s[-1])
Output-
Welcome to the Geeks World
<class 'str'>
e
l
d
Python List – Lists are just like arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the 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 the sequence inside the square brackets[].
Access List Items In order to access the list items refer to the index number. In
Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just
write List[-3]. Negative indexing means beginning from the end, -1 refers to the
last item, -2 refers to the second-last item, etc.

Example-
a = []
a = [1, 2, 3]
print(a)
b = ["Geeks", "For", "Geeks", 4, 5]
print(b)

Output-
[1, 2, 3]
['Geeks', 'For', 'Geeks', 4, 5]

Example-
a = ["Geeks", "For", "Geeks"]
print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])

Output-
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Python Tuple – Just like a list, a tuple is also 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 Data Types, tuples are created by placing
a sequence of values separated by a ‘comma’ with or without the use of
parentheses for grouping the 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.
Access Tuple Items In order to access the tuple items refer to the index number.
Use the index operator [ ] to access an item in a tuple.
Example-
tup1 = ('Geeks', 'For')
print("\nTuple with the use of String: ", tup1)

Output-
Tuple with the use of String: ('Geeks', 'For')

Example-
tup1 = tuple([1, 2, 3, 4, 5])
print(tup1[0])
print(tup1[-1])
print(tup1[-3])

Output-
1
5
3

Boolean Data Type in Python


Python Data type with 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 the class bool.
Example-
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
The first two lines will print the type of the boolean values True and False, which
is <class 'bool'>. The third line will cause an error, because true is not a valid
keyword in Python. Python is case-sensitive, which means it distinguishes
between uppercase and lowercase letters.
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.

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.
To create an empty set, you must use set(), as {} creates an empty dictionary.
Common Uses of Sets:
Removing duplicates:
Easily convert a list or other iterable to a set to obtain only the unique
elements.
Fast membership testing:
Checking if an element exists in a set using the in keyword is highly efficient.
Mathematical set operations:
Sets support operations like union (| or union()), intersection
(& or intersection()), difference (- or difference()), and symmetric difference
(^ or symmetric_difference()).
Example-
s = {10, 50, 20}
print(s)
print(type(s))
Output-
{10, 50, 20}
<class 'set'>

Example-
s1 = set("GeeksForGeeks")
print("Set with the use of String: ", s1)
s2 = set(["Geeks", "For", "Geeks"])
print("Set with the use of List: ", s2)
Output-
Set with the use of String: {'s', 'o', 'F', 'G', 'e', 'k', 'r'}
Set with the use of List: {'Geeks', 'For'}

Example-
set1 = set(["Geeks", "For", "Geeks"])
print(set1)
for i in set1:
print(i, end=" ")
print("Geeks" in set1)

Output-
{'Geeks', 'For'}
Geeks For True

Example-
# Create a set
fruits = {"apple", "banana", "cherry"}
# Add an element
fruits.add("orange")
print(fruits) # Output might be {'cherry', 'apple', 'orange', 'banana'} (order varies)
# Try to add a duplicate
fruits.add("apple")
print(fruits) # Output remains the same, 'apple' is not added again
# Check for membership
if "banana" in fruits:
print("Banana is in the set.")
# Remove an element
fruits.remove("cherry")
print(fruits)
# Perform set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1 | set2 # or set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 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 that hold only a single value as an element,
a Dictionary holds a key: value pair. Key-value is provided in the 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.

Accessing Key-value in Dictionary In order to access the items of a dictionary


refer to its key name. Key can be used inside square brackets. Using get() method
we can access the dictionary elements.

Example-
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)

Output-
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Example-
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
print(d['name'])
print(d.get(3))

Output-
For
Geeks

Here are some quick example for Data Types in Python


 x = "Hello World" #string
 x = 50 #integer
 x = 60.5 #float
 x = 3j #complex
 x = ["geeks", "for", "geeks"] #list
 x = ("geeks", "for", "geeks") #tuple
 x = {"name": "Suraj", "age": 24} #dictionary
 x = {"geeks", "for", "geeks"} #set
 x = frozenset({"geeks", "for", "geeks"}) #frozenset
 x = True #boolean
 x = b"Geeks" #bytes
 x = bytearray(4) #bytearray
 x = memoryview(bytes(6)) #memoryview
 x = None #special value

Type conversion in Python


Type conversion in Python refers to the process of changing the data type of a
value from one type to another. This can be done either automatically by the
Python interpreter (implicit conversion) or explicitly by the programmer using
built-in functions (explicit conversion or type casting).

1. Implicit Type Conversion (Coercion):


This occurs automatically when Python needs to perform an operation involving
different data types and can safely convert one type to another without data
loss. For example, when adding an integer and a float, Python implicitly converts
the integer to a float before performing the addition.
Example-
x = 10 # integer
y = 5.5 # float
result = x + y # x is implicitly converted to float
print(result)
print(type(result))

Output-
15.5
<class 'float'>

2. Explicit Type Conversion (Type Casting):


This involves the programmer explicitly converting a value from one data type to
another using built-in functions. This is necessary when implicit conversion is not
possible or when a specific data type is required for an operation. Common
functions for explicit conversion include:
int(): Converts to an integer.
float(): Converts to a floating-point number.
str(): Converts to a string.
list(): Converts to a list.
tuple(): Converts to a tuple.
set(): Converts to a set.
dict(): Converts to a dictionary.

Example-
num_str = "123"
num_int = int(num_str) # Explicitly convert string to integer
print(num_int)
print(type(num_int))
price_float = 25.99
price_int = int(price_float) # Explicitly convert float to integer (truncates decimal)
print(price_int)
print(type(price_int))

Output-
123
<class 'int'>
25
<class 'int'>

Data Loss: Explicit conversion, especially from a larger data type to a smaller
one (e.g., float to int), can lead to data loss.
Type Compatibility: Not all type conversions are possible (e.g., converting a
non-numeric string to an integer will raise a ValueError).
Error Handling: When performing explicit conversions, particularly with user
input, it is good practice to use try-except blocks to handle
potential ValueError exceptions.

Operators:
Operators are used to perform operations on variables and values.
For example- We use the + operator to add together two values-
Example-
print(10 + 5)
Output:
15
Python divides the operators in the following groups:
 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Arithmetic operators:
Arithmetic operators are used with numeric values to perform common
mathematical operations:
1. Addition +
x+y
Example:
x=5
y=3
print(x + y)
Output:
8

2. Subtraction –
x–y
Example:
x=5
y=3
print(x - y)
Output:
2

3. Multiplication *
x*y
Example:
x=5
y=3
print(x * y)
Output:
15

4. Division /
x/y
Example:
x = 12
y=3
print(x / y)
Output:
4

5. Modulus %
x%y
Example:
x=5
y=2
print(x % y)
Output:
1

6. Exponentiation **
x ** y
Example:
x=2
y=5
print(x ** y) #same as 2*2*2*2*2
Output:
32

7. Floor division //
x // y
Example:
x = 15
y=2
print(x // y) #the floor division rounds the result down to the nearest
whole number
Output:
7

Assignment operators:
Assignment operators are used to assign values to variables

1. Assign =
Example:
x=5
print(x)
Output:
5

2. Add and assign + =


Example:
x=5
x += 3
print(x)
Output:
8

3. Subtract and assign - =


Example:
x=5
x -= 3
print(x)
Output:
2

4. Multiply and assign * =


Example:
x=5
x *= 3
print(x)
Output:
15

5. Divide and assign / =


Example:
x=5
x /= 3
print(x)
Output:
1.6666666666666667

6. Modulus and assign % =


Example:
x=5
x%=3
print(x)
Output:
2

7. Floor division and assign // =


Example:
x=5
x//=3
print(x)
Output:
1

8. Exponentiation and assign ** =


Example:
x=5
x **= 3
print(x)
Output:
125

9. Bitwise AND and assign & =


Example:
x=5
x &= 3
# combines the values of two variables using a bitwise AND operation
and assigns the result to the variable on the left.
# x = 5: The binary representation of 5 is 101
# x &= 3: The binary representation of 3 is 011
# print(x): The output is 1, which is the binary representation of 001
print(x)
Output:
1

10. Bitwise OR and assign | =


Example:
x=5
x |= 3
# performs a bitwise OR operation on the left and right operands, and
assigns the result to the left operand.
# = 5: The binary representation of 5 is 101
# x = 3: The binary representation of 4 is 011
# print(x): The output is 7, which is the binary representation of 111
print(x)
Output:
7

11. Bitwise XOR and assign ^ =


Example:
x=5 #101
x ^= 3 #011
# compares two binary values and returns a result based on whether the
bits match:
# 1: If one input is 1 and the other is 0
# 0: If both inputs are 1 or both are 0
print(x)
Output:
6 #110

12. Walrus Operator : =


Example:
print (x := 3)
# We can use this walrus operator to assign a value and do condition
check at the same time. So, we can use variable a not just in statement
also after that. it will simply assign new value into variable and enables
condition check.
Output:
3

Comparison operators:
Comparison operators are used to compare two values
1. Equal = =
Example:
x=5
y=3
print(x = = y)
# returns False because 5 is not equal to 3
Output
False

2. Not equal !=
Example:
x=5
y=3
print(x != y)
# returns True because 5 is not equal to 3
Output
True

3. Greater than >


Example:
x=5
y=3
print(x > y)
# returns True because 5 is greater than 3
Output
True

4. Less than <


Example:
x=5
y=3
print(x < y)
# returns False because 5 is not less than 3
Output
False
5. Greater than or equal to >=
Example:
x=5
y=3
print(x >= y)
# returns True because 5 is greater, or equal, to 3
Output
True

6. Less than or equal to <=


Example:
x=5
y=3
print(x <= y)
# returns False because 5 is neither less than or equal to 3
Output
False

Logical operators:
Logical operators are used to combine conditional statements

1. And
Returns True if both statements are true
Example:
x=5
print(x > 3 and x < 10)
# returns True because 5 is greater than 3 AND 5 is less than 10
Output
True

2. Or
Returns True if one of the statements is true
Example:
x=5
print(x > 3 or x < 4)
# returns True because one of the conditions are true (5 is greater than 3,
but 5 is not less than 4)
Output
True
3. Not
Reverse the result, returns False if the result is true
Example:
x=5
print(not(x > 3 and x < 10))
# returns False because not is used to reverse the result
Output
False

Identity operators:
1. Is
Returns True if both variables are the same object
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is z)
# returns True because z is the same object as x
print(x is y)
# returns False because x is not the same object as y, even if they have the
same content
print(x = = y)
# to demonstrate the difference betweeen "is" and "= =": this comparison
returns True because x is equal to y
Output:
True
False
True
2. Is not
Returns True if both variables are not the same object
Example:
x = ["apple", "banana"]
y = ["apple", "banana"]
z=x
print(x is not z)
# returns False because z is the same object as x
print(x is not y)
# returns True because x is not the same object as y, even if they have the
same content
print(x != y)
# to demonstrate the difference betweeen "is not" and "!=": this
comparison returns False because x is equal to y
Output:
False
True
False
Membership operators:
1. In
Returns True if a sequence with the specified value is present in the object
Example:
x = ["apple", "banana"]
print("banana" in x)
# returns True because a sequence with the value "banana" is in the list
Output:
True

2. Not in
Returns True if a sequence with the specified value is not present in the
object
Example:
x = ["apple", "banana"]
print("pineapple" not in x)
# returns True because a sequence with the value "pineapple" is not in the
list
Output:
True

Bitwise operators:
1. AND &
Sets each bit to 1 if both bits are 1
Example:
print(6 & 3)
# The & operator compares each bit and set it to 1 if both are 1, otherwise it
is set to 0:
6 = 0000000000000110
3 = 0000000000000011

2 = 0000000000000010

Output:
2

2. OR |
Sets each bit to 1 if one of two bits is 1
Example:
print(6 | 3)
# The | operator compares each bit and set it to 1 if one or both is 1,
otherwise it is set to 0:
6 = 0000000000000110
3 = 0000000000000011

7 = 0000000000000111

Output:
7

3. XOR ^
Sets each bit to 1 if only one of two bits is 1
Example:
print(6 ^ 3)
#The ^ operator compares each bit and set it to 1 if only one is 1, otherwise
(if both are 1 or both are 0) it is set to 0:
6 = 0000000000000110
3 = 0000000000000011

5 = 0000000000000101

Output:
5

4. NOT ~
Inverts all the bits
Example:
print(~3)
The ~ operator inverts each bit (0 becomes 1 and 1 becomes 0).
Inverted 3 becomes -4:
3 = 0000000000000011
-4 = 1111111111111100
Output:
-4
5. Zero fill left shift <<
Shift left by pushing zeros in from the right and let the leftmost bits fall off
Example:
print(3 << 2)
#The << operator inserts the specified number of 0's (in this case 2) from the
right and let the same amount of leftmost bits fall off:
If you push 00 in from the left:
3 = 0000000000000011
becomes
12 = 0000000000001100
Output:
12

6. Signed Right Shift >>


Shift right by pushing copies of the leftmost bit in from the left, and let the
rightmost bits fall off
Example:
print(8 >> 2)
The >> operator moves each bit the specified number of times to the right.
Empty holes at the left are filled with 0's.
If you move each bit 2 times to the right, 8 becomes 2:
8 = 0000000000001000
becomes
2 = 0000000000000010
Output:
2

Precedence and Associativity of Operators in Python;


In Python, operators have different levels of precedence, which determine
the order in which they are evaluated. When multiple operators are present in
an expression, the ones with higher precedence are evaluated first. In the
case of operators with the same precedence, their associativity comes into
play, determining the order of evaluation.
Precedence Operators Description Associativity
1 () Parentheses Left to right
2 x[index], Subscription, Left to right
x[index:index] slicing
3 await x Await expression N/A
4 ** Exponentiation Right to left
5 +x, -x, ~x Positive, Right to left
negative, bitwise
NOT
6 *, @, /, //, % Multiplication, Left to right
matrix, division,
floor division,
remainder
7 +, – Addition and Left to right
subtraction
8 <<, >> Shifts Left to right
9 & Bitwise AND Left to right
10 ^ Bitwise XOR Left to right
11 | Bitwise OR Left to right
12 in, not in, is, is Comparisons, Left to Right
not, <, <=, >, >=, membership
!=, == tests, identity
tests
13 not x Boolean NOT Right to left
14 and Boolean AND Left to right
15 or Boolean OR Left to right
16 if-else Conditional Right to left
expression
17 lambda Lambda N/A
expression
18 := Assignment Right to left
expression
(walrus operator)

Expressions in Python-

An expression is any piece of code that evaluates to a value. Unlike statements,


which perform actions, expressions compute and return results

It's a combination of values, variables, operators, and function calls that


Python can evaluate to produce a value. Even a literal or variable alone counts.
For example, 42, "hello", or x are all valid expressions.

Example What It Does


5+3 Arithmetic expression → returns 8
x*2 Multiplies variable x by 2
len("hi") Function call returning integer
(a if a > b else b) Conditional (ternary) expression
Example What It Does
[i*i for i in range(5)] List comprehension → builds a list of squares
{n: n*n for n in
Dict/set comprehension → builds a dict/set
range(5)}
(x := some_function()) Assignment expression (walrus operator, Python 3.8+)

Solve the operator precedence examples.


a = 20, b = 10, c = 15, d = 5, e = 0
e = (a + b) * c / d
e = ((a + b) * c) / d
e = (a + b) * (c / d)
e = a + (b * c) / d

1. e = (a + b) * c / d
(a + b) = 30
30 * c = 30 * 15 = 450
450 / d = 450 / 5 = 90.0

e = 90.0

2. e = ((a + b) * c) / d
(a + b) = 30
30 * c = 450
450 / 5 = 90.0

e = 90.0

3. e = (a + b) * (c / d)
(a + b) = 30
(c / d) = 15 / 5 = 3.0
30 * 3.0 = 90.0

e = 90.0

4. e = a + (b * c) / d
(b * c) = 10 * 15 = 150
150 / d = 150 / 5 = 30.0
a + 30.0 = 20 + 30.0 = 50.0

e = 50.0
Statement in Python?
A statement in Python is a single line of code that instructs the Python
interpreter to perform an action.
Every line you write in Python (like assigning a value, printing, looping, etc.) is
considered a statement.
Types of Statements in Python with Examples
Assignment Statement- Assigns a value to a variable.
x = 10
name = "Alice"
Print Statement- Displays output.
print("Hello, World!")
Conditional Statement- Controls the flow of execution based on conditions.
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Looping Statement- Executes a block of code repeatedly.
for i in range(3):
print("Iteration:", i)
Import Statement- Used to include external modules or libraries.
import math
print(math.sqrt(25))
Function Definition Statement- Defines a reusable block of code.
def greet():
print("Hello from function!")
greet()

You might also like