0% found this document useful (0 votes)
30 views219 pages

PythonVK.notes

The document provides a comprehensive overview of Python, covering its history, key features, and applications. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various domains including web development, data analysis, and machine learning. Additionally, it explains fundamental concepts such as data types, operators, and programming structures in Python.
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)
30 views219 pages

PythonVK.notes

The document provides a comprehensive overview of Python, covering its history, key features, and applications. It highlights Python's simplicity, versatility, and extensive libraries, making it suitable for various domains including web development, data analysis, and machine learning. Additionally, it explains fundamental concepts such as data types, operators, and programming structures in Python.
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
You are on page 1/ 219
python’Content Overview with Page References Quick access to topies in python Topic Introduction to Python operations in Python User Input and Type Conversion Control Flow Loops: Patterns Strings Allasing and Cloning Tuples sets Dictionaries Functions in Python Scope of Variables Recursive Functions Lambda (Anonymous) Functions Modules File Hancling Regular Expression Exceptional Handling Intraduetion to OOP Concepts:Guido van Rossum father of python Introduction to Python Python ie @ general-purpose, high-level, interpreted, and object-orianted programming language used for a wide range of applications. Developed by Guido van Rossum in 1989 while working at the National Research Institute In the Netherlands, Python was offically released to the public in 1991, Python 10, released in January 1994, Introduced features like functions, exception handing, and core data types such as lists, dletionarles, and strings, Python 2.0 followed in October 2000, bringing features lke list comprehensions and garbage collection based on reference counting, Python 8.0, released In December 2008, introduced backward: incompatible changes to improve language consisteney and ‘efficiency. Today, the latest version of Python continues to enhance ite feature set eupparting outting-edge technologies like machine learning, data science, and web development. Ite syntax, which uses English Keywords, males Python easy to read and understand, making it @ top choice a8 a first programming language for beginners. The language includes high-level data structures, dynamic typing, and dynamic binding, making it highly attractive for rapid application development. its simplicity and readability help reduce program maintenance costs, while its support for modules and packages encourages program modularity and code reuse.Python is a general-purpose, high-level programming language that supports object-oriented programming (00P). itis dynamically typed, interpreted, and commonly used as a scripting language, known for its simplicity, versatility, and extensive iibraries for diverse applications. Key Features of Python General-Purpose: Python Is versatile and suitable for various applications scientific computing, machine learning, data analysis, and automation, Including web development, ‘Simple and Easy to Learn: Py:hon’s syntax Is straightforward and resembles English, making it an Ideal choice for beginners. With only 80+ keywords, Python reduces complexity, enabling faster development and lower maintenance costs. High-Level Language: Abstracts low-level details such 2s memory management and hardware intricacies, allowing developers to focus on problem-solving rather than technical overheed, Object-Oriented Programming (OOP): Python supports OOP principles Ike classes, objects, inheritance, and polymorphism, promoting code modularity and reuse. Dynamically Typed: Variables do not require explicit type declarations, Python determines the type at runtime, reducing bollerplate code and enabling faster development. Interpreted Language: Python executes code ine by line, simplifying debugging and supporting quick prototyping. Ths feature also makes Python an excellent scripting language for task automation. Portability: Python ensures consistent results across platforms, making it highly portable. Developers can migrate Python pragrams between syateme without issues,Integration with Legacy Code: Python allows integration with pre-existing codebases in languages like C, C++, and Java, ensuring compatibility with older systems. Embedded Capabilities: Python can be embeded in applications written in other programming languages toextend their functionality Extensive Standard Library: Python comes with a rich set of built-in ibrarias for take lke fle hanaling (08, shuti), web scraping (urls, htmlparser), data processing (csv, json), and more. These libraries enable developers to perform complex tasks without the need to write adcitionsl code, saving time and effort. Ecosystem of Third-Party Libraries: Python boasts over 137,000 third-party libraries, such as NurnPy, Pandas, TensorFiow, and Flask, making it a powerhouse for specialized domains like Al, web development, and data Free and Open Source: Python Is freely avallable for personal and commercial use. Its source code Is open, sllowing developers to moclfy and adept it to their needs. Improved Performance via Tools: Too's lke Cython, PyPy, and integration with C/C++ libraries enhance Python's performance, making it suitable for computationally intensive applications such as scientific ‘computing, machine learning, and real-time systems.Applications of Python We can use Python everywhere because Python is known for its general-purpose nature, which makes it applicable in almost every domain of software development. The most commen application areas are + Desktop Applications + Web Applications + Database Applications * Network Programming + Games + Data Analysis Applications Machine Learning Artificial inteligence Applications + lorPrint() = In Python, the print() function is used to output data to the console or standard output device. It can display strings, numbers, fr any other data type, making ita fundamental tool for debugging and providing information to the user. What is keyword in Python? in Python, there are 35 keywords that are reserved words with Special meanings, and they cannot be used as identifiers. These keywords define the syntax and structure ofthe language." [print ("keyword in Python") Lmport keyword print (keyword. kwlist) [None and True are special constants in Python and are always capitalized. They should not be used as identifiers + All the other words, such as and, assert, def, etc, are reserved keywords In Python. These keywords are writen in lowercase and have specific mesnings and functionalities within the language, s0 they cannot be used as variable names or identifiers.‘Comments Comments in Python are non-executable lines of text that describe what is happening in the code, helping othere (6r yourself) understand the program's logic and purpose. + Single-ine comments:- Use the # symbol to create a comment: + Multitine comments: Use triple quotes Doestrings Docstrings, or documentation strings, are 2 type of multi-line comment used to describe the purpose and behavior of functions, classes, and medules in Python. They provide a convenient way to decument code and can bbe accessed programmatically. fonexecutable part of program "ke ds used for multiline coment! “"" this is a docstring that describes what the function does."*" arlo Print (a)Python Identifiers ‘What are Identifiers? “Identifiers a names used to identity variables, functions, classes, or other objects in Python, Rules for Naming Identifiers + Must bogin with a latter (A-Zor a-2) oran underscor + Cannot start with a digit. + Can contain letters, digits, or underscores. + Case-sensitive (e.g, myVar and MWar are different) + Cannot use Python keywords or reserved words. Examples of Identifiers Valid Identifiers: Invalid Identifier + my.variable + 125variable + datarzs + my-variable + temp var + for + variable t + pricertoft + employes_name + @username + customer id + class: + product price + totalSamount + User login status + myvariable 2nd_placePython Variables A.variable ie a memory location or container usad to atore data. It has a name (identifier) that allows you to reference the stored value, Variables can hold different types of data, such as integers, floats, strings, or ists. ==> value t ¥ variable <_ variable value . volue types in python data represent the kind of stored a variable. you do not need to explicitly declare type instead is automatically determined based on assigned this makes dynamically-typed language. int fatnen er rn eeermnae="a" bytes ks oe aa tea segues ae tuple rae set frozenset dict sepa min en te testes ee nonetype fenrseana cies ern felnefeefeme fen cele enetype>Operators in python Operators are special symbols used to perform operations on variables and values. They alow you to manipulate data and variables In varlous ways, such ae performing arithmetic Calculations, comparing values, and combining logical expressions, Categories of Operators in Python + Arithmetic Operators + Comparison Operators + Logical Operators + Assignment Operators + bitwise operators + Membership Operators + Wdontity OperatorsCRG pan 6TH TT We Beintta + bb pe Feist tea fu Brine (ote) ee sint(0/p) Peinetavay princi) Brine wwtesy Arithmetic Operators: Used to perform mathematical operations Addition (+) x= 5: rint(x+ y) # Output:8 + Subtraction (-) 1; 4; print(a-b) # Output: + Muttipication (+) m = 7: = 6; print(m * n) # Output: 42, + Division (/) p= 18:4 = 3: print(p Ja) # Output:5.0 + Floor Division (//) r= 17:8 = 4% print(r 11s) # Output: 4 1 Modulus (%) = 10;u = 3; print(t %u) # Output: + Exponentiation ()" :print(v**w) # Output: 820 be50 print (ab) 2-20 be50 print (acb) + Comparison Operators: Used to compare two values + Equal to (==) x=5:y = 5: printix==y) # Output: False a at ) x= Sty = Sip yh ## Out Ee inary # Not equal t (=) 8=10;b = 4: print(a I= b) # Output: True 20 * Greater than (+) m= 7:n = 6;print(m > n) # Output: True belo print (aceb) + Less than («) p= 18:4 20; print(p =) r= 17; 8 «17; print{r>= 8) # Output: True bes + Loss than or equal to ( 10:4 2; print(t 10)¢At least one condition is tre Woutpue: true # Logical Nor (not) aos Brint (not (2 ) Shite bts tothe right, effectively dividing the number by powers of 2Key Notes: + Applicable to Integers and Boolear ‘also work with boolean values (Tru Bitwise operators are mainly used with into |. False =0), + Shift Operations: Loft shift multiplios by powers of 2,while right shift divides by powers of 2. ‘+ Negative Numbers: The NOT operator gives negative results in Python due to two's complement representation + Low-Level Data Handling: Eitwise operators are essential for tasks like data manipulation, encryption, compression, and interfacing with hardware.AND (8): + Insight: The result ist only if both bits are t, otherwise, the result is 0. + Example:1& 1= 1,but1B0=0andoa, + Perform the Bitwise AND: Tho bitwise AND (8) operator compares each bit from the two binary number. The result is ‘nly when Both corresponding bits are and 0 otherwise. x= 51 #Binary: 110011 y= 30 #Binary: 011110 ppaeaeag ocr emenests nce result = x & y oes moon print (result) + result = 010010 #resul 18 + Calculation Breakdown: + First bits 1 AND + Second bit: AND 1 Third bit: AND 1= 0 + Fourth bit:0 AND Fifth Bf AND 1=1 Sith bits 1AND:+ Bitwise OR (): + Insight: The result is tif atleast one itis 1, otherwise, the results . + Example: 110=1,010=0,and1] + Perform the Bitwise OR: The bitwise OR (|) operator compares ach bt of two binary numbers. The result ist when at least one cof the corresponding bits is 1, and 0 only when both bits are 0. + Let's align the binary representations of a,b, and ¢: prine(a |b) # Result: 7 (Binary: 9110) | 7 Gor gengeed) —TheremuktaoM.whichle in deoina Prints | c) # Results § (Binary: C100) gin gay + Jo101 (e=5) “OM (Result=7) The result is O11, which 7 n decimal, + 0100 (b=4) + Jo101 (#8) ‘The result is 0101, whichis Sin decirnl+ Bitwise XOR (*): insight: The result is 1if the bits are different (one is 1,the other Is 0} Example:1*0=1,0™1=1,and1* + Perform the Bitwise XOR: The bitwise XOR (*) operator compares each bit of two binary numbers. The resuit is 1 when the corresponding bits are afferent, and 0 when the corresponding bits fare the same. Let's align the binary representations of a and b: @=o1010 b=100100, a= 010110 b= 36 #Binary: 100100 print (a * b) #Result: 50 (Binary: 110010) + result= 10010 + Calculation Breakdown: + Firat bit:0XOR1 + Second bit: XORO=1 + Third bit 0 XORO + Fourth bit 1XOR Fifth bits1 xORO Sixth Bit: 0XORO "0 Result: 60 (Binary: 110010)twvige NOT (-): + Insight: The NOT operator flips the bits. If the bit Is, It becomes 0, ‘and fits 0, e becomes + Example:1= 0 (fips 1 t0.0) and 0 = 1 (flips 0%01). + Perform the Bitwise NOT (-) : inverts each bit of a number: 1 ‘becomes 0, and 0 becomes 1. It works on a single operand and returns the two's complement of the number. x= 27 + Let's align the binary representations of x andy: y= 18 x= 00011011 (Binary of 27) ¥= 00010010 (Binary of18) print (+x) # Output: -28 print(~y) # Output: -19 ememerenrs coeds Forx=27: + Binary of: 0071011 + NOT (x Fall bts > 00100 + Interpretation: 28 n two's complement (Decimal) Fory= 18 * Binary of y: 00010010 # NOT Cy): Flip allie > most01 + Interpretation: 19 in two's complement, (Decimal)xed x result = x > 1 shifts bits of 8 (1000) to the right, resulting in 4 (0100), equivalent to 8/2 = 4. + Perform the Bitwise Right Shift The bitwise Right Shift (>>) operator shifte the bite of a number to the right by @ specified number of positions. it discards the rightmost bits and fils the leftmost bits with =5 Zeros (fo positive numbers). Each shift divides the rumber by 2. For y ‘example, shifting a number by one position to the right is equivalent to y_result = y >> 1 dividing it by 2. print(y, y result) Sat align the binary reprecentations of xand x roma Y=5 (Binary representation: 0101 #output y 5 y.result = y >> 1 (Binary after right shift by 1: 0010, foutput y_ result 2 + Caleulation Breakdown: + Original Binary (y = + Binary: 0101 + Right shift by 1 Position: + Shift allbits one place to the right: 0010 + Interpretatios + Binary 0010 equals 2in decimal‘+ Membership Operators: Used to test Ifa value isin a sequence, ‘membership operators in , not in sin setaditya” print ("a" in s) + numbers = [1,2,3,4, 5]: print(S in numbers) # Output: True sMaditya" + prine(6 in numbers) # Output: False print ("A" in s) inname) #¥ Output: True as"prathanesh” print ("o" in a) . name) # Output: Flee ‘prathamesh” print ("p" in a) + notin + letters = "Hello; print(2" not in letters) # Output True 'varad” print ("" not in a) + print(H" not in otters) # Output: False as"varad” «+ fruits = [banana’, ‘cherry"l print("orange notin fruits) # Output: True print ("d" not in a) + prine(tbanana" notin fruits) # Output: FalsePaine (@ sob) fee eine (48tap) ‘eine (iste) print (@ te b )Afaioe fede (4tta)) fess (ast) pint (@ s9 sot B yealoe Pelatla so not b) # Tews, because « and b have different valves eine (satan) Prine (iai0y) 05 sae) itt outpat 2 ntegee) Identity Operators: These operators are used to determine whether two variables point to the same object Jn memory, The Is operator returns True if two variables refer to the same object, while the is not operator returns, ‘Trueif they refer todifferent objects, + 9 [1,2,3:b= a: print(aisb) # Output: True + o=[12, 3] print(a isc) # Output: False + tanot hello" y =x; print(xis not y) # Output False world; print(x is not m) # Output True om d() Function: The Id) function returns the unique identity (memory address) of an object. This Is useful for verifying ‘object identity when using the is ors not operators. Key Points: + Every object in Python has a unique identifier during ite lifetime, which is returned by the id function. + Variables with the same value but different objects will have different IDs[sept t) = used to take tnput trem veer neue (tinea the value £6 2°) fprsntivie enterea value tei" 0) riet (x rant ypetetrtai)) eine (ay Brine yretetoat 09) brane (eypetine 0) Brine (eyretetoat(an)) lar Sat tnpue("Enter whe value 46 32)) iF int, fugue Center the valve t¢ 6) brane ("asaeion of entered value", 348) leiatea = Sop ("Eater the value 6f iF input Penton the ae t¢°b™) [rane (Ceadtion or encores va User Input and Type Conversion in Python User input :n Python, the input() function takes input from the user, returning it asa string regardless of the data type. The entered value is stored in a variable for further use, ‘Type Conversion: Type conversion in Python is the process of changing one data type to another, enabling operations ‘across different types. Functions ike sr() Int(), and flost() facilitate this conversion. ‘input() = used to take input from user a= Input("Enter the value Ifa print("The entered value isa) x= 122092839 print(x) print(typo(str(x)) 2 =12.2092839 print(a) print(typetfiost(a))) d=1220 printia) print(typetine(s)))(AE = Lf perticular condtional, 19 true then return if block: feode to execute / if block condition''* Ae to: ‘print ("a is greater than 10") se be Print ("a is greater than b") Understanding if Statements syntax: ‘tif condition true, then if block willbe executed Ft condition: 4# code to execute if block condition arto: print('a word = "Python ‘greater than 10") I word == "Python": print(“This is Python programming”)1113e condition {a true then Sf block will be executed Otherwise else block will be executed ** 1 Gf condition 4€ block code flee condition: lee block code *** sears print (‘a ie greater than bt) oleet print("b is greater than a) Introduction to if-else Statement ifcolze statement: Executes one block of code ifthe ‘condition ie true, and another block ifthe condition istalee ‘syntax itcondition Bifblock code lee: ‘else block code a= 720 Customer's eredit score b=550 # Minimum required credit score for loan approval tas: print(‘Loan approved") loa: print("Loan denied. Your credit score 00 0")Example of if else # Taking input from the user number = int (input ("Enter a number: ")) # checking i£ the munber is even of od is‘mmber’s2 == PrIne(* (number) is an even nunber.") etset print (*(nunber) is an odd number.) Lon ea -n ‘Drine(*ou do not qualify for 2 senior citizen discount." ‘Checking Even or Odd Number In this example, we take @ number as Input from the User and check if It is even or odd using an if-else statement. The condition number % 2 == 0 is used to determine whether the number is divisible by 2, which ‘means it's even. If the condition is false, the number is F Citizen Discount In this example, we use an if-else statement to check if @ person qualifies for @ senior citizen discount based on their ag4‘han oF equa to 1541 kite ly se the greatest") Prine ("2 Ss the greatest.*) Understanding if-elif-else Statements in Python ‘The if-lifelse statement Is used to check multiple conditions sequentially. It allows you to execute different blocks of code based on which condition is true first. If 8 Condition evaluates to True, the corresponding block of code is executed, and the rest of the conditions are skipped. if none of the conditions are met, the code in the else block (if provided) is executed. citizen") lf age > 18: prine( “Adult but not @ Senior Citizen") print("Minor") (output) (*Adult but not a Senior citizenExmple of if, else, elif # User inputs [purchase _anount = float (input ("Enter the total purchase amount: ")) membership status = input ("Are you a menber? (yes/no): ").1ower() # Discount logic if menbership_status = yess print ("You qualify fora 20% discount!) elset print ("You qualify for a 108 discount!) ‘elif purchase amount > 200: Print ("You qualify for a 18% discount Jers Print ("No discount available Applying Discounts Based on Membership and Purchase Amount This example demonstrates how to use if-else and elif statements to apply different discount rates based on user membership status and the total purchase amount. f the user is @ member, they receive one of two discounts ‘depending on their purchase. f not a member, @ separate dlecount Is applied bbased on the amount spent.Why and When to Use a For Loopin Python +L Set Number of Repetitions: A for loop Is Ideal when you know exactly how many times you ‘want to repeat a task. For example, if you need to calculate percentages for 50 students, a for loop can efficiently run the calculation 50 times without repeating the code manually. 2. Reduces Code Repetition: By using a for loop, you avoid duplicating code. Instead of writing ‘the same block of code over and over again, the loop handles the repetition automatically, ‘making your code cleaner and easier to maintain, For example, calculating the total score of & Ist of students can be done with just a loop, instead of rewriting the logic for each student. ‘3. Works Well with Sequences: For loops are perfect for iterating through collections like lists, ‘strings, or dictionaries. If you have alist of items and need to perform an action on each one, 3 {or loop can easily handle this task. For instance, you can loop through alist of names and print ‘each one, or calculate the sum ofall eloments ina it. ‘4, automates Repeated Tasks: When you nea! to perform a task multiple times, ike processing data from a list or calculating values, a for loop automates this process efficiently. I's ‘especially useful when the number of iterations is known, making tasks lke data analysis or batch processing simple anc fast.|i’ eSat“antanht tase st sap eine (hyo orsng") pein ON 1 ea 4 asi eaeisn Aaah Exploring Python Iteration with for Loops It you want to execute some code without writing it again and ‘again, you can use iterative statements like for oops, ‘Syntax: foriin range(start, end, step): Code tobe executed ‘for loop is used to iterate over a sequence (such as @ range, string, lst, tuple, dletionary, or any other iterabla). allows you to execute @ block of code for each item in the sequence. Unlike a walle loop, where the number of Iterations may not be predetermined, 8 for loop Is typically used when you know the ‘exact number of Iterations or when you want to iterate over ‘each element of acollection directly,days_of week = (Mons + "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", “Sunday"] 4 usst of tasks for each day faske = ("Check emails"; “Team meeting", “Code review", “Client cali", “Weite reports", "Work on project", "Plan next week") 4 veing 2 “for’ Loop with string concatenation to print each day's task Tor UUM range (los ape. of wool) Prine(?0s * + days Se week[2) + °, your task Sor "+ easka[s]) ‘The loop iterates over the days and tasks, printing a task for each day. In this example, a for loop is used to iterate through the days of the waek and print corresponding tasks. We ereate twa liste: one for the days and another for tha tasks. Each task aligns with the same index in both lists, ensuring the correct task Is displayed ‘or each day. The for loop uses the range() function to access both the day and its task, ‘and the print function formats them for easy reading. defined — days of week and tasks. For Loop: erates using range() to access each day, Indexing: Uses Index! to access both the day and the corresponding task ‘String Concatenation: Combines the day and task Into a message. ‘Output: Prints each day with its corresponding taskWhy and When to Use a While Loop in Python, 1. Flexible Iteration: A while loop is useful when you don’t know how many times you need to repeat a task. For example, if you sre tracking your steps to reach a dally gosl, the loop can keep running, asking for input until the goal is. met. The loop stops only when @ specific condition is true, offering flexibility when the number of repetitions Is unknown. 2. Ideal for Conditions that Change: if the task should continue until a certain condition is Satisfied, a while loop works well. For example, in a game, the loop can run until the player aches @ specific score. It gives you eontrol aver when to stop based on dynamic conditions that evolve during execution. 3. Continuous Task Execution: A while loop is perfect when you want a task to continue running {28 long as the condition holds true. For instance, you might keep checking for user input or Updating system until the carract information is entered. The loop can be set to stop once the condition is Fulfilled, automating tasks that would otherwise require manual intervention, 4 Dynamic User-Driven Loops: When your loop depends on user input or real-time data, a while oop provides the fexiblty to continue running until a specific condition is met. This is useful in situations where the number of iterations isn’t predetermined, like repeatedly asking for valid Input until the user provides the correct value.enekite loop {ebsle loop’ also called an indefinite iaep.) imitdaasaation Peint(-wmie toop completed) eat priate tn cope pri) print Gveite Loop completes) Exploring Python Iteration with While Loops “if you want to execute some code repeatedly until a specific condition is met, you can use iterative statements like while loops: ‘Syntax: while condition: "Code to be executed 4 Increment or decrement to avoid infinite loop “if you want to repeat a block of code until a certal condition is true, you can use a while loop. I's useful ‘when you don't know how many times the code needs to| run or when the condition might change as the code runs. The loop keeps executing as long as the condition is true, andit stops when the condition becomes false”# paily step goal daily goal = 10000 ‘stepsieaken = 0 # white loop to track steps while steps_taken 500: # Expensive item detected print ("Order cannot be placed. Item too expensive:", item) break print ("Processing item priced at:", item) else: print ("All items are within the budget. Placing the order.") “How break Interrupts Loops: A Shopping Cart Example" ‘The break statement in Python is used to exit a loop when a specified condition ie ‘met, preventing further iterations. In the example, the cart ist contains item prices, land the program scans each item. if an itam costs more than t500, the program prints a message and stops processing using the break statement. Ifno item exceeds £500, the loop completes, and the else block runs, allowing the order to be placed. ‘This Combination of break and else helps manage scenarios where certain conditions Interrupt the loop, making it @ useful tool for decision-making.fcontinue example cart = [1001,130, 400,478.10, 120, 32, 490, 200, 130,50] for item in cart if item , >=) and equality operators for strings, The comparison is performed based on the _lexicographical {alphabetical order ofthe characters. How It Works: + The *= operator checks for exact equ strings. + Tho operators check the alphabetical order ‘based on the Unicode value of characters. ity between ‘This program accepts user input and gives a clear comparison result.fremoving spaces from the string Removing Spaces from the Strin, string =" python build strong development |" In Python, we can remove spaces from a string using # Removing spaces using rstrip() ie uae three methods: print ("After rstrip():", string.rstrip()) + rstrip(: Removes spaces from the right side of the # Removing spaces using 1strip() fad print ("After Istrip():", string.1strip()) + Istip(): Removes spaces from the left side of the string. # Removing spaces using strip() print ("After strip():", string. strip()) fee Pee string.Ein’), index(), rfind(), rindex() methods x = "We need to purchase this product now. can you buy" 41, Using find() method find por = x.find("produce") Prine(*Using find():", find pos) #2, Using index(), method ty index pos = x-index("product") print {*Uaing index ():*, Index pos) except ValueError: EINE ("Substring not found using index()") 43. Using rfind() method (search from right to Left) Eeind poo = x-rfind(*product") Print (Using Ffind():", FEind pos) #4, Using rindex() method (search from right to left) fey ‘Einde, pos = x-rindex ("product") Print ("Using rindex():", rindex pos) except Valuetrrort Eine ("Substring not found weing index ()") Finding Substrings in Python: We can find the position of a substring In a string using various methods. These methods help in locating the first occurrence of the substring from the forward or backward direction, Methods for Forwar find), indoxt) Methods for Backward Direction: find), rine) Direction:#find() method text = “Learning Python is easy do you know 2 position = text.find("Python") position? = text. £ind("do") print (position,position2) 1.find() method: The find() method returns the index of the first occurrence of the substring. If the substring is not found, it returns -# index() method text = "Learning Python is easy do you know?" try: ‘position! = text.index ("Learning") Print ("Position of "Learning':", positionl) ‘except Valuezrror? print ("*Python' not found using index()") try: ‘position? = text.index ("know") Print ("Position of tknow':", position2) ‘except Valuezrror: print ("know not found using index ()") index() Method ‘The index() method in Python is used to find the position of the first occurrence of a substring in a String. If the substring is found, it returns the index of the first occurrence. If the substring is not found, It raises a Valuetsror syntax: string index(substring)4 r£ind() method text = "Learning Python is easy, and Python ie fume position] = text.rfind ("Python") print (position!) position? = text.rfind("snd") print (position2) positions = text.rfind ("ava") Print (positions) rfind() Method ‘The rfindl) method in Python is used to find the position ‘of the last occurrence of a substring in a string. It works: similar to the find\) method, but it starts s the right end of the string instead of the substring is found, it returns the index of the last leccurrence. fit isnot found, it returns. synta string find(substring)# Using rindex() text = "I eat pizza. Pizza is the beste!" try: last_occurrence = text.rindex("Pizza") print ("position:", last_occurrence) except ValueError: print (""Pizza’ not found in the text.") Findex() Method ‘The rindex() method in Python is similar to the index) ‘method, but it searches for the substring starting from the right end ofthe string (Le. the last occurrence of the substring). If the substring is not found, it raises a Valueerror. Syntax: string find(substring)‘Counting Substring Occurrences in a String You can count how many times a substring appears in a 10)".format(VK)) # Output: "Python" print ("Center aligned: {:*10)".format(VK)) # Output: " Python Case 5: String Formatting with 0 In Python, you can format strings using alignment and padding techniques with the format() method. The 0) placeholder ie used to insert values into string, and alignment can be controlled with the , and * symbols. The ", width=8)) # Output: ####Code Print (template. format ("Hello", fill="!", align=">", width=23)) # output Case 9: Dynamic Formatting In Python, dynamic formatting allows you to adjust width, alignment, and Padding at runtime. Using placeholders like fil, align, and width, you can ‘customize the output. For example, "(fil (align) (width))" lets you set the Padding character, alignment, and width dynamically, making your formatting more flexible and adaptabletase 10: Dynanic Float Template template ~ *{:(£111} (align) (width) . (precision) £)* 9123.46 print (template. format (123.45678, £111=" ", width=10, precision-2)) # output: print (template, format (7.12345, fil1=" widthe12, precision=3)) # output: 78.123 45.6780 print (template. format (45.678, fill~"=", aligne">", widthel0, precision=4)) # output: = print (template. format (9.87654, fill="", aligns"*", width=23, precision-5)) # outputs 9.87654 Case 10: Dynamic Float Template In Python, you can control the precision of floating-point numbers ‘dynamically by using placeholders. By combining fil, align, width, and precision placeholders in a format string, you can adjust the number's

You might also like