PythonVK.notes
PythonVK.notes
=) 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 a10)".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
Unit-1 Introduction To Python, Datatypes, Operators, Conditional StatementsNo ratings yetUnit-1 Introduction To Python, Datatypes, Operators, Conditional Statements24 pages Chapter - 1 - Python Overview and FundamentalsNo ratings yetChapter - 1 - Python Overview and Fundamentals14 pages A Powerpoint Presentation On Python: by Durga Prasad KopanathiNo ratings yetA Powerpoint Presentation On Python: by Durga Prasad Kopanathi33 pages Python Notes Class X Artificial IntellgenceNo ratings yetPython Notes Class X Artificial Intellgence9 pages Object Oriented Programming Using Python: Name:Ankeet Giri Reg No.: 11904096No ratings yetObject Oriented Programming Using Python: Name:Ankeet Giri Reg No.: 1190409620 pages Python Notes Second Semester BVOC Computer ApplicationNo ratings yetPython Notes Second Semester BVOC Computer Application27 pages