0% found this document useful (0 votes)
23 views37 pages

Python Advance

Uploaded by

Adith
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)
23 views37 pages

Python Advance

Uploaded by

Adith
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

Variables in Python | Python for Beginners

A variable in Python is simply a name that stores a value in memory.


Think of it like a container or a label that points to some data.

also identifier , it is case sensitive

follow this practise

like

test_bar = “hello”

cannot use - , “ “

cannot do a = “hello” + 5

when we do this a = “hello”


print(a[10]) // it give error because this index not found

but print(a[0:100]) it not give an error

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

A string in Python is a sequence of characters.

It is used to store text, like words, sentences, or even symbols.

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

A list in Python is a collection of items stored in a single variable.

🔹 Key Points about Lists:


1.​ Ordered – Items have a specific order, and you can access them using an index
(starting at 0).​

2.​ Changeable (Mutable) – You can add, remove, or modify items.​

3.​ Can hold any data type – Numbers, strings, other lists, or a mix of types.​

4.​ Allows duplicates – Same value can appear multiple times.

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.

🔹 Key Points about Tuples:


1.​ Ordered – Elements have a specific order and can be accessed by index.​
2.​ Immutable – You cannot add, remove, or change items after creation.​

3.​ Can hold any data type – Numbers, strings, lists, or even other tuples.​

4.​ Allows duplicates – Same value can appear multiple times.

A set in Python is an unordered collection of unique elements.

🔹 Key Points about Sets:


1.​ Unordered – Items do not have a specific order.​

2.​ Mutable – You can add or remove elements.​

3.​ No duplicates – Each element appears only once.​

4.​ Cannot contain mutable items – Lists or dictionaries cannot be elements of a set.

when create set1 and set2

print(set1 | set2) // it print all values in this set interception

print(set1 & set2) // which have in two of them common

print(set1 & set2) // Difference A-B that means a inside but not inside the b

A dictionary in Python is an unordered collection of key-value pairs.

It is used to store data in a way that each value can be quickly accessed using a
unique key.

🔹 Key Points about Dictionaries:


1.​ Key-value pairs – Every item has a key and a value: {key: value}.​

2.​ Keys are unique – You cannot have duplicate keys.​

3.​ Values can be any data type – Numbers, strings, lists, tuples, other dictionaries.​

4.​ Mutable – You can add, update, or remove items.


🖨️ Print Function Basics The video kicks off by introducing the print() function in
Python, which is used to display output to the console. It explains how to use it with strings
and variables to show messages or results.

⌨️ 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.

🎨 Output Formatting Finally, it touches on formatting output—how to combine strings and


variables in a clean, readable way using commas or string concatenation.

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

These operators are used to perform common mathematical calculations.

●​ + (Addition): Adds two operands.


●​ - (Subtraction): Subtracts the second operand from the first.
●​ * (Multiplication): Multiplies two operands.
●​ / (Division): Divides the first operand by the second.
●​ The video also briefly mentions the modulus operator (%), which returns the
remainder of a division.
Assignment Operators

These are used to assign values to variables.

●​ = (Assignment): The basic operator to assign a value (e.g., x = 8).


●​ Shorthand Operators: These combine an arithmetic operation with assignment for
brevity. For example, x = x + 2 can be written as x += 2. This shorthand works
for other operators as well, such as *= for multiplication.
●​ Multiple Assignment: Python allows you to assign values to multiple variables on a
single line (e.g., a, b = 5, 6).

Unary Operator

A unary operator works on a single operand.

●​ - (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.

A logical operator in Python is used to combine or modify boolean values (True or


False) to make decisions.
●​ and: Returns True only if both conditions it connects are true.
●​ or: Returns True if at least one of the conditions it connects is true.
●​ not: Reverses the result of a condition. It turns True into False and False into
True.

A ternary operator in Python is a one-line shorthand for an if-else statement.


It lets you choose between two values based on a condition in a single line

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.

●​ Functionality: It ensures that one block of code in the if-elif-else chain is


always executed.
●​ Syntax: It is written as else: and does not require a condition.

Ternary Operator (Conditional Expressions)

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.

●​ Syntax: variable = value_if_true if condition else


value_if_false
●​ Benefit: It makes your code cleaner and more readable for simple conditional
assignments.

Logical and Comparison Operators

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"

print(a < b) # True (because 'a' comes before 'b')


print(a > b) # False

●​ Comparison is done character by character using ASCII/Unicode values.​

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.

Basic for Loops

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.

●​ Structure: The basic syntax is for item in sequence:. The code to be


repeated must be indented.
●​ The range() Function: This is the most common way to define how many times a
loop should run.
○​ range(3) will run the loop three times, with an item variable taking the
values 0, 1, and 2 in each iteration.

Customizing range()

The range() function can be customized with additional arguments:


●​ Start and End: range(start, end) creates a sequence of numbers starting from
start and going up to, but not including, end. For example, range(1, 4)
produces the numbers 1, 2, and 3.
●​ Step: range(start, end, step) adds an increment value. range(1, 10, 2)
will produce every second number: 1, 3, 5, 7, and 9.

Controlling the Loop

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.

●​ range objects: The range() function produces an iterable object.


●​ Strings: Strings are iterable. A for loop can iterate through each character of a
string.
●​ Lists: Lists are also iterable. A for loop will iterate through each item in the list.
What is a Function in Python?
A function is a block of code that performs a specific task.

●​ You write it once, and you can reuse it many times.​

●​ Functions make programs modular, organized, and easier to read.

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

*args - for to get multiple arguments as tuple


*kwargs - it used to get multiple key value pair to pass

scope global keyword


ummary

This tutorial provides a thorough introduction to functions in Python. It explains that


functions are reusable blocks of code that perform a specific task, helping to make programs
smaller, more organized, and easier to maintain. The video covers how to define functions,

📦
use different types of parameters and arguments, understand variable scope, and concludes
with a practical coding exercise.

Defining and Calling Functions

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.

●​ Definition: def greet():


●​ Calling: To execute the function, you "call" it by its name followed by parentheses:
greet()

Parameters and Arguments

Functions become more powerful when they can accept inputs.


●​ Parameters: These are the variables listed inside the parentheses in the function
definition. They act as placeholders for the data the function needs. Example: def
greet(first_name, last_name):
●​ Arguments: These are the actual values you provide to the function when you call it.
Example: greet("John", "Smith"). The value "John" is the argument for the
first_name parameter.

Types of Functions

Functions can be categorized into two main types:

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.

Function Arguments In-Depth

Python offers flexible ways to handle function arguments.

●​ 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:

●​ "FizzBuzz" if the number is divisible by both 3 and 5.


●​ "Fizz" if the number is divisible by 3.
●​ "Buzz" if the number is divisible by 5.
●​ The number itself otherwise.

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

●​ If we don’t handle it → program stops (crashes).​

●​ If we handle it → program keeps running safely.​

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 try-except Block

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)

Handling Specific Exceptions

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

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 check an element in list


to append a element to list last
index

to add a
element to an specific index
to remove the last item in the list

to remove a specific element from the list


to clear all the elements in the list

to reverse the list using reverse method

to sort using sort it change th original list

to sort list sorted(list) it return new list


slicing - slicing is the way to access subpart our list using column
Tuples

A tuple in Python is an ordered, immutable collection used to store multiple items in


a single variable, typically written with parentheses like (1, "a", True). Because tuples
can’t be changed after creation, they’re useful for fixed data, function returns, and as
dictionary keys when all elements are immutable
to use an element how much time in the tuple
set

Here’s a simple explanation of a Python set:


●​ A set is a bag of unique items — it automatically removes duplicates.programiz+1
●​ The items are not in any fixed order, so there’s no indexing like s.realpython+1
●​ It’s good for quick checks like “is this item present?” and for math-like
operations (union, intersection).python+1
Simple examples:
●​ Creating: s = {1, 2, 3} or s = set() -> {1, 2, 3}.geeksforgeeks+4
●​ Add/remove: s.add(4), s.discard(2).programiz+1
●​ Operations:
●​ {1, 2} | {2, 3} -> {1, 2, 3} (union) realpython
●​ {1, 2, 3} & {2, 3} -> {2, 3} (intersection)realpython
●​ {1, 2, 3} - {2} -> {1, 3} (difference)realpython

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

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

Tuples

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
Set

add() Adds an element to the set

clear() Removes all the elements from the set

copy() Returns a copy of the set

difference() - Returns a set containing the difference between


two or more sets

difference_update() - Removes the items in this set that are also


= included in another, specified set

discard() Remove the specified item

intersection() & Returns a set, that is the intersection of two other


sets

intersection_update() & Removes the items in this set that are not present
= in other, specified set(s)

isdisjoint() Returns whether two sets have a intersection or


not
issubset() < Returns True if all items of this set is present in
= another set

< Returns True if all items of this set is present in


another, larger set

issuperset() > Returns True if all items of another set is present in


= this set

> Returns True if all items of another, smaller set is


present in this set

pop() Removes an element from the set

remove() Removes the specified element

symmetric_difference() ^ Returns a set with the symmetric differences of two


sets

symmetric_difference_ ^ Inserts the symmetric differences from this set and


update() = another

union() | Return a set containing the union of sets


update() | Update the set with the union of this set and others
=

Dictinary

Method Description

clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkey Returns a dictionary with the specified keys and value


s()

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key


popitem Removes the last inserted 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

update( Updates the dictionary with the specified key-value pairs


)

values() Returns a list of all the values in the dictionary

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.

python file handling

🔹 What is File Input/Output (I/O)?


File I/O means interacting with files in your computer using Python.

●​ Input → Reading data from a file into your program.​

●​ Output → Writing data to a file from your program.​

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)

●​ File must already exist.​

●​ Reads and writes are allowed.​

●​ Writing does not erase file (but overwrites content starting from cursor).​

●​ Cursor starts at the beginning.​

👉 Use case: Updating content in an existing file.

2. w+ (write + read)

●​ Creates a new file if not exists.​

●​ If file exists, it’s erased (truncated to empty) first.​

●​ Allows both writing and reading.​

●​ Cursor starts at the beginning (but file is empty initially).​


👉 Use case: Start fresh, write + then read back.

3. a+ (append + read)

●​ Creates file if not exists.​

●​ Opens in append mode (writes go to end of file only).​

●​ Allows reading also.​

●​ 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

🔹 What is a Module in Python?


A module in Python is simply a file that contains Python code (functions, classes, or
variables) that you can use in another program.

👉 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.​

○​ Examples: math, os, sys, random​

2.​ User-defined modules → you write them yourself in a .py file.​

○​ Example: You create mymath.py with some helper functions, then


import it.​
3.​ Third-party modules → installed using pip.​

○​ Examples: numpy, pandas, requests​

🔹 Why use Modules?


●​ Reusability → write once, use many times.​

●​ Organization → keep code clean and modular.​

●​ Collaboration → easy to share and maintain code.​

🔹 How it works (Concept)


1.​ Python looks at the file name (like math.py).​

2.​ When you import math, it loads that file as a module.​

3.​ You can now call math.sqrt(16) instead of writing your own square root
logic.​

🔹 Difference: Module vs Package


●​ Module = a single Python file (.py) with code.​

●​ Package = a collection of modules organized in a folder with __init__.py.​

👉 Example:
●​ random.py → a module​
●​ numpy/ (folder with many .py files) → a package

Difference in one line

●​ Encapsulation = Hiding the data (restricting access).​

●​ Abstraction = Hiding the implementation (showing only essentials).

●​ pip freeze > requirements.txt


●​
●​

%Y → Year (2025)​

%y → Short Year (25)​

%m → Month (09)​

%B → Full month name (September)​

%b → Abbreviated month name (Sep)​

%d → Day of month (19)​

%A → Full weekday name (Friday)​


%a → Abbreviated weekday (Fri)​

%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")))

date_str = "19-09-2025 14:30"

dt = datetime.strptime(date_str, "%d-%m-%Y %H:%M")

print(type(dt)) # 2025-09-19 14:30:00

●​ strftime → datetime ➝ string (formatting)​

●​ strptime → string ➝ datetime (parsing)​

import os
print(os.getcwd()) # current directory

print(os.listdir()) # list files/folders

os.mkdir('new_folder') # create folder

next_week = today + timedelta(weeks=1)

print("Next week:", next_week)

You might also like