[Go to site: main page, start]

0% found this document useful (0 votes)
10 views66 pages

Complete Python Notes

This document provides an introduction to Python, covering its history, features, advantages, and disadvantages. It also includes installation instructions, basic programming concepts, data types, operators, and control flow statements. The document serves as a comprehensive guide for beginners to understand and start programming in Python.

Uploaded by

Soumya Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
10 views66 pages

Complete Python Notes

This document provides an introduction to Python, covering its history, features, advantages, and disadvantages. It also includes installation instructions, basic programming concepts, data types, operators, and control flow statements. The document serves as a comprehensive guide for beginners to understand and start programming in Python.

Uploaded by

Soumya Das
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Complete PYTHON — Notes — @ Chapter 1: Introduction to Python @ curious_programmer What is Python? = Python is a popular, high-level, interpreted programming language known for its simplicity and readability. It is used for web development; data science, AL, automation, and more. History of Python +1989: Python created by Guido van Rossum qi at CWT, Netherlands | +1991: Python 0.9.0 released - included features like classes, functions += 2000: Python 2.0 released - added lict comprehensions, | garbage collection ¢ || «2008: Python 3.0 released - improved language Q | constructs, better Unicode support Features of Python “G) Easy to Learn: Simple and easy to-understand syntax Cross-Platform Runs on various platforms (Windows, Mac, Linux) Readable : Code is clear and B= readable like Enolich Fi] Large Standard Library ‘3 ES Rich set of modules & Interpreted: Executes code functions for various tasks line by line, no need for Dial 3 namically Typed complatien Sea] No need to declare variable Cross-Platform: Runs on at ore various platforms ([Link], 252 Open Source Linux) s : Free and open source, with a large community Advantages & Disadvantages @ curious_programmer @ Advantages =» (®) Disadvantages v Simple and Easy to Leam: x Slower Execution: Reade like Englich, reducing Interpreted nature makes it learning curve slower than compiled languages. wv Extensive Libraries: Rich » Triple-Quoted Comments + These are for multi-line [aes comments. *® Comments make your code more readable and understandable, Chapter 3: Python Basics = @ Curious_programmer @ Keywords & Identifiers * Keywords: Are words in Python that are reserved and cannot be used as identifiers Keywords: | if, else, for, while, def, import, class, None ... L = * Keywords include conditional statements, loops, functiondefs tions, and more e Identifiers: Are user-defined names for varicbles, functions, classes, and more. © Good naming conventions: + Should start with a letter (a-z,A-Z) or an underscore (_) *| my_variable, count123, data, sum total | 2nd_name, my-var, for*count | € tnvalid identifiers @ Variables ® Variables in Python are used to store data values like numbers, strings, lists, etc © No need to explicitly declare the variable type in Python, its dynomically typed © Example: a variable assignment: | name age | height neers = “Ate 7 Alice’ 25 5.7 age = 25 foonees s ® Variables. store values in memory © No spaces © No special characters ($, 6, %, %) © Identifiers are case-sensitive Data Types Overview @ curious_programmer © Data Types Overview ® Data types classify the type of value a variable holds * Common Puthon data types are listed in following examples [ eres Gno * = 10: | Floats (float) = Z | Strings (str) —- name = “Alice” | Lists (list) _ numbers = £1,203) | tuples (tuple) point = {(name": “Bob”, “age: 30} ® Different data types allow you to work with various kinds of data. Type Casting @ Type casting is converting a value from one data type to anather. © Tn Python, you can do this using built-in functions like int, fleatO, and strO © Use intO to convert to an integer. | int _ | — | | heigl coriginal_str = "123° _>»|123. || 4s || 57 number = int(original_str) Result: number = 123 # converts string to int © Use str to convert toa float: | number as _| heart | age = 25 So 2s7 |[-s.7_| age_str = str(age) # converts string to float Result: age_str = °25' © Type casting is useful when you need to perform operations between different data types: rr Input & Output es @ curious_programmer @ printO function @ The printO function is used to output data to the screen, You can print strings, numbers, and more. print C"Hello, Python!") Hello, Python: print ("The answer is, 42) The answer is. * You can use comma seperators to print multiple items print("Name: “Alice") Name: Alice print ("Hello, fname}!"), @ You can use Surith formatting note LGiLS © Indentation in Python Indentation is used to define the structure of the code Python uses indentation with four spaces to indicate code blicks. @ Indentation is essential for loops, conditionals, and function definitions @ Incorrect indentation can cause errors. Comeat: > Incorrect indentation if age >= 18: print c" Adult") if age >== 18: print "Adult" else: PR else: printC*Minor: by print C" Minor") IndentationError: unindent : 55° does oot match any outer Resul sty = "25 ee indentation level @ Type casting is useful when you need to perform operations between different data types ‘eee Chapter 4: Python Data Types @ curious — programmer © Built-in Data Types Python has several built-in data types that are used to store diferent types of values. The main built-in numeric types are int, Float, and complex, and there is also a a Boolean type. Numeric W int: Storing integer values. Example: a = 10, b =-25 © float : Storing floating point numbers (decimals). Example: ¢=3.14,d=05 © complex: Storing complex numbers with a real and imaginary part Example j w 15} Boolean Storing true or false values. The Boolean values are: True and False. vp = True KA True v q=False [X] False “|: — @curious_programmer —— 2 o String A string is a sequence of characters enclosed in quotes Tt is used to store text name = “Alice” [ greeting = “Hello, World!" | fruit = “apple” i eh VA Fith o None Type The NonéType represents the absence of a value. Tt has a single value: None. result =None _ Chapter S: Python Operators @ curious_programmer ® Arithmetic Operators * Arithmetic operators are used to perform basic mathematical operations ® Numeric © Arithmetic operators ate used to perform basic mathematical ‘operations. [Operator | Description | Example | Result reser ee Addition ty k= — | Subtraction x-y } * Multiplication: x+y peer Division’ Ky R= By SB % | Modulus x% 4 (remainder) Z © Different data types allow you to compare two values. © Relational (Comparison) Operators ® Relational operators are used to compare two values and return Boolean result (True or False). © Indentation is essential fer loops, conditionals, and function definitions. @ Relational (Comparison) Operators © Relational operators are used to compare two values. Operator | Description | Example Equal to x==y x=7%y=5 Notequalto x!=ay > Greater than x>y | ee Less than x10 =False | or a10 =True | not nota = True © Assignment Operators Assignment operators are used to assign values to variables. Operator Example += Addition x+=3 (x=x4+3) —= Subtraction x—= (x= x= 2) *= Multiplication) x#=4 9 (x=x*4) /= Division x/=S (x=x/5) | %= Modulus x%=2 (X=xX%2) | += Exponentiotion x**=3 (x=x** 3) =x//3) ee [= Floor Division | @ curious_programmer © Bitwise Operators Bitwise operators operate on bits of integers and perform operations bit by bit Operator Meaning Example & Bitwise AND 5&3=1 | Bitwise OR 513=7 ie Bitwise XOR 543=6 ~ Bitwise NOT ~5=-6 | << Left shift S's<'1=10 | >>| Right shift Sr) = peers a © Membership Operators Membership operators are used +o test whether a value is present in a sequence (eg. list, string) Operator Example Sig Returns True if a value is found in the sequence ‘a! in “apple” = True not in Returns True if a value is not found in the sequence. | ‘x'not in [1, 2,3] = True J Z @ curious—programmer © Identity Operators ® Identity operators are used to compare the memory location of two objects. © is: Returns True if both variables refer to the same object. @ is not: Returns True if variables do not refer to the same object (12,3) b= Gs! a is not b= True is not ies not | Multiplication a== | Division (remainder) | X/¥ (2:3) = 40 | x %y = 2 © Note: Identity operators are used to check if two variables point to the sameobject in memory @ Operator Precedence © Operator precedence determines the order 3f operations in expressions. © Operators with higher precedence are evaluated first. Operator(s) | Precedence *~ Exponentiation — Exponentiation A //1% | Pv // == +> | Muttipication, Diision, Fear Division, Moduks i= Addition, Subtraction ea ie] ><=: | Identity, Assignment, Comparisons © Example: 10 - 3*2.// 5 is evaluated as 10 © Result: 10 - (6/5) = 10-1 (3*2) 75). = 9; @ Example: 10-3*2.1'S is evaluated as 10 -(3*2) // 5) © Result: 10-(6/5) =10-1=9 Chapter 6: Control Flow Statements @ curious_programmer © Conditional Statements Conditional statements allow you to make decisions based on conditions. The main conditional statements in Python are: olf The if statement executes code block only when the condition is True age = 18 if age == 18: print (You are an adult." ) | o if-else The if-else statement fine one) cede block ifthe Zondition is True and another code block if it is False Operator Example in Returns True if a value is found in the sequence. | ‘a’ in “apple” = True not in Returns True if a value is not found in the sequence. xc not in (1,2, 3] = True © Nested if An if statement inside another if statement to check multiple conditions. num = 15 if num > 10: | print (Value is greater than 10.) | else: | print (Value is greater than 5') print ("Value is 5 or less.) og @ curious_programmer © Looping Statements © The for loop is used for iterating over a sequence (like a list tuple, or string) © is not: Returns True if both variables refer to the same object. © is not: Returns True if variables do not refer to the Sar 2 object. Operator | Description | Example enue is | Addition x+y G2s)yex |xisye True is not | Multipieation count = Output | while count<3: | O print(count) 1 count += 1 2 © Executes the block of code while the condition remains True. @ Nested loops © Anested loop is a loop inside another loop. eS Loop Control Statements © break: Terminates the loop early for i in range(5): Output if i== 3: ° break 1 print GD 2 © continue : Skips the rest of the loop and continues to the next iteration, © pass: Acts as a ploceholder for code to be added later | Operator(s) | Precedence | Output: tee | for iim range(s) TTerminctes the Wspecrly | 0 iss 1 break sero 2 prank Pass 4 © pass: Acts asa pacclethe loop and continues to the next iteration. for i in range(s) | Output: | Output ° ° 1 1 2 2 > printa = a = SC _ Chapter 7: Strings in Python @ curious_programmer @ String Creation A string is a sequence of characters enclosed in quotes. in Python strings can be created by enclosing characters in quotes: | ee Triple quotes"! ub alllow for | multi-line strings. © Indexing & Slicing Strings are indexed starting from ©. We can occess parts of a string using indexing and slicing: fpoe ee On tate ee tee Os Meza Dima ueee y=. Ply lt [hfe ln] Si a a Se [Index / Slice |) ERample text[O] "P" First character text[-1] —® | "Nn" Last character text [0:2] —- | “Py" Characters from index © to 2 (exclusive) text[1:] “ython" Characters from index 1 to end text[-3:] —e “hon” Choracters from the third to last to end text[:2] —» "Pto" Characters from start to end with step 2. @ curious—programmer © String Methods String methods are built-in Functions that perform operations on string data, like changing letter case, removing whitespace, or replacing parts of the string, ‘2 ‘String methods are built-in functions for manipulating and managing ‘String data. ~~ text = *hello world” => “HELLO WORLD” text = “Hello World” => "hello world” text - "__python__" => “python” textstripQ = “python’ = “mananas” textreplace(‘ban’, “man) = “mananas” 1 © String Formatting String formatting lets you construct strings by inserting values frorn variables into string templates — format®) Met pS f-Strings name = “Alice’ age =25 greeting = f"My name is {name} and Lam {} yearsold. and Lam Lam {age} years old.” format(name, age) Print (greeting) | Print (greeting) Output.” My name is Alice | Output. "My name is Alice and Tam and Tam 25 years ald.” | | 25 years old.” © String Formatting String formatting lets you construct strings by inserting values from variables into string templates is {} and Lam {} years old." @ curious_programmer © Escape Characters Escape characters are special characters in strings that start with a backslash (\) and are followed by a character to represent special characters within a string frittte=nenort 2 String methods are built-in functions for manipulating and managing string data. “~~ Description Inserts a new line. Inserts a tab Inserts a single quote Inserts a double quote Example ©CodeWithCurious text = "Hello, This is a new line.” print (text) Output. Hello, This is a new line. | © String Functions String functions are built-in functions that operate with or on string data. Example amt = "Simple123” length = lenCamt) # length is now 9 Output: 9 © Immutability of Strings Strings are immutable, meaning their values cannot be changed after they are created. To modify a string, a new string must be created. Example greeting = “Hello” ‘inglO] = "J” # This causes an error! Chapter 8. Lists @curious_programmer Creating Lists Lists are created by enclosing items in square brackets []. Lists can store items of any data type. @ numbers = [1, 2, 3,4, 5] — int mixed_list = ["Python", 42, 3.14, True] —-str, int, float, bool, bool Example fruits = ["apple", “banana', ‘cherry”] © List Indexing & Slicing Lists use zero-based indexing. You access individual elements using their index or use slicitig to, colors = ["red’, ‘green’, ‘blue’, ‘yellow’, ‘purple”] colors[0] —["apple’, "banana’, “cherry’] Output: “red” © List Indexing & Slicing Lists use zero-based indexing. You can access individual elements using their index or use slicing te access a range of elements. colors = ['red”, ‘green’, ‘blue’, ‘yellow’, ‘purple"] colors[O] Output: “red” colors[1:4] Output: ['green’, “blue’, ‘yellow"] © Negative indices start at -1 for the last element. © Slicing: list[start:stop] Stops at the index before stop. @ curious_programmer © List Methods Lists are created by enclosing items in square brackets [], Lists can store items of any data tupe. Fruits = [Yapple’, banana’, cherry" ‘Output: 1 O° Nested Lists Lists can contain other lists, creating nested lists. These are lists within lists moatrix[1[2] ‘Output: (1, 2, 3] Output: 6 © Negative indices start at -1 for the last element. © Slicing: list [start:stop] Stops at the index before s top. @ curious_programmer © List Comprehension List comprehension provides a concise way to create lists. Useful for transforming or filtering elements in a list © squares = [x**2 for x in range(S)] Output: [0, 4, 4,.9,16] © evens = [x for x in range(10) if x % 2 == 0] Output: [0, 2, 4, 6, 8] © Difference between List & Array Lists and arrays Gri Bet palbevonb)é Refig) bUE they have some important differences Implemented in Python natively Requires Ning package Flexible, can store | Fixed data type for all different data re elements ate general | Efficient for numerical purpose usage operations. import numpy as np: a=[Link][4, 2, 3,4, 5]) print (a) ‘Gutput: array{[1, 2, 3.4, 51] Chapter 9. Tuples @ curious_programmer © Creating Tuples Tuples ore ordered, immutable collections of iteme, Created by enclosing elements in parentheses © colors = ["red’, for x in range(511 Output Dred’, "green’, *biue"] O numbers = (1, 2,3,4,5) Output: [0, 2,4, 6,8] singleclement= (42,) (note: needs a comma) © Tuple Operations Tuples support in, Li with commen tide - Lists } Arrays Implemented in Requires Numpy package Python natively rece and combin used Flexible, can store | Fixed data tupe for all different data tupes elements. | Good for general Efficient for numerical | purpose usage operations. © Tuples are immutable: cannet be changed offer creation. © Tuples can be used as keys in dictionaries (lists can't). import numpy as np @ = [Link][ C1, 2, 3, 4,51) print (a) Output: orray[[1,2, 3,4, 57] @ curious_programmer uple Metheds Atthough tuples are immutable, they do have two methods that: can be used to gather information. i ) | Returns the number of occurrences of a value “inde Retums'the indaxof the first occurrence offa value O numbers = (1, 2,3, 3,2, 4,2). Output= numbers:.count(2) 20, 30, 40, SO fs - ide nae OadewithC urious Output: 3 ecg pecking: Returns the number of Common idoerences: _| ene pair: “Packing: | packed =1,2,3,4.5 | Output: (1,2.3,4,5] © packed = 1,2,3,4,5 Output: (4, 2.3,4,5) © 4,6, ¢ = packed Output: a; 1, b, 2, <: 3 @ first, #rest = (4, 2, 34,5] Output: first: 4, rest: [2,3,4,5] Mutable untO, index) append), extend(),, | popO. ee Generally for fixed Used for dynamic O tuplel = (4, 2,3) Supt appendis) © listt = (4,2, 3] list append(4) Output: [1, 2, 3, 4] Chapter 10: Sets @ curious — programmer Creating Sets A set is a collection of unique, unordered elements in Python Sets can be created by using the set() function or by enclosing elements in curly braces {}. © seti= set([1, 2,3, 4}] # Using set () function © set2= {5,6,7,8) # Using curly braces Set Properties v Elements are unordered; duplicates are not allowed. v Sets are mutable, meaning you can add or remove elements y You can use the 1én()-function to get the! number of elements in a set. Example: len(set2) returns 4 Set Methods © add(x): Adds element x to the set. fm remove x) Remes cenent fron te sel, raises KeyError if not found. @ union(set2): Returns a new set with elements from the original set and set2. @ intersection(set2): Returns a new set with elements common to the original set and set2 @ intersection(set2): Returns a new set with elements common to the original set and set2. Set Operations @ curious_programmer @ Union The union of two sets retums a new set containing all unique elements frorn both sets: set1 set2 set1 = {1,2, 3, 4} | aes set2 = {3,4, 5,6} i-< a set1 | set2 # (1,2,34,5,6} | a e set2 o Intersection sell The intersection of two sets retums anew set containing only the common elements set1 set2 setl = {1725°8, 4} set2 = {3,4,576} | set1 & set2 # {3,43 o Difference The difference of two sets returns a new set containing the elements in the first set that are not in the second set. set1 set2 set1—set2 # {1,2} | ae as set1—set2 # {1,2} ace ° Frozenset_ A frozenset is an immutable version of a set in Python Tt acts like a set but cannat be modified, | fs = frozenset (1, 2,3, 41) Chapter 11: Dictionary @ curious_programmer © Dictionary A dictionary is a collection of key-value pairs that is mutable and unordered. In Python, dictionaries are defined using curly braces {} with key- value pairs separated by colons © Creating Dictionary. To create a dictionary, define it using curly braces, with key- value pairs separated by colons. my-dict = { "name": “Alice”, "age": 25; "city": "New York") student_scores = {"Math!: 85, 'English': 92, “History': 78 } @ Accessing Elements Use the key in square brackets to access the value associated with that key: print (my-dict ["name"]) # Output: Alice. print (my-dict ["age") # Output: 25, print(student_scores["Math"]) # Output: 85 print (student_scores["English']) # Output: 92 print (student_scores["Math"]) _ # Output: 85 print Gtudent_scores["English"]) # Output: 92 @ curious_programmer © Dictionary Methods Keys, Values & Items © Dictionaries are created by enclosing key-value pairs in curly braces {}. Keys and values are separated by colons and each pair is separated by commas © student = [‘name': ‘Alice’, ‘age: 25, ‘city’: ‘New York"} (0 > keys( —> student = student. ke Output: dict_keys(L'name’, ‘age’, ‘city"]) © > values( —> student = (“age’, 25), City", "New York")]] © ?[Link] — Retums a view of all keys in the dictionary, [Link] > Retums a view of all values in the dictionary: © > [Link] > Returns a view of all key-value pairs as tuples. © [Link]© —> Returns a view of all keys in the dictionary, © [Link] > Returns a view of all values in the dictionary. © [Link] > Retums a view of all key-value pairs as tuples. @ curious_programmer Nested Dictionary —> Nested dictionaries are dictionaries within dictionaries. They are useful for storing complex data hierarchies © Example = SESSA © Dictionary Comprehension —> Dictionary comprehension creates dictionaries in a concise way by iterating over an iterable and applying an expression to each item. O squares = (4 x**2 for x in range(1, 6). Output: Ur 4, 2,4, 3:9, 4, 16, 5: © evens = (x: xt*2 for x in range(1, 11) if x % 2 =O) Output: (2:4, 4, 16, 6: 36, 8,64, 10: 100) © Conditional dictionary comprehension example: x#*2 For x in range(1, 11) if x % 2 == 0) 4, 4.16, 6: 36, 8, 64, 10: 100) Chapter 12: Functions @ curious_programmer @ What is Function? A function is a reusable block of code that performs a specific task Functions help break a program into smaller, manageable, and reusable parts. © Defining & Calling Functions To define a function in Python, use the def keyword followed by the function name, parentheses Q, and a colon MietprectO: # This defines a Function named grect: | def greet(): # The function name followed by parentheses greet # Calls the gréet Function, output: Hello, World! | def add(a, b): # This defines a function named add. returna + b result =add(5, 7) # Calls the add function with arguments Sand 7. print(result) # Output: 12

You might also like