0% found this document useful (0 votes)
3 views17 pages

Python Module 3 (2025) ..

This document provides an overview of Python programming concepts, focusing on dictionaries, NumPy, file handling, and directories. It explains how dictionaries work as mapping types, introduces key NumPy features like array shapes and broadcasting, and details file operations including reading and writing files. Additionally, it covers file system organization and best practices for handling file paths across different operating systems.

Uploaded by

Naveen Naveen
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)
3 views17 pages

Python Module 3 (2025) ..

This document provides an overview of Python programming concepts, focusing on dictionaries, NumPy, file handling, and directories. It explains how dictionaries work as mapping types, introduces key NumPy features like array shapes and broadcasting, and details file operations including reading and writing files. Additionally, it covers file system organization and best practices for handling file paths across different operating systems.

Uploaded by

Naveen Naveen
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

Module 3 Python programming 1BPLC105B

Dictionaries:

• Dictionaries All of the compound data types we have studied in detail so far —
strings, lists, and tuples — are sequence types, which use integers as indices to access
the values they contain within them
.
• Dictionaries are yet another kind of compound type. They are Python’s built-in
mapping type. They map keys, which can be any immutable type, to values, which can
be any type (heterogeneous), just like the elements of a list or tuple. In other
languages, they are called associative arrays since they associate a key with a value.

• As an example, we will create a dictionary to translate English words into Spanish.


For this dictionary, the keys are strings.

• One way to create a dictionary is to start with the empty dictionary and add key: value
pairs. The empty dictionary is denoted {}:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B

Dictionary operations

Dictionary methods
• Dictionaries have a number of useful built-in methods. The keys method returns what
Python 3 calls a view of its underlying keys.
• A view object has some similarities to the range object we saw earlier — it is a lazy
promise, to deliver its elements when they’re needed by the rest of the program.
• We can iterate over the view, or turn the view into a list like this:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B

Aliasing and copying


• As in the case of lists, because dictionaries are mutable, we need to be aware of
aliasing. Whenever two variables refer to the same object, changes to one affect the
other.
• If we want to modify a dictionary and keep a copy of the original, use the copy
method.
• For example, opposites is a dictionary that contains pairs of opposites:

Numpy:

• As we can see, this worked the way we expected it to. We note a couple of things: -

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
We abbreviated numpy to np, this is conventional. - [Link]
• list as argument. - The list [2, 3, 8] contains int’s, yet the result contains float’s. This
means numpy changed the data type automatically for us. Now let’s take it a step
further and see what happens when we multiply together array’s.

Shape:
• One of the most important properties an array is its shape.
• We have already seen 1 dimensional (1D) arrays, but arrays can have any dimensions
you like. Images for example, consist of a 2D array of pixels.
• But in color images every pixel is an RGB tuple: the intensity in red, green and blue.
Every pixel itself is therefore an array as well.
• This makes a color image 3D overall. To get the shape of an array, we use shape:

Slicing:
Just like with lists, we might want to select certain values from an array. For 1D arrays it
works just like for normal python lists:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B

Masking :
This is perhaps the single most powerful feature of Numpy. Suppose we have an array, and
we want to throw away all values above a certain cutoff:

Broadcasting:
Another powerful feature of Numpy is broadcasting. Broadcasting takes place when you
perform operations between arrays of different shapes

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• The shapes of a and b don’t match. In order to proceed, Numpy will stretch b into a

second dimension, as if it were stacked three times upon itself.

• The operation then takes place element-wise. One of the rules of broadcasting is that

only dimensions of size 1 can be stretched (if an array only has one dimension, all

other dimensions are considered for broadcasting purposes to have size 1).

• In the example above b is 1D, and has shape (2,). For broadcasting with a, which has

two dimensions, Numpy adds another dimension of size 1 to b. b now has shape (1, 2).

• This new dimension can now be stretched three times so that b’s shape matches a’s

shape of (3, 2). The other rule is that dimensions are compared from the last to the

first.

• Any dimensions that do not match must be stretched to become equally sized.

However, according to the previous rule, only dimensions of size 1 can stretch.

• This means that some shapes cannot broadcast and Numpy will give you an

error:

What happens here is that Numpy, again, adds a dimension to b, making it of shape (1, 2). The

sizes of the last dimensions of b and c (2 and 3, respectively) are then compared and found to

differ. Since none of these dimensions is of size 1 (therefore, unstretchable) Numpy gives up

and produces an error.

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
The solution to multiplying c and b above is to specifically tell Numpy that it must add that

extra dimension as the second dimension of b. This is done by using None to index that second

dimension. The shape of b then becomes (2, 1), which is compatible for broadcasting with c:

dtype:

• type means data type in NumPy (e.g., int8, float64).

• int8 means an integer stored in 8 bits.

• With 8 bits → 256 possible values (2^8 = 256).

• uint8 (unsigned integer):

• Only positive numbers

• Range: 0 to 255

• int8 (signed integer):

• Allows negative numbers

• Range: –128 to +127

• Larger dtypes (like int64) allow much bigger ranges.

• Example: int64 range is –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

• Bigger dtype ≠ always better:

• Larger types use more memory.

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• If your values are always small (e.g., <100), using bigger types wastes memory.

• Use default dtype unless you face memory issues, then choose a smaller dtype like

uint8.

• uint8 stores integers in 8 bits → only values 0..255.


• Adding 200 + 200 in a uint8 cannot produce 400 because 400 > 255.
• NumPy does not automatically promote the result to a larger integer type; it stays in
uint8.
• When the sum exceeds the uint8 range it wraps around (modulo 256), so 200 + 200
becomes 400 % 256 = 144.
• Standard Python integers are arbitrary-precision, so plain Python would give 400 —
NumPy behaves differently for fixed-size dtypes.
• Fixes / best practices:

• Store or cast to a larger dtype before the operation (e.g. uint16, int32, int64) so the
result fits.

Example:

• import numpy as np
• a = [Link]([200], dtype=np.uint8)
• b = [Link]([200], dtype=np.uint8)
• (a + b).dtype # uint8 -> value wraps to 144
• a16 = [Link](np.uint16)
• b16 = [Link](np.uint16)
• (a16 + b16) # dtype uint16 -> value 400
• Alternatively, create arrays with a larger dtype from the start if you expect large
results.

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• Takeaway: watch dtype sizes in NumPy — if results may exceed the type range,
promote to a bigger dtype to avoid silent overflow.

Files:
• RAM (Random Access Memory)
• RAM stores data while a program is running.
• It is fast and inexpensive.
• It is volatile, meaning the data disappears when:
o the program ends, o the computer turns off or restarts.

• Non-volatile storage
• To keep data even after shutdown, it must be saved to a non-volatile medium.
• Examples:
o Hard drive o USB drive o CD-RW

• Data stored here remains available the next time the program runs.
• Files
• Data in non-volatile storage is kept in files, which are named locations on storage
devices.

• Programs can read and write files to save information permanently.


• Working with files is like using a notebook
• A notebook must be opened before use.
• It must be closed after you finish.
• While open, you can:
o read from it, o write to it.

• You can read it in order or jump to different parts, similar to random access in files.

Writing our first file:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• Opening a file creates a “file handle” o When you open a file in Python, you get a

file handle. o A file handle is an object that allows your program to interact with the

file.

o It acts like a connection between your program and


the file stored on disk.
• The variable (e.g., myfile) refers to the handle o When you write:

o myfile = open("[Link]", "w") o myfile stores the

file handle.

o You use this handle to perform actions like write(),


read(), or close().

• Methods on the handle change the actual file o When you call:

o [Link]("Hello") o The content is written to

the actual file on your hard drive or USB drive.

• The open() function o Takes two arguments:

1. filename — the name/location of the file.


2. mode — what you want to do with the file.
• Mode "w"
o "w" stands for write mode.
o It means:
▪ You are opening the file to write data.
▪ If the file already exists → it will be overwritten (old content erased).
▪ If it doesn't exist → Python will create a new file.
If you want, I can also explain "r", "a", "w+", or show a simple program using file handles!
With mode "w", if there is no file named [Link] on the disk, it will be created. If there already
is one, it will be replaced by the file we are writing

Reading a file line-at-a-time:


• Useful programming pattern
• The example shows a common and very useful pattern:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
o Open a file o Loop through each line o Process each

line

• In larger programs, the logic inside the loop usually becomes more complex.
• Using file lines in bigger programs

• For example:
o If each line contains a friend’s name and email, o You

could split the line into parts, o Then call another

function (e.g., to send an invitation).

• This shows how file-reading loops integrate with real-world tasks.


• Why end="" is used in print()
• Normally, print() adds a newline (\n) after every output.
• But when reading a file using:
• for line in myfile:
• each line already contains its own newline at the end.
• So if you use print(line) without end="", you get double spacing:
o One newline from the file, o One newline

automatically added by print(). • Solution

• Using:
• print(line, end="")
• stops print from adding an extra newline.
• This ensures the output looks exactly like the file content.

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B

Turning a file into a list of lines:


• It is often useful to fetch data from a disk file and turn it into a list of lines. Suppose
we have a file containing our friends and their email addresses, one per line in the file.

• But we’d like the lines sorted into alphabetical order. A good plan is to read everything
into a list of lines, then sort the list, and then write the sorted list back to another file:

We could have used the template from the previous section to read each line one-at-a-time, and
to build up the list ourselves, but it is a lot easier to use the method that the Python implementors
gave us

Reading the whole file at once:


• Another way of working with text files is to read the complete contents of the file into
a string, and then to use our string-processing skills to work with the contents.

• We’d normally use this method of processing files if we were not interested in the line
structure of the file. For example, we’ve seen the split method on strings which can
break a string into words. So here is how we might count the number of words in a
file:

Directories:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
[Link] system

• Files on storage devices are organized using rules called a file system.
• A file system contains:
o Files o Directories (folders) — which can

contain both files and other directories.

2. Current directory
• When you create a file using open() in write mode, it is created in the current
directory (where the Python program is running).
• When you open a file for reading, Python also looks for it in the current directory by
default.

3. Opening files outside the current directory


• To open a file in another folder, you must give the path of the file.
• Example (Unix/Linux):
• wordsfile = open("/usr/share/dict/words", "r") o This path means:

▪ words file
▪ inside dict
▪ inside share
▪ inside usr
▪ inside the root directory /.

4. Reading lines
• readlines() reads all lines from the file into a list.
• You can then inspect part of the list, such as:
• print(wordlist[:6])

5. Windows paths
• A Windows-style path:

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
o "c:/temp/[Link]" (forward slashes

work) o "c:\\temp\\[Link]" (backslashes

must be written twice)

• Backslashes need escaping because \n, \t, etc., are special characters in strings.

6. / and \ cannot be used in filenames


• These characters are reserved for separating folders and filenames.
• Example:
o Correct: folder/[Link] o Incorrect:

file/[Link] (invalid filename)

7. Use [Link] to handle paths safely


• Python's [Link]() automatically handles slashes for different operating systems.
• import os
• path = [Link]("directory", "filename")
• Output:

o On Linux → "directory/filename" o On

Windows → "directory\\filename"

8. Why use [Link]?

• Avoids errors from wrong slashes.


• Makes code portable between Windows, Linux, macOS.
• Prevents string escaping issues.
• Easier and safer than manually typing paths.

Fetching something from the web:


1. The web uses URLs

• To get content from the internet, you request a


URL (like [Link]

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• The URL points to a resource stored on a remote web server.
2. Your program sends an HTTP request

• Python sends a message called an HTTP request to the server.


• Common types:
oGET → fetch data o POST → send data

3. The server responds

• The server receives your request and returns a response.


• This response typically contains:
oStatus code (200 = success, 404 = not

found) o Content/body (text,

HTML, JSON, image, etc.) 4. Python can

fetch web content using modules

Two common modules:


a) urllib (built-in) import
[Link]

response = [Link]("[Link]
data = [Link]() print(data)
b) requests (external library but
very easy) import requests

response = [Link]("[Link]
print([Link])
5. Data formats you often fetch
• HTML pages
• JSON data (very common for APIs)
• Text files
• Images and other media
6. Why fetch data from the web?

Dept of CSE AIET Devanahalli


Module 3 Python programming 1BPLC105B
• To download files
• To interact with APIs (weather data, stock prices, maps, etc.)
• To automate tasks
• To scrape websites
• To update information in your app 7. Saving fetched data to a file
Example:
import requests

url = "[Link]
response = [Link](url)

with open("[Link]", "w") as f:


[Link]([Link])

Dept of CSE AIET Devanahalli

You might also like