0% found this document useful (0 votes)
2 views133 pages

Module 1 Python

The document provides an overview of Python programming, covering its basics, key features, applications, and various integrated development environments (IDEs) like Anaconda, PyCharm, and VS Code. It discusses Python's data types, operators, and variable management, emphasizing its ease of use and versatility for tasks ranging from web development to machine learning. Additionally, it includes examples and explanations of Python's syntax and functionalities.

Uploaded by

manvitshetty07
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)
2 views133 pages

Module 1 Python

The document provides an overview of Python programming, covering its basics, key features, applications, and various integrated development environments (IDEs) like Anaconda, PyCharm, and VS Code. It discusses Python's data types, operators, and variable management, emphasizing its ease of use and versatility for tasks ranging from web development to machine learning. Additionally, it includes examples and explanations of Python's syntax and functionalities.

Uploaded by

manvitshetty07
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

Python Programming

Laboratory

By: Prof. ANIKET KORE


By: Prof. Sridhar Iyer
Module 1 : Python Basics, Control Structure and Data Structures
Introduction to
Python
Python is a powerful, high-level, and
versatile programming language created
by Guido van Rossum in 1991.

Its simple syntax makes it beginner-


friendly while its robust libraries make it
suitable for complex applications like web
development, machine learning, data
analysis, and more.
Key Features and Applications of Python

Key Features of Python: Applications:

[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.

[Link] in Jupyter Notebook:

# Example of interactive cell execution


a = 10
b = 20
print("Sum:", a + b) # Output: Sum: 30
Included Tools:

b. Spyder:

•A lightweight IDE included in the Anaconda distribution.


•Specifically designed for data scientists and engineers.

•Features:
• Variable Explorer: View and modify variables during
execution.
• Integrated IPython console for interactive coding.
• Debugging and profiling tools for optimizing code
performance.

# Code snippet for Spyder


import numpy as np
data = [Link]([1, 2, 3, 4])
print("Mean:", [Link]()) # Output: Mean: 2.5
2. PyCharm
PyCharm is a professional IDE specifically designed for Python
development. It offers robust tools to handle large-scale projects
efficiently.

• 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):

•A lightweight and highly customizable IDE developed by Microsoft.


•Popular due to its support for multiple languages, including Python,
JavaScript, and HTML.

•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.

[Link] (Integrated Development and Learning Environment):

•Python’s default IDE, lightweight and simple.


•Ideal for beginners.
•Features:
• A built-in interpreter for immediate feedback.
• Basic code editing and debugging tools.
5. Google Colab:
•A cloud-based Jupyter Notebook environment provided by
Google.
•No installation is required; runs on a browser.
•Free access to GPUs/TPUs for machine learning tasks.

•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.

Get the type: You can get the data type of a


variable with the type() function.
Python Data Types
A datatype represents the type of data stored into a variable or memory.
Data Types
• A datatype represents the type of data stored into a variable or memory.
• BUILT-IN DATATYPES are of 5 types:
1. None Type
2. Numeric Type
3. Sequences
4. Sets
5. Mappings
I) None Type
• The None datatype represents an object that does not contain any value. (like
‘null’ object in Java).
• None keyword is an object , it is of datatype of class NoneType.
• One of the uses of None is that it is used inside a function as a default value of the
arguments.
II) Numeric Type

• The numeric types represent numbers. There are 3 subtypes:


• int
• float
• complex
int Datatype
• Represents an integer number. eg. 200, -50, 0, etc.
• There is no limit for the size of an int datatype.
• It can store very large integer numbers conveniently.
II) Numeric Type
float Datatype
• Represents floating point number.
• A floating point number is a number that contains a decimal point. eg. 0.5, -
3.47567, 0.0001 etc.
• Floating point numbers can also be written in scientific notation where we use ‘e’
or ‘E’ to represent power of 10. eg. 2.5x104 is 2.5E4
II) Numeric Type
Complex Datatype
• A complex number is a number that is written in the form of a+bj or a+bJ.
• Here a= real part of the number, b= imaginary part of the number.
• j or J indicates the square root value of -1.
II) Numeric Type
bool Datatype
• The bool datatype in Python represents Boolean values.
• False represents 0
• True represents 1
• A blank String “” is also represented as False.

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

• A sequence represents a group of elements or items.


eg. a group of integer numbers will form a sequence.
• There are six types of sequences:
• Str
• List
• tuple
• range
• Set
• Mapping
I) String

• str represents string datatype


• A string is represented by a group of characters.
• Strings are enclosed in single quotes or double quotes.
• You can assign a multiline string to a variable by using three quotes.
** We can also write strings inside triple, double or single quotes to span a group of
lines including spaces.
eg. str=‘’’ Hi ‘Kids’ ‘’’
II) List

• Lists in Python are similar to arrays in C or Java.


• A list represents a group of elements.
• The main difference between a list and an array is that a list can store different
types of elements.
• The size of list can grow dynamically in memory but array size is fixed & cannot
grow at runtime.
eg. list=[10, -20, 15.5, “Sammy”, ‘Dash’]

• We can perform different slicing operations on this.


III) Tuples
• Tuples are used to store multiple items in a single variable.
• Tuple items can be of any data type.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed.
• To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple.
• E.g.
thistuple = ("apple",)
print(type(thistuple))
tuple1 = ("abc", 34, True, 40, "male")
IV) Range
• The range datatype represents a sequence of numbers.
• The numbers in the range are not modifiable.
• Generally range is used for repeating a for loop for a specific number of times.
• To create range write:
• r=range(10) #range is created from 0 to 9
eg. To display a no. 0 to 10
for i in range(11):
print(i)
IV) Range

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

• A set is an unordered collection of elements much like a set in Maths.


• The order of elements is not maintained in the sets.
• It means the elements may not appear in the same order as they are entered into
the set.
• A set does not accept duplicate elements.
• There are two sub types in sets:
• set datatype
• frozen datatype.
V) Sets
set Datatype
• To create a set, enter the elements separated by commas inside curly braces { }
s={10,20,30,20,50} # duplicate data present
print(s) #may dsplay {50, 10, 20, 30}

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

d={10 : ‘Mumbai’ , 11 : ‘Delhi’ , 12 : ‘Rajasthan’}


name of the associated value
key
dictionary
A little about Characters in Python

• 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

• A string represents a group of characters.


• Strings in python are surrounded by either single quotation marks, or double quotation
marks.
• 'hello' is the same as "hello".
String Length
• To get the length of a string, use the len() function
• Eg.
• a = "Hello, World!"
print(len(a))
Strings in Python – Indexing
• Index represents the position number.
• Index is written using square brackets [].
• By specifying the position number through an index, we can refer to the individual
elements of a string.

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

• You can return a range of characters by using the slice syntax.


• Specify the start index and the end index, separated by a colon, to return a part of the
string.
• Syntax:
• Stringname [start : stop : stepsize]
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.

❖To add a space between them, add a " ":


Python - Format - Strings
❖The format() method takes unlimited number of arguments, and are placed into the
respective placeholders:
Python - Format - Strings

❖You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:
Python - Format – Strings – More examples

❖ We cannot combine strings and numbers like this

❖ 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

• The index() method raises an exception if the value is not found.


• The index() method is almost the same as the find() method, the only difference is that the find() method returns
-1 if the value is not found.
Python LISTS

• A list in Python is used to store the sequence of various types of data.


• Python lists are of mutable type which means that we can modify its element after it is
created.
• The items in the list are separated with the comma (,) and enclosed with the square brackets [].
• Lists are one of 4 built-in data types in python used to store collections of data, the other 3 are
TUPLE, SET, and DICTIONARY, all with different qualities and usage.
• Lists are created using square brackets.
List indexing and splitting
• The indexing is processed in the same way as it happens with the strings.
• The elements of the list can be accessed by using the slice operator [].
• The index starts from 0 and goes to length -1.
• The first element of the list is stored at the 0th index, the second element of the list is stored at the
1st index, and so on.
Negative indexing
• Python provides the flexibility to use the negative indexing also.
• The negative indices are counted from the right.
• The last element (rightmost) of the list has the index -1; its adjacent left element is
present at the index -2 and so on until the left-most elements are encountered.
Negative indexing
Add List Items
Append Items
▪ To add an item to the end of the list, use the append() method:

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.

Remove Specified Index


▪ The pop() method removes the specified index.
▪ If you do not specify the index, the pop() method removes the last item.
▪ The del keyword can also delete the list completely.
Remove List Items
Remove Specified Item
Remove List Items
Clear the List
▪ The clear() method empties the list.
▪ The list still remains, but it has no content.
Sort List Items
▪ List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:

▪ Sort the list numerically


Sort List Items
▪ To sort descending, use the keyword argument reverse = True
Reverse List Items
▪ The reverse() method reverses the current sorting order of the elements.
List Extra methods
1. List Length:
To determine how many items a
list has, use the len() function:

2. List Items - Data Types:


List items can be of any data
type. Also, A list can contain
different data types.

3. The list() Constructor


It is also possible to use the list()
constructor when creating a new
list.
Loop Lists
1. Loop Through a List
• You can loop through the list items by using a for loop.

2. LOOP THROUGH THE INDEX NUMBERS


• You can also loop through the list items by referring to their
index number.
• Use the range() and len() functions to create a suitable
iterable.

3. USING A WHILE LOOP


• You can loop through the list items by using a while loop.
• Use the len() function to determine the length of the list,
then start at 0 and loop your way through the list items by
referring to their indexes.
• Remember to increase the index by 1 after each iteration.
List Comprehension
• LIST COMPREHENSION offers a shorter syntax when you want to create a new list based on
the values of an existing list.
• Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter
“A" in the name.
• Without list comprehension you will have to write a for statement with a conditional test inside,
whereas with list comprehension you can do all that with only one line of code.
List Methods
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Python TUPLES
• Tuples are used to store multiple items in a single variable.
• A tuple is a collection which is ordered and unchangeable.
• Tuples are written with round brackets.
• Tuple items are ordered, unchangeable, and allow duplicate values.
• Tuple items are indexed.
Tuple Length
• To determine how many items a tuple has, use the len() function.
tuple
Create Tuple With One Item
• To create a tuple with only one item, you have to add a comma after the item,
otherwise Python will not recognize it as a tuple
tuple
Access Tuple Items
• You can access tuple items by referring to the index number, inside square
brackets
tuple
tuple
• Tuples are unchangeable, meaning that you cannot change, add, or remove items
once the tuple is created.
• Convert the tuple into a list to be able to change it
tuple
Tuple Methods
Method Description
count() Returns the number of times a specified value occurs in a tuple
index() Searches the tuple for a specified value and returns the position of where
it was found
Python DICTIONARY

• Dictionaries are used to store data values in key:value pairs.


• A dictionary is a collection which is ordered, changeable and do not allow duplicates.
• Dictionaries are written with curly brackets, and have keys and values:
Dictionary
• To determine how many items a dictionary has, use the len() function.

• Access the items of a dictionary by referring to its key name


Dictionary
• The keys() method will return a list of all the keys in the dictionary.

• 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 popitem() method removes the last inserted item


Dictionary
• The clear() method empties the dictionary:

• The del keyword removes the item with the specified key name:

• The del keyword can also delete the dictionary completely:


Dictionary Comprehension
• Dictionary Comprehension is creating dictionaries using simple expressions.
• A dictionary comprehension takes the form:
{key: value for (key, value) in iterable}
Python SET

• Sets are used to store multiple items in a single variable.


• Sets are written with curly brackets.
• Set items are unordered, and
unchangeable, andduplicate
does not allow do not allow
values duplicate values.
Set - Methods
• Add an item to a set, using the add() method:

• 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 del keyword deletes the set completely:


Set - Methods
• The union() method returns a new set with all items from both sets:

• The update() method inserts the items in set2 into set1:


Set - Methods
• The intersection() method will return a new set, that only contains the items that are
present in both sets.

• 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:

• typecode specifies the type of array elements (e.g., integers, floats).


•Example type codes:
•'i' for signed integers.
•'f' for floating-point numbers.
•'u' for Unicode characters.
Python ARRAYS – Array Operations
Accessing Elements
from array import array
arr = array('i', [10, 20, 30, 40, 50])
Removing Elements:
print(arr[0]) # Output: 10
•Using remove(value): Removes the first
print(arr[-1]) # Output: 50 (last element)
occurrence of the specified value.
•Using pop(index): Removes the element at the
Traversing an Array:
specified index.
for num in arr:
print(num)
[Link](30) # Removes the value 30
[Link](2) # Removes the element at index 2
Adding Elements:
•Using append(): Adds an element to the end.
Slicing Arrays:
•Using extend(): Adds multiple elements.
Slicing retrieves a subset of elements.
[Link](60) # Adds a single element
print(arr[1:4]) # Output: array('i', [20, 40, 50])
[Link]([70, 80, 90]) # Adds multiple elements
print(arr) # Output: array
('i', [10, 20, 30, 40, 50, 60, 70, 80, 90])
Python ARRAYS – Functions of Array Module
Python ARRAYS – Examples
Example 1: Sum of Elements in an Array Example 3: Reverse an Array

from array import array arr = array('i', [1, 2, 3, 4, 5])


[Link]()
arr = array('i', [10, 20, 30, 40]) print("Reversed Array:", arr)
total = sum(arr)
print("Sum of elements:", total) Example 4: Creating Arrays in NumPy:

Example 2: Find the Maximum Element import numpy as np

arr = array('i', [1, 2, 3, 4, 5]) # 1D array


[Link]() arr = [Link]([1, 2, 3, 4, 5])
print("Reversed Array:", arr) print(arr)

# 2D array
matrix = [Link]([[1, 2, 3], [4, 5, 6]])
print(matrix)
Program 2a: Addition of two numbers
C Java Python

#include <stdio.h> class AddNumbers a=10


void main() { public static void main b=10
{ (String args[]) c=a+b
int a,b,sum; { int x, y, z; print ( “Sum is” ,c)
a=10; x=10;
b=10; y=10;
sum=0; z = x + y;
sum=a+b; [Link]("Sum of
printf( “The sum is entered integers = "+z); } }
%d” ,sum);
}
Program 2b: Addition of two numbers
C Java Python
#include <stdio.h> import [Link]; a=input( “Enter First
void main() class AddNumbers { no”)
{ public static void b=input(“Enter second
int a,b,sum; main(String args[]) number”)
sum=0; { int x, y, z; sum=a+b
printf( Enter number a%d”); [Link]("Enter print(“Sum is”,sum)
scanf(“%d” ,&a); two integers to calculate
printf( Enter number b%d”); their sum ");
scanf(“%d” ,&b); Scanner in = new
sum=a+b; Scanner([Link]);
printf( “The sum is %d” x = [Link]();
,sum); y = [Link]();
} z = x + y;
[Link]("Sum of
entered integers = "+z);
}
}
Program 3 : Demonstration of Arithmetic
Operator
a=5
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a%b)
print(a//b)
print(a**b)
Program 4 : Demonstration of Membership
Operators
x = 'Hello world‘
print('H' in x)
print('Hello' not in x)
print(‘hello’ in x)
Exercise 1
1. WAP to display your name and college name
2. Modify first program add your designation with your
name ,but it should be displayed on new line.
3. WAP to calculate area of circle. Define pi=3.14 and
radius 2
4. Modify the program number 2 in such a way that area
will be a rounded number.
5. Modify the program number 4 ,take radius as input from
the user.

You might also like