All-Units-Python-Notes-By-MultiAtomsPlus
All-Units-Python-Notes-By-MultiAtomsPlus
ul
ti
At
om
s
Pl
us
M
ul
ti
At
om
s
Pl
us
M
ul
ti
At
om
s
Pl
us
M
ul
ti
At
om
s
Pl
us
M
ul
ti
At
om
s
Pl
us
us
Pl
s
om
At
ti
ul
M
For loop provides a mechanism to repeat a task until a particular condition is True. It
is usually known as a determinate or definite loop because the programmer knows
exactly how many times the loop will repeat. The for...in statement is a looping
statement used in Python to iterate over a sequence of objects.
For Loop and Range() Function
The range() function is a built-in function in Python that is used to iterate over a
sequence of numbers. The syntax of range() is range(beg, end, [step])
The range() produces a sequence of numbers starting with beg (inclusive) and ending
with one less than the number end. The step argument is option (that is why it is
placed in brackets). By default, every number in the range is incremented by 1 but we
can specify a different increment using step. It can be both negative and positive, but
not zero.
Nested Loops
● Python allows its users to have nested loops, that is, loops that can be placed
inside other loops. Although this feature will work with any loop like while loop
as well as for loop.
A for loop can be used to control the number of times a particular set of
● statements will be executed. Another outer loop could be used to control the
number of times that a whole loop is repeated.
Loops should be properly indented to identify
which statements are contained
● within each for statement.
Break Statement in Python
The break statement in Python is used to terminate the loop or statement in which it is
present.
Continue Statement in Python
Continue is also a loop control statement just like the break statement. continue
statement is opposite to that of the break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop. As the name suggests the continue
statement forces the loop to continue or execute the next iteration.
Pass Statement in Python
As the name suggests pass statement simply does nothing. The pass statement in
Python is used when a statement is required syntactically but you do not want any
command or code to execute. It is like a null operation, as nothing will happen if it is
executed.
Thank You so much for watching
● These data types serve different purposes and have unique characteristics.
Operations:
1. Concatenation: Concatenation involves combining two or more strings into a
single string.
2. Indexing: Indexing allows accessing individual characters within a string using
their positions (indices).
3. Length: The ‘len()’ function returns the length of a string, i.e., the number of
characters it contains.
Multi Atoms Plus
4. Case Conversion: String methods like upper(), lower(), capitalize(), and title() can
change the case of characters in a string.
Lets Code
1. Basic
2. Omitting Start or End
3. Negative Indices
4. Step Parameter
5. Reversing a String
1. Appending Elements
2. Removing Elements
3. Slicing Lists
4. Concatenating Lists
5. Reversing a String
Multi Atoms Plus
2022-23- 2marks
List comprehensions help programmers to create lists in a concise way. This is mainly
beneficial to make new lists where each element is the obtained by applying some
operations to each member of another sequence or iterable. List comprehension is also
used to create a subsequence of those elements that satisfy a certain condition.
Multi Atoms Plus
Tuples in Python
● Tuples are ordered collections of elements in Python.
● They are similar to lists but are immutable, meaning their elements cannot be
changed after creation.
1. Immutable Nature
2. Tuple Unpacking
3. Length and Membership Test
Multi Atoms Plus
Dictionaries in Python - 2022-23
● Dictionaries are unordered collections of key-value pairs in Python.
● They provide a flexible way to store and retrieve data, where each value is
associated with a unique key.
1. Adding Items
2. Removing Items
3. Dictionary Methods - keys() , values() , items().
Lets Code
Python Programming
File: A file is a digital container used to store data on a computer. It has a name, often
with an extension indicating its type (e.g., .txt for text files), and can contain various
types of information such as text, images, or programs. Files are essential for data
allowing information to be saved and retrieved later.
Types of files:
Python can be used to perform operations on a file. (read & write data)
Let’s Code..
Multi Atoms Plus
Writing to files in Python
It is an essential operation for data storage, logging, configuration files, and more. Here
are the basic methods for writing to files, including writing a single string, writing
multiple lines, and appending to a file.
file.write('Hello, World!\n')
file.close()
Multi Atoms Plus
2. Writing Multiple Lines
The writelines() method allows you to write a list of strings to a file. Each string in the
list is written to the file sequentially. This method does not add new lines
automatically, so each string should end with a newline character if needed.
file.writelines(lines)
file.close()
Multi Atoms Plus
3. Appending to a File
To append data to an existing file without truncating it, you can open the file in
append mode ('a'). The new data will be added at the end of the file.
file.close()
By using these methods, you can efficiently write data to files in Python, ensuring
proper file management and data persistence. Always remember to close the file after
writing to ensure that all data is flushed from the buffer and saved to the disk, and to
release system resources.
Let’s Code..
Multi Atoms Plus
`r'' Open text file for reading. The stream is positioned at the beginning of the file.
`r+'' Open for reading + writing. The stream is positioned at the beginning of the file.
`w'' Truncate file to zero length or create text file for writing. The stream →beginning.
`w+'' Open for reading + writing. The file is created if it does not exist, otherwise it is
truncated. The stream → beginning of the file.
`a'' Open for writing. The file is created if it does not exist. The stream is positioned at
the end of the file. Subsequent writes to the file will always end up at the then current
end of file.
`a+'' Open for reading + writing. The file is created if it does not exist. The stream is
positioned at the end of the file.
Let’s Code..
Multi Atoms Plus
Deleting the file in Python
To delete a file in Python, you can use the os.remove() function from the os module.
Here’s how you can delete a file:
import os
file_path = 'example.txt'
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} successfully deleted.")
else:
print(f"{file_path} does not exist.")
Let’s Code..
Multi Atoms Plus
Q. WAPP to write the no. of letters and digits in the given input
String in a file object.
input_string = input("Enter a string: ") # Write counts to a file
letters_count = 0 file_path = 'letter_digit_counts.txt'
digits_count = 0 file = open(file_path, 'w')
file.write(f"Number of letters:
{letters_count}\n")
for char in input_string:
file.write(f"Number of digits: {digits_count}\n")
if char.isalpha():
file.close()
letters_count += 1
elif char.isdigit():
digits_count += 1
Let’s Code..
Multi Atoms Plus
File Handler in Python
File Handler Basics:
Operations:
● Reading: Use methods like read(), readline(), or iterate over lines with a loop.
● Writing: Employ write() to add content to a file, or writelines() to write multiple
lines at once.
● Moving the Pointer: Adjust the file pointer with seek() to navigate through the
file.
● Querying Position: Determine the current position with tell().
Multi Atoms Plus
Modes: as previous
Closing Files:
● Call close() on the file handler to free up resources once operations are done.
Error Handling:
Best Practices:
file_object.seek(offset, whence)
offset: It specifies the number of bytes to move the file pointer.
whence: It specifies the reference point from where the offset is calculated. It can take
one of the following values:
● When you open a file, the file pointer starts at the beginning (0 offset).
● seek(offset, 0) moves the pointer offset bytes from the beginning of the file.
● seek(offset, 1) moves the pointer offset bytes from the current position.
● seek(offset, 2) moves the pointer offset bytes from the end of the file (a negative
offset is usually used in this case).
# Open a file Multi Atoms Plus
file = open('example.txt', 'r')
# Move pointer to the 10th byte from the start
file.seek(10, 0)
print(file.read(5)) # Reads 5 bytes from the current position (10th byte)
# Move 5 bytes forward from the current position
file.seek(5, 1)
print(file.read(10)) # Reads 10 bytes from the current position (15th byte)
# Move to the 10 bytes before the end of the file
file.seek(-10, 2)
print(file.read(5)) # Reads 5 bytes from this position (10 bytes before the end)
# Close the file
file.close()
Multi Atoms Plus
tell() function in Python
The tell() function returns an integer that represents the current position of the file
pointer in bytes from the beginning of the file.’
file_object.tell()
Understanding and utilizing tell() allows precise control over file operations,
especially when dealing with large files or when needing to track and manage
file positions dynamically during file processing in Python.
Let’s Code..
Multi Atoms Plus
Key Concepts:
1. Module: A single file containing Python code (functions, classes, variables, etc.)
with a .py extension.
2. Package: A directory containing multiple modules and an __init__.py file, which
makes it a package. The __init__.py file can be empty or execute initialization code
for the package.
2. module1.py:
3. module2.py:
Numpy: For numerical computations and operations on large arrays and matrices.
Installing Packages
Use pip, the Python package installer, to install packages from the Python Package
Index (PyPI).
Installation
Use color names (e.g., 'blue'), hex codes (e.g., '#FF5733'), or RGB tuples (e.g., (0.1, 0.2,
0.5)).
Markers:
Types include '.' (point), 'o' (circle), 's' (square), '^' (triangle), etc.
Functions for linear algebra operations such as dot products, matrix multiplication,
and eigenvalue decomposition.
Array Manipulation:
Series: A one-dimensional labeled array that can hold any data type.
DataFrame: A two-dimensional labeled data structure with columns of potentially different data
types.
Multi Atoms Plus
Creating Data Structures
# Creating a Series
s = pd.Series([1, 2, 3, 4, 5], name='numbers')
print(s)
# Creating a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3],
'B': ['a', 'b', 'c'],
'C': [4.5, 5.5, 6.5]
})
print(df) Multi Atoms Plus
Data Manipulation:
Indexing and Selection: Accessing and manipulating data using labels and
integer-based indexing.
1. Indexing and Selection using Labels (loc): Accessing data using labels.
Handling Missing Data: Functions for detecting, filling, and dropping missing values.
Reading/Writing Data: Functions for reading from and writing to various file formats including CSV, Excel
1. Reading CSV Files: Using pd.read_csv() to read data from a CSV file.
2. Reading Excel Files: Using pd.read_excel() to read data from an Excel file.
Python offers several libraries to create GUIs, with Tkinter being the most commonly
used due to its simplicity and integration with Python's standard library. Other popular
GUI frameworks include PyQt, Kivy, and wxPython.
1. Button: A Button widget is used to display a clickable button that can trigger a
function or event when clicked.
● tk.Label(root, text="This is a label"): Creates a label with the text "This is a label".
● label.pack(): Adds the label to the window.
entry2 = tk.Entry(root)
entry2.pack()
result = tk.DoubleVar()
result_label = tk.Label(root, textvariable=result)
result_label.pack()
Multi Atoms Plus
1. Import Tkinter Module:
2. Define Functions:
This function retrieves the values from entry1 and entry2, adds
them, and sets the result in the result variable.
This creates the main window of the application and sets its title to "Simple Calculator".
Creates the second entry widget for user input and adds it to the window.
This creates a label that displays the result of the calculation. The label's text is bound to the result variable.
This starts the Tkinter event loop, which waits for user interactions and updates the GUI accordingly.
1. PyCharm: Developed by JetBrains, PyCharm is a powerful and widely-used IDE for Python. It
comes in two versions: Community (free) and Professional (paid).
● Intelligent Code Editor: Code completion, real-time error checking, and quick fixes.
● Debugging and Testing: Integrated debugger and test runner.
● Version Control: Supports Git, SVN and more.
● Web Development: Supports Django, Flask, and other web frameworks.
3. Spyder: An open-source IDE specifically designed for scientific computing and data analysis,
often used with Anaconda distribution.
3. Spyder: An open-source IDE specifically designed for scientific computing and data analysis,
often used with Anaconda distribution.