Module 1 Python
Module 1 Python
Laboratory
[Link] to Learn: Simple syntax like English. •Web Development: Django, Flask.
[Link] Language: Code executes line-by-line. •Machine Learning: TensorFlow, Scikit-
[Link] Typed: No need to declare variable learn.
types explicitly. •Scripting and Automation: Automate
[Link] Libraries: Offers prebuilt modules for mundane tasks.
almost any task (e.g., NumPy, Pandas). •Game Development: Pygame.
[Link]-Platform: Works seamlessly across Windows,
Mac, and Linux.
print("Hello, World!")
Program 1 : Hello World
Language Program
C #include<stdio.h>
void main()
{
printf(“ Hello World”);
}
Java class HelloWorldApp
{
public static void main(String[] args)
{
[Link]("Hello World!");
}
}
Python print “Hello World”
Advantages vs Disadvantages
Career Opportunities
Types of IDE’s
An IDE (Integrated Development Environment) is a software application that provides
comprehensive tools to write, debug, and run programs. Python supports a wide range of IDEs, each
catering to specific needs.
1. Anaconda
Anaconda is a popular Python distribution that comes pre-installed
with tools and libraries focused on data science, machine learning,
and scientific computing.
•Key Features:
• Comes with pre-installed Python and R environments.
• Includes a package manager (conda) for installing and
managing libraries.
• Provides integrated tools like Jupyter Notebook and Spyder.
• Ideal for large-scale data analysis, visualization, and machine
learning tasks.
• Platform-independent and works on Windows, macOS, and
Linux.
Included Tools:
a. Jupyter Notebook:
1. A web-based interactive development environment.
2. Allows writing and executing code in individual
cells, making it ideal for experimentation and
visualization.
3. Commonly used for:
1. Plotting graphs and charts.
2. Real-time code execution and data
visualization.
3. Markdown support for documentation.
b. Spyder:
•Features:
• Variable Explorer: View and modify variables during
execution.
• Integrated IPython console for interactive coding.
• Debugging and profiling tools for optimizing code
performance.
• Key Features:
• Code Navigation:
• Jump to function definitions and usages with ease.
• Debugging Tools:
• Includes a visual debugger to step through code, inspect
variables, and fix errors.
• Integrated Terminal:
• Allows executing shell commands directly within the IDE.
• Version Control Integration:
• Supports Git, SVN, and other version control systems for
collaborative development.
• Supports Python frameworks like Django, Flask, and FastAPI.
•When to Use PyCharm:
• Ideal for web development, automation projects, and large
applications requiring advanced debugging.
[Link] Code (Visual Studio Code):
•Features:
• Python extensions (e.g., Microsoft’s Python extension) enable
linting, debugging, and auto-completions.
• Integrated terminal for running commands.
• Marketplace for additional plugins like Jupyter Notebooks, Git
integration, and Docker tools.
•Ideal for:
• Collaborative development and sharing of
notebooks.
• Running deep learning models (TensorFlow,
PyTorch).
• Sharing notebooks via Google Drive.
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Lab Setup
Python Keywords
Python Keywords
Python Identifiers
Python Variables
Python has no command for declaring a Variables do not need to be declared with
variable. A variable is created the any particular type, and can even change
moment you first assign a value to it. type after they have been set.
Python Variables Naming Convention
Python Variables Naming Convention
Python Variables
CASTING: If you want to specify the data type Python allows you to assign values to multiple
of a variable, this can be done with casting variables in one line. And you can also assign
the same value to multiple variables in one line as
follows.
a=10>5 a=5>10
print(a) # True print(a) #False
Representing Binary, Octal and Hexadecimal
Numbers
binary number should be written by prefixing 0b or 0B before the
value
Binary
eg. 0b110110, 0B10101001 are treated as binary numbers.
octal numbers are indicated by prefixing 0o or 0O before the actual
value
Octal
eg. 0o145 or 0O773
Hexadecimals numbers are witten by prefixing 0x or 0X before the
value
Hexadecimal
eg. 0xA180 or 0X11fb91
Python Casting
• Depending on the type of data, Python internally assumes the datatype for the
variable.
• But sometimes, the programmer wants to convert one datatype into another type.
• This is called type conversion or coercion
Python Casting
int(x) to convert the number x into int types
eg. x=15.56
int(x) # 15
float(x) to convert the number x into float types
eg. x=15
float(x) # 15.0
complex(x) convert x into a complex number with real part x and imaginary part
zero.
eg. x=10
n=complex(x) # 10+0j
complex(x,y) convert x into a complex number with real part x and imaginary part y.
eg. x,y=10,5
n=complex(x,y) # 10+5j
III) Sequences in Python
range Datatype
• We can use a starting number, an ending number & a step value in the range as:
r=range(30, 40, 2)
eg: for i in range(10, 40, 2):
print(i)
V) Sets
Points to note:
• Set does not maintain the order of the elements.
• The repeated element 20 is stored and displayed only once.
• Since sets are unordered we cannot retrieve the elements using indexing or slicing
operations.
V) Sets
• Instead:
• update() – method is used to add elements to a set
• remove() – method is used to remove any particular element.
Example:
s={10, 20, 30, 40}
[Link]([50, 60]) # any no of item can be updated
print(s)
[Link](50) #only one item can be removed at a time.
print(s)
V) Sets
frozenset Datatype
• The frozenset datatype is same as the set datatype.
• The main difference is that the elements in the set datatype can be modified.
• But the elements of frozenset elements cannot be modified.
• We can create a frozenset by passing a set to frozenset()
Example:
s={10,20,30,40}
fs=frozenset(s)
print(fs)
V) Sets
frozenset Datatype
• update() and remove() methods will not work on frozenset since they cannot be
modified or updated.
VI) Mapping Types
• A map represents a group of elements in the form of key value pairs so that when
the key is given, we can retrieve the value associated with it.
• The ‘dict’ represents a ‘dictionary’ that contains pairs of elements such that the
first element represents the key and the next one becomes its value.
Example:
separates key & value
• Languages like C and Java contain char datatype that represents a single
character.
• Python does not have a char datatype to represent individual character.
• It has str datatype which represents strings.
• String is composed of several characters.
• Think of a character, think of it as an element in a string.
Python Operators
Operators are special symbols or keywords in Python that perform operations on values or variables. Python provides
several types of operators, each serving a specific purpose. These operators allow developers to perform
computations, comparisons, logical evaluations, and other operations efficiently.
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. IDENTITY OPERATORS
6. MEMBERSHIP OPERATORS
7. BITWISE OPERATORS
Python Operators – Arithmetic Operators
Python Operators – Assignment Operators
Python Operators – Relational Operators
Python Operators – Logical Operators
Python Operators – Bitwise Operators
Python Operators – Membership Operators
Python Operators – Identity Operators
Python STRINGS
index
0 1 2 3 4 5 6 7 8 9 10
str C O R E P Y T H O N
Python - Slicing Strings
• By leaving out the start index, the range will start at the first character:
• By leaving out the end index, the range will go to the end:
Python - Modify Strings
• Python has a set of built-in methods that you can use on strings.
❖Upper Case
❖Lower Case
Python - Modify Strings
❖Remove Whitespace
❖Replace String
Python - String Concatenation
❖To concatenate, or combine, two strings you can use the + operator.
❖You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
Python - Format – Strings – More examples
❖ But we can combine strings and numbers by using the format() method.
❖ The format() method takes the passed arguments, formats them, and places them in the
string where the placeholders {} are.
Python - Format – Strings – More examples
❖ You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders
Python - Escape Characters
❖To insert characters that are illegal in a string, use an escape character.
❖An escape character is a backslash \ followed by the character you want to insert.
❖You will get an error if you use double quotes inside a string that is surrounded by
double quotes:
Python - Escape Characters
❖To fix this problem, use the escape character \":
Python - Escape Characters
❖Another way of doing it:
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
find() Searches the string for a specified value and returns the position of
where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of
where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it
was found
rindex() Searches the string for a specified value and returns the last position of where it
was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
Python - String Methods
❖All string methods returns new values. They do not change the original string.
Method Description
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Python - String Methods Demo
Note: All string methods return new values. They do not change the original string.
Python - String Methods Demo
Insert Items
▪ To insert a list item at a specified index, use the insert() method.
▪ The insert() method inserts an item at the specified index:
Add List Items
Extend List
▪ To append elements from another list to the current list, use the extend() method.
▪ The extend() method does not have to append lists, you can add any iterable object
(tuples, sets, dictionaries etc.).
Remove List Items
Remove Specified Item
▪ The remove() method removes the specified item.
• The values() method will return a list of all the values in the dictionary.
• The items() method will return each item in a dictionary, as tuples in a list.
Dictionary
• Change the value of a specific item by referring to its key name:
Dictionary
• The update() method will update the dictionary with the items from the given argument.
• The argument must be a dictionary, or an iterable object with key:value pairs.
Dictionary
• There are several methods to remove items from a dictionary:
• The pop() method removes the item with the specified key name:
• The del keyword removes the item with the specified key name:
• To add items from another set into the current set, use the update() method.
Set - Methods
• To remove an item in a set, use the remove(), or the discard() method.
Set - Methods
• The pop() method to remove an item.
• This method will remove a random item, so you cannot be sure what item that gets
removed.
Set - Methods
• The clear() method empties the set:
• The difference() method returns a set containing the difference between two or more sets
Python ARRAYS
• An array is a data structure that holds multiple values of the same data type. Unlike lists, arrays
provide better performance for certain operations because they are more memory-efficient when
dealing with numerical data.
• However, Python does not have a built-in array data structure; instead, the array module and third-
party libraries like NumPy are commonly used for array implementation.
1. Introduction to Arrays
• Arrays are collections of elements of the same type stored in contiguous memory locations.
• Arrays allow for:
• Storing multiple values under a single name.
• Performing operations like indexing, slicing, and iteration.
Python ARRAYS - Creating Arrays
• Using the array Module:
• The array module is a standard library for creating arrays in Python.
Syntax:
# 2D array
matrix = [Link]([[1, 2, 3], [4, 5, 6]])
print(matrix)
Program 2a: Addition of two numbers
C Java Python