Python Advance
Python Advance
like
test_bar = “hello”
cannot use - , “ “
cannot do a = “hello” + 5
also we can’t do a string a[2] = ‘w’ it show error also change the entire variable
A data type in Python means the kind of value a variable can hold.
It tells Python what type of data is stored, so it knows how to handle it.
Number - int,float,comples
text - string
boolean - bool
sequences - list.tuple,range
set - set,frozenset
mapping - dict
print(type(12)) #int
print(type(2.5)) # float
print(type(2j+12)) #complex
# #Boolean
# print(type(True)) #Bool
✅ Key Points:
● Enclosed in single (') or double (") quotes.
● Strings are immutable, which means once created, they cannot be changed
directly.
● You can access characters using indexing (0 is the first character) and slicing.
3. Can hold any data type – Numbers, strings, other lists, or a mix of types.
A tuple in Python is very similar to a list, but with one key difference: it is immutable, which
means once created, you cannot change its elements.
3. Can hold any data type – Numbers, strings, lists, or even other tuples.
4. Cannot contain mutable items – Lists or dictionaries cannot be elements of a set.
print(set1 & set2) // Difference A-B that means a inside but not inside the b
It is used to store data in a way that each value can be quickly accessed using a
unique key.
3. Values can be any data type – Numbers, strings, lists, tuples, other dictionaries.
⌨️ User Input with input() Next, it demonstrates how to take input from the user using
the input() function. This allows users to enter data during program execution, which can
then be stored in variables.
🔄 Displaying User Input The tutorial shows how to take the input received and print it
back out, reinforcing the connection between input and output in Python.
Operators
Of course. Here is a detailed summary of the video "#11 Python Tutorial for Beginners |
Operators in Python."
Summary
This video explains the different types of operators in Python, which are special symbols
used to perform operations on variables and values. The tutorial categorizes them into
arithmetic, assignment, unary, relational, and logical operators.
Arithmetic Operators
Unary Operator
● - (Negation): This is used to change the sign of a number. For example, if a variable
n holds the value 7, then -n will be -7.
Relational Operators
These operators compare two values and return a Boolean value: True or False.
● < (Less than): Checks if the first value is less than the second.
● > (Greater than): Checks if the first value is greater than the second.
● == (Equal to): Checks if two values are equal. It uses a double equals sign to
distinguish it from the assignment operator.
● <= (Less than or equal to): Checks if the first value is less than or equal to the
second.
● >= (Greater than or equal to): Checks if the first value is greater than or equal to the
second.
● != (Not equal to): Checks if two values are not equal.
Logical Operators
These operators are used to combine or modify conditional statements and Boolean values.
Sure, here is a detailed summary of the video "Control Flow in Python - If Elif Else
Statements."
Summary
This video explains how to control the flow of a Python program using conditional
statements. It covers the fundamental if, elif, and else statements, which allow the
program to make decisions and execute different blocks of code based on specific
👨💻
conditions. The tutorial also explores how to build more complex conditions using logical
operators and how to write cleaner code with the ternary operator.
if Statements
The if statement is the most basic control flow structure. It executes a block of code only if
a specified condition is True.
● Structure: It starts with the if keyword, followed by the condition and a colon (:).
● Indentation: The code to be executed under the if statement must be indented
(typically with four spaces). This indentation is crucial as it tells Python which lines of
code belong to the if block. If the condition is False, the indented block is skipped.
elif Statements
elif, short for "else if," is used to check for additional conditions if the preceding if (or
elif) statement was False.
● Purpose: It allows you to create a chain of checks. The program will test each elif
condition in order until it finds one that is True.
● Execution: Once a true condition is found, its corresponding code block is executed,
and the rest of the elif and else blocks are skipped. You can have as many elif
statements as you need.
else Statements
The else statement acts as a catch-all. It provides a block of code to be executed if none
of the preceding if or elif conditions are met.
This is a concise, one-line way to write a simple if-else statement. It's often used to
assign a value to a variable based on a condition.
To create more powerful and complex conditions, you can use logical and comparison
operators.
● Logical Operators:
○ and: Returns True only if both conditions are true.
○ or: Returns True if at least one condition is true.
○ not: Inverts the result of a condition (e.g., not True becomes False).
● Chaining Comparison Operators: Python allows you to chain comparison
operators for cleaner code. For example, instead of writing age >= 18 and age <
65, you can write 18 <= age < 65, which is more natural to read.
● Short-Circuiting: Python's logical operators are efficient. For an and expression, if
the first part is false, Python doesn't bother checking the second part. For an or
expression, if the first part is true, it doesn't check the second. This is known as
short-circuit evaluation.
2. Lexicographical Comparison
● You can use <, >, <=, >= to compare strings alphabetically (like dictionary order)
a = "apple"
b = "banana"
Here is a detailed summary of the video "Python For Loops - Python Tutorial for Absolute
Beginners."
Summary
This tutorial explains for loops in Python, a fundamental concept for repeating a block of
code multiple times. It covers how to create loops, customize their behavior with the
range() function, control their execution with break, and use them with different types of
🔄
iterable objects like strings and lists.
A for loop is used to iterate over a sequence (like a list, a string, or a range of numbers)
and execute a block of code for each item in that sequence. This avoids writing the same
code over and over again.
Customizing range()
You can control the flow of a loop from within its code block.
● break Statement: The break statement immediately terminates the loop. The
program then continues with the code that comes after the loop. This is useful for
stopping the loop when a certain condition is met.
● for-else Statement: A for loop can have an optional else block. The code in the
else block will run only if the loop completes all its iterations without being
terminated by a break statement. This is useful for running a piece of code after a
successful loop completion.
Nested Loops
You can place one loop inside another. This is called a nested loop.
● Execution: For each single iteration of the outer loop, the inner loop will run through
all of its iterations.
● Example: A common use is to generate coordinates or work with 2D grids. for x
in range(3): for y in range(2): will produce pairs like (0,0), (0,1), then
(1,0), (1,1), and finally (2,0), (2,1).
Iterables
An iterable is any object in Python that you can loop over. for loops are designed to work
with iterables.
when set to this it convert that to optional parameter when we don’t pass second parameter
it default using the 1 when we pass anything it uses that
📦
use different types of parameters and arguments, understand variable scope, and concludes
with a practical coding exercise.
A function is defined using the def keyword, followed by a function name, parentheses (),
and a colon :. The code that belongs to the function must be indented.
Types of Functions
1. Functions that perform a task: These functions do something, like printing a
message to the screen.
2. Functions that return a value: These functions perform a calculation or process
and then send a result back using the return keyword. This returned value can be
stored in a variable or used in other parts of your code, making them more flexible.
○ If a function doesn't have an explicit return statement, it automatically
returns None, which represents the absence of a value.
● Keyword Arguments: To make your code more readable, you can specify which
parameter you are providing an argument for. This is especially useful when a
function has many parameters. Example: increment(number=2, by=1).
● Default Arguments (Optional Parameters): You can make a parameter optional by
giving it a default value in the function definition. Example: def
increment(number, by=1):. If you don't provide the by argument when calling
the function, it will automatically use 1. Important: Optional parameters must always
come after required parameters.
● Arbitrary Arguments (*args): If you want a function to accept a variable number of
arguments, you can use * before a parameter name (e.g., *numbers). Python will
bundle these arguments into a tuple (an immutable list).
● Arbitrary Keyword Arguments (**kwargs): To accept a variable number of
keyword arguments, use ** before a parameter name (e.g., **user). Python will
bundle these into a dictionary (a collection of key-value pairs).
Scope of Variables
Scope determines where a variable can be accessed.
● Local Variables: Variables created inside a function (including its parameters) are
local. They only exist within that function and are destroyed once the function
finishes executing.
● Global Variables: Variables created outside of any function are global. They can be
accessed from anywhere in the file.
○ Note: Modifying global variables from inside a function is considered bad
practice as it can make your code hard to debug.
FizzBuzz Exercise
The video concludes with a classic programming exercise called FizzBuzz. The goal is to
create a function that takes a number and returns:
This exercise reinforces the use of conditional logic (if/elif/else) within a function
Exception Handling
🚨 Exception Handling in Simple Language
● Exception = Error that happens while the program is running.
his tutorial explains exception handling in Python, a crucial mechanism for managing errors
that occur while a program is running. It differentiates between compile-time, logical, and
runtime errors, and then focuses on how to use try, except, and finally blocks to
handle runtime errors (exceptions) gracefully without crashing the application. 🚧
Types of Errors
The video first categorizes the different kinds of errors you might encounter in programming:
● Compile-time Errors: These are syntax errors that violate the rules of the Python
language, like forgetting a colon (:) or misspelling a keyword. The program won't run
at all until these are fixed.
● Logical Errors: The code runs without crashing, but it produces an incorrect or
unexpected result. This is a flaw in the program's logic, like using addition (+) instead
of subtraction (-). These are often the hardest to find.
● Runtime Errors (Exceptions): These errors occur during the execution of the
program. The syntax is correct, but an issue arises that the program can't handle,
such as trying to divide a number by zero or attempting to open a file that doesn't
exist. Exception handling is designed to manage these runtime errors.
The core of exception handling is the try-except block. It allows you to run code that
might cause an error and define a fallback plan if it does.
● try Block: You place the code that might cause an exception inside the try block.
Python will attempt to execute this code.
● except Block: If an error occurs in the try block, the program immediately jumps
to the except block. This block contains the code that will handle the error, such as
printing a user-friendly message. This prevents the program from crashing.
Python
try:
a=5
b=0
print(a / b) # This line will cause an error
except Exception as e:
print("Sorry, something went wrong:", e)
While you can catch a general Exception, it's better practice to handle specific types of
errors. This allows you to respond differently to different problems.
● Multiple except Blocks: You can have multiple except blocks to handle different
exceptions like ValueError (e.g., trying to convert text to a number) or
ZeroDivisionError.
● Order Matters: If you are handling both specific and general exceptions, the general
except Exception block should always be the last one, as it will catch any error
that wasn't caught by the more specific blocks above it.
Python
try:
# Code that might cause an error
pass
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input. Please enter a number.")
except Exception as e:
print("An unknown error occurred:", e)
The finally block is an optional part of the structure that contains code that will always
execute, no matter what.
● Execution: The code in the finally block runs whether an exception occurred or
not. It even runs if the try or except blocks have a return statement.
● Purpose: It is commonly used for cleanup actions, such as closing a file or
disconnecting from a database, ensuring that these essential tasks are completed
regardless of errors.
list -
A list in Python is a built-in data type that stores an ordered, changeable collection of
items, and it can hold mixed data types like numbers, strings, and even other lists.
Use square brackets to create a list, for example: [1, "a", True]
to add a
element to an specific index
to remove the last item in the list
Quick tip:
● Use set() for an empty set, because {} makes an empty dictionary.
dict
A dictionary in Python is a collection that stores data as key-value pairs, like a
real-world dictionary maps a word (key) to its meaning (value). Keys must be unique
and immutable (e.g., strings, numbers, tuples), while values can be any type and can
repeat.
Core idea
● Think of it as a labeled box: the label is the key, and inside is the value. Access
is fast using the key, not positions.
● Example: student = {"name": "Asha", "age": 20, "marks": 92}
Key properties
● Ordered by insertion (Python 3.7+), changeable, and keys are unique.
● Keys are immutable; values can be any type (even lists or other dicts).
Common operations
● Create: person = {"name": "Ravi", "city": "Pune"}
● Read: person["city"] -> "Pune"
● Add/Update: person["age"] = 30
● Remove: person.pop("city")
● Safe get: person.get("email", "not set") # avoids error if missing
● Keys/values: person.keys(), person.values(), person.items()
Handy patterns
● Build from pairs: dict([("a", 1), ("b", 2)])
● Dict comprehension: squares = {n: n*n for n in range(5)}
● Nested dicts: users = {"u1": {"name": "Asha", "active": True}}
If starting out, remember: use {} for dictionaries; use [] for lists. Keys label data, so
choose clear, descriptive key names.
Method Description
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
Tuples
Method Description
index() Searches the tuple for a specified value and returns the
position of where it was found
Set
intersection_update() & Removes the items in this set that are not present
= in other, specified set(s)
Dictinary
Method Description
items() Returns a list containing a tuple for each key value pair
setdefa Returns the value of the specified key. If the key does not exist: insert
ult() the key, with the specified value
A data structure is a way to store and organize data so it can be used efficiently.
Think of it like different containers that hold data in different ways depending on
what you want to do with it.
So, it’s how Python communicates with external storage (like .txt, .csv, .json,
.bin files).
When you add +, it means → both read and write are allowed.
1. r+ (read + write)
● Writing does not erase file (but overwrites content starting from cursor).
2. w+ (write + read)
3. a+ (append + read)
● Cursor starts at the end for writing, but you can move it with seek() to read.
👉 Use case: Add new logs/data while still being able to read the whole file
👉 Think of it like a toolbox: instead of rewriting the same tools, you just import the
toolbox and use them.
🔹 Types of Modules
1. Built-in modules → come with Python by default.
3. You can now call math.sqrt(16) instead of writing your own square root
logic.
👉 Example:
● random.py → a module
● numpy/ (folder with many .py files) → a package
%Y → Year (2025)
%m → Month (09)
%H → Hour (24-hour)
%I → Hour (12-hour)
%p → AM / PM
%M → Minute
%S → Second
print(type(now.strftime("%d:%b:%Y %a %I:%M")))
import os
print(os.getcwd()) # current directory