0% found this document useful (0 votes)
9 views14 pages

Python Tutorials 1

This document is a comprehensive Python tutorial that covers topics from beginner to advanced levels. It includes sections on installation, basic syntax, data types, control flow, functions, and more, progressing to intermediate and advanced concepts like object-oriented programming, decorators, and asynchronous programming. Each section provides essential information and examples to help learners understand and apply Python programming effectively.
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)
9 views14 pages

Python Tutorials 1

This document is a comprehensive Python tutorial that covers topics from beginner to advanced levels. It includes sections on installation, basic syntax, data types, control flow, functions, and more, progressing to intermediate and advanced concepts like object-oriented programming, decorators, and asynchronous programming. Each section provides essential information and examples to help learners understand and apply Python programming effectively.
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 TUTORIALS: BEGINNER TO ADVANCED

Python Tutorial:
From Beginner to Advanced

-Anupam Shrivastava

@CODE_WITH_AS 1
PYTHON TUTORIALS: BEGINNER TO ADVANCED

Contents
1 Beginner Python Tutorial 3
1.1 Introduction to Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.1 Installing Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.1.2 Running Python . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 Basic Syntax and Variables . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5 Control Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.1 If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.5.2 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6.1 Default Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.6.2 Lambda Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Lists and List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7.1 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.8 Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.9 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.10 Tuples and Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.11 Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.12 Basic Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Intermediate Python Tutorial 7


2.1 Modules and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.1.1 Creating a Module . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.2 File Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3 List Comprehensions and Generators . . . . . . . . . . . . . . . . . . . . 7
2.3.1 Advanced List Comprehension . . . . . . . . . . . . . . . . . . . . 7
2.3.2 Generators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4 Object-Oriented Programming (OOP) . . . . . . . . . . . . . . . . . . . 8
2.4.1 Classes and Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.4.2 Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5 Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.1 Custom Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.6 Working with Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

2.6.1 Example: Using requests for HTTP Requests . . . . . . . . . . . 9


2.7 Regular Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.8 Working with Dates and Times . . . . . . . . . . . . . . . . . . . . . . . 9

3 Advanced Python Tutorial 9


3.1 Decorators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
3.2 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3 Multithreading and Multiprocessing . . . . . . . . . . . . . . . . . . . . . 10
3.3.1 Multithreading . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.3.2 Multiprocessing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.4 Metaclasses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
@CODE_WITH_AS 2
PYTHON TUTORIALS: BEGINNER TO ADVANCED

3.5 Advanced Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . 11


3.5.1 Collections Module . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.6 Asynchronous Programming . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.7 Type Hints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3.8 Memory Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.9 Unit Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

@CODE_WITH_AS 3
PYTHON TUTORIALS: BEGINNER TO ADVANCED

1 Beginner Python Tutorial


1.1 Introduction to Python
Python is a high-level, interpreted programming language known for its readability and
versatility. It is widely used in web development, data science, automation, and more.

1.1.1 Installing Python


• Download Python from [Link]
• Install and verify by running python –version in your terminal.

1.1.2 Running Python


• Use the Python interpreter: Type python in your terminal for interactive mode.
• Run scripts: Save code in a .py file and run with python [Link].

1.2 Basic Syntax and Variables


Python uses indentation (usually 4 spaces) to define code blocks. No semicolons are
needed.

1.2.1 Variables
Variables store data and do not require explicit type declaration.
1

1.2.2 Comments
1 # Single - line comment
2 """
3 Multi - line
4 comment
5 """

1.3 Data Types


• Numeric: int (e.g., 5), float (e.g., 3.14), complex (e.g., 3+4j)
• Text: str (e.g., "hello")
• Boolean: True, False
• Sequence: list, tuple, range
@CODE_WITH_AS 4
PYTHON TUTORIALS: BEGINNER TO ADVANCED

• Mapping: dict
• Set: set, frozenset
• NoneType: None
1 # Examples
2 integer = 10
3 floating = 3.14
4 text = " Hello "
5 n umbers = [1 , 2 , 3] # List
6 coordinates = (4 , 5) # Tuple
7 person = {" name ": " Bob ", " age ": 30} # Dictionar y
8 unique = {1 , 2 , 3} # Set
9 nothing = None

1.4 Operators
• Arithmetic: +, -, *, /, // (floor division), %, ** (exponent)
• Comparison: ==, !=, >, <, >=, <=
• Logical: and, or, not
• Assignment: =, +=, -=, etc.
• Membership: in, not in
• Identity: is, is not
1 x = 10
2 y = 3
3 print ( x + y) # 13
4 print ( x // y) # 3 ( floor d i v isi on )
5 print ( x > y) # True
6 print (" h" in " hello ") # True

1.5 Control Flow


1.5.1 If Statements
1 age = 18
2 if age >= 18:
3 print (" Adult ")
4 elif age >= 13:
5 print (" Teen ")
6 else :
7 print (" Child ")

1.5.2 Loops
• For Loop: Iterates over a sequence.

@CODE_WITH_AS 5
PYTHON TUTORIALS: BEGINNER TO ADVANCED

1 for i in range (5): # 0 to 4


2 print ( i)

• While Loop: Runs until a condition is false.


1 count = 0
2 while count < 5:
3 print ( count)
4 count += 1

• Break and Continue:


1 for i in range (10):
2 if i == 5:
3 break # Exit loop
4 if i % 2 == 0:
5 continue # Skip even numbers
6 print ( i) # Prints 1 , 3

1.6 Functions
Functions are defined using def and can take parameters and return values.
1 def greet( name ):
2 return f" Hello , { name }!"
3 print ( greet(" Alice ")) # O utput : Hello , Alice !

1.6.1 Default Parameters


1 def add (a, b =5):
2 return a + b
3 print ( add (3)) # 8 ( uses def aul t b=5)
4 print ( add (3 , 2)) # 5

1.6.2 Lambda Functions


Anonymous functions for simple operations.
1 square = lamb da x: x * x
2 print ( square (4)) # 16

1.7 Lists and List Operations


Lists are mutable, ordered sequences.
1 fruits = [" apple ", " banana ", " cherry "]
2 fruits . append (" orange ") # Add i tem
3 fruits . remove (" banana ") # Remove item
4 print ( fruits [1]) # cherry ( i ndexing)
5 print ( fruits [1:3]) # [’ cherry ’, ’ orange ’] ( sli ci ng )

@CODE_WITH_AS 6
PYTHON TUTORIALS: BEGINNER TO ADVANCED

1.7.1 List Comprehension


1 squares = [ x **2 for x in range (5)] # [0 , 1 , 4 , 9 , 16]

1.8 Strings
Strings are immutable sequences of characters.
1 text = " Hello , W orl d !"
2 print ( text . l o wer ()) # hello , w orld !
3 print ( text . s plit ( " ,")) # [’ Hello ’, ’ World !’]
4 print ( f" Welco me { text}") # Welco me Hello , Worl d !

1.9 Dictionaries
Dictionaries store key-value pairs.
1 person = {" name ": " Alice ", " age ": 25}
2 print ( person [" name "]) # Ali ce
3 person [" city "] = " New York " # Add key - value
4 del person [" age"] # Remove key
5 print ( person . keys ()) # di ct _keys([’ name ’, ’ city ’])

1.10 Tuples and Sets


• Tuples: Immutable sequences.
1 point = (3 , 4)
2 print ( point [0]) # 3

• Sets: Unordered, unique elements.


1 numbers = {1 , 2 , 3 , 3} # {1 , 2 , 3}
2 nu m bers . add (4)
3 print ( n umbers ) # {1 , 2 , 3 , 4}

1.11 Input/Output
1 name = input (" Enter your name : ")
2 print ( f" Hello , { name }!")

1.12 Basic Error Handling


Use try and except to handle exceptions.
1

2 num
3 num
4

@CODE_WITH_AS 7
PYTHON TUTORIALS: BEGINNER TO ADVANCED

2 Intermediate Python Tutorial


2.1 Modules and Packages
Modules are Python files you can import. Packages are directories of modules.
1 # Im port in g standard library module
2 im port math
3 print ( math . sqrt (16)) # 4.0
4 # I mport in g with alias
5 im port random as rnd
6 print ( rnd . ra nd int (1 , 10)) # Random number b etwee n 1 and 10

2.1.1 Creating a Module


Save this as [Link]:
1 def say_hello ():
2 return " Hello fr o m modu le !"

Use it:
1 import mymo dule
2 print ( m ymo du le . say_hello ()) # Hello from mod u le !

2.2 File Handling


Read and write files using open().
1 # Wri ti ng to a file
2 with open (" exam p l e . txt " , " w " ) as file :
3 file . wri te (" Hello , file !")
4 # Reading f rom a file
5 with open (" ex am p le . txt " , " r") as file :
6 content = file . read ()
7 print ( content) # Hello , file!

2.3 List Comprehensions and Generators


2.3.1 Advanced List Comprehension
1

2 num num

@CODE_WITH_AS 8
PYTHON TUTORIALS: BEGINNER TO ADVANCED

2.3.2 Generators
Yield values one at a time to save memory.
1 def fibonacci( n ):
2 a, b = 0 , 1
3 for _ in range ( n):
4 yield a
5 a, b = b , a + b
6 print ( list ( fibonacci (5))) # [0 , 1 , 1 , 2 , 3]

2.4 Object-Oriented Programming (OOP)


2.4.1 Classes and Objects
1 class Person :
2 def __init__ ( self , name , age ) :
3 self. name = name
4 self. age = age
5 def introduce ( self):
6 return f" Hi , I ’m { self. name }, { self. age} years old ."
7 person = Person (" Alice ", 25)
8 print ( person . introduce ()) # Hi , I ’m Alice , 25 years old.

2.4.2 Inheritance
1

2.5 Exception Handling


2.5.1 Custom Exceptions
1 class Cu stom Error( Excep tion ):
2 pass
3 try :
4 age = int ( input (" Enter age : "))
5 if age < 0:
6 raise Cu stom Error(" Age cannot be negative !")
7 except C ustom Error as e:
8 print ( e)

@CODE_WITH_AS 9
PYTHON TUTORIALS: BEGINNER TO ADVANCED

2.6 Working with Libraries


2.6.1 Example: Using requests for HTTP Requests
1 import requests
2 response = requ es ts . get(" https :// api . github . com ")
3 print ( response . status_code ) # 200
4 print ( response . json ()) # JSON response

2.7 Regular Expressions


Use the re module for pattern matching.
1 import re
2 text = " Contac t : al ic e@ ex amp l e . com "
3 pattern = r"\ b[\ w. -]+@[\ w . -]+\.\ w+\ b"
4 emails = re. fin dal l ( pattern , text)
5 print ( emai ls ) # [’ ali ce @ e xam pl e . com ’]

2.8 Working with Dates and Times


Use the datetime module.
1 from dateti me i mport datetime , ti me delt a
2 now = d at et ime . now ()
3 print ( now ) # Current date and time
4 yesterday = now - ti m edelta ( days =1)
5 print ( yesterday ) # Yesterday ’s date

3 Advanced Python Tutorial


3.1 Decorators
Decorators modify the behavior of functions or methods.
1 def log _ dec ora tor ( func ):
2 def wrapper (* args , ** kwargs ):
3 print ( f" Cal lin g { func . __name__ } with { args } , { k war g s }" )
4 result = func (* args , ** kwargs )
5 print ( f"{ fun c . __name__ } returned { result } ")
6 return result
7 return wrapper
8 @ l og_ dec o ra t o r
9 def add (a, b):
10 return a + b
11 print ( add (2 , 3))

@CODE_WITH_AS 10
PYTHON TUTORIALS: BEGINNER TO ADVANCED

3.2 Context Managers


Manage resources like files or connections.
1 from contextlib import c o nt ext man ag er
2 @ c on t ex t manager
3 def temp _ file ():
4 print (" Creating temp file ")
5 try :
6 yield " temp . txt"
7 finally :
8 print (" Cl ea n i n g up temp file ")
9 with temp _fil e () as filen ame :
10 print ( f" Using file : { fil en ame }")

3.3 Multithreading and Multiprocessing


3.3.1 Multithreading
For I/O-bound tasks.
1 i mp ort threading
2 import time
3 def pr i nt _ nu mb er s ():
4 for i in range (5):
5 print ( f" Nu mber : { i}")
6 time . slee p (1)
7 thread = threa din g . Thread ( target= pr in t _n um bers )
8 thread . start ()
9 thread . join ()

3.3.2 Multiprocessing
For CPU-bound tasks.
1 from mu l t ipro cess i n g imp ort Process
2 def co mpu te_sq uare ( n):
3 print ( f" Square of { n }: { n * n}")
4 processes = [ Process( target= compu te_ square , args =( i,)) for i in
range (5)]
5 for p in processes :
6 p. start ()
7 for p in processes :
8 p. join ()

3.4 Metaclasses
Control class creation.
1

@CODE_WITH_AS 11
PYTHON TUTORIALS: BEGINNER TO ADVANCED

10

11

12

3.5 Advanced Data Structures


3.5.1 Collections Module
1 from collect ions import Co u nter , defaultdict , namedtuple
2 # Counter
3 counts = C ou nt er ( " mississippi ")
4 print ( counts) # Co unter ({ ’ i’: 4 , ’s’: 4 , ’p ’: 2 , ’m ’: 1})
5 # Def aul tdi ct
6 d = d efaul tdic t ( int )
7 d[" a"] += 1
8 print ( d) # defaultd ict ( <class ’ int ’ >, {’ a’: 1})
9 # Namedtuple
10 Point = n am edtuple (" Point " , [" x" , " y"])
11 p = Point (3 , 4)
12 print ( p.x , p. y) # 3 4

3.6 Asynchronous Programming


Use asyncio for concurrent tasks.
1 i mp ort asyncio
2 async def say_hello ():
3 print (" Hello ")
4 await asyncio . slee p (1)
5 print (" World ")
6 async def main ():
7 await asyncio . gather( say_hello (), say_hello ())
8 asyncio . run ( main ())

3.7 Type Hints


Improve code readability and catch errors.
1 from typing im p ort List , Dict
2 def greet_all( names : List [ str ]) -> Dict [ str , str ]:
3 return { name : f" Hell o , { name }!" for name in names }
4 print ( greet_all ([" Al ice ", " Bob "]))

@CODE_WITH_AS 12
PYTHON TUTORIALS: BEGINNER TO ADVANCED

3.8 Memory Management


Use weakref for weak references.
1 import weakref
2 class Object :
3 pass
4 obj = Object ()
5 ref = w eak ref . ref( obj )
6 print ( ref()) # < Object object at ... >
7 del obj
8 print ( ref()) # None

3.9 Unit Testing


Use unittest for testing.
1 im port unitt e st
2 def add (a, b):
3 return a + b
4 class T estM at h Op e rati o ns ( unitt est . TestCase ):
5 def test_add ( self):
6 self. asse rtEqual( add (2 , 3), 5)
7 self. asser tEq ua l( add (-1 , 1), 0)
8 if __name__ == " __m ain__ ":
9 unit test . main ()

@CODE_WITH_AS 13
PYTHON TUTORIALS: BEGINNER TO ADVANCED

Follow @Anupam Shrivastava to stay updated


on Python/ Data Science/ AI/ ML/ BI

🔔 Don’t forget to like, share, and subscribe to


@Code_with_AS for more Python tutorials and
mini-projects!

@CODE_WITH_AS 14

You might also like