PythonVK.notes
PythonVK.notes
=) r= 17; 8 «17; print{r>= 8) # Output: True bes + Loss than or equal to ( 10:4 2; print(t <= u) # Output: True print (a==b) 20 beso print (a!=b)Hogical operators in Fython fogical AND (and) xe7 print (x < 5 and x < 10)#Both conditions are not true Foutpae® False Mogical OR (or) yn3 Brint ty < § or y > 10)¢At least one condition is tre Woutpue: true # Logical Nor (not) aos Brint (not (2 < 10)) # Reverses the condition’s truth value F output: False Logical Operators: Logical operators are used to combine conditional etatements, allowing for more complex and flexible conditions in your programs. Python has three main logical operators: AND, OR, and Nor. + Logical AND (and) : The and operator returns True if ‘both conditions are Trus. Otherwise, Itreturns False. + Logical oR (or): The or operator returns True if at least one of the conditions Is True. it only returns Falge if both conditions are False + Logical NOT (not): The not operator Is a unary ‘operator that reverses the truth value of a condition. It returns True if the condition Is False, and False if the condition ie Tue,{assignment operator fpeiae” (a) an eine cae rine ‘aniso aime pein) prince fate pelnetey ipetiz0 Print ani20 [Feinecay Assignment Operators: Used to assign values to variables. Assignment (=) x 10; print(x) # Output: 10 Add and Assign ( Subtract and Assign (~ Multiply and Assign ( 0 mem ry += 3: print(y) # Output: 8 s print(a) # Output:6 2: print(m) # Output: 12 Divide and Assign (/=) p= 20; p /= 4s print(p) # Output 5.0 Modulus and Assign (%=) t= 10; Exponentiation and Assign (=)** v= 2: Floor 0 fon and Assign ( print(t) # Output: print(y) # Output: 8 ie = 4: print) # Output: &What is Binary? Binary is a numeral system that uses only two digits: O and 1. This system is fundamental to computers, as all data ie ultimately represented in binary form. Each digit represents @ place value, with the rightmost digit being the least significant. The values increate baead on theit position, commonly reprasanted ae Powers of twor0,1,2, 4,8, 16,32, and 64. This makes binary essential for digital electronics and computing. How Binary is Calculated Binary digits (bits):In the binary number system, we only use two digits: O and 1, These are called bits. Place value: Just like in our usual decimal system (base 10), where each digit has a place value (lie ones, ‘tens, hundreds), binary digits have place values too, but they increase by powers of 2 instead of 10. Here's how it works: + The rightmost digit represents 240 (which equal). + The next digit to the left represents 2" (which equals 2), + Then 22 (which equals 4), and so on.How to Read Binary Numbers: To understand a binary number, we look at each alg and calculate its place value. For example, the binary number 101s calculated like this: The rightmost is in the 270 place, soit equals 1* 240 The next 1isin the 2" place, soit equals 1* 2" = 2. The next Ois in the 2°2 place, sot equals 0 *2°2 =o. The leftmost tis in the 2% place, soit equals 1* 2" ‘Adding Up the Values: Now, add up the values of each place: 8+0+2+1=11(in decimal) So, the binary number 101 is equal to1! in the decimal system. Example Calculation: Converting 1011 (Binary) to Decimal Let's break down the number 1ottin binary: tats oxo Letnd erat Now add those lus ogetier ssop2e 11 (Decimal)Bitwise Operators: Bitwise operators operate on the binary representations of integers, manipulating individual bits to perform specific tasks. These operators are mainly used with Integers and can also work with booleans (True = 1, Falee = 0). They are useful for low-level data manipulation, encryption, network ‘operations, and hardware programming where direct bit management is needed. These operations allow ffficient handling of data at the bit level, enabling tasks like performance optimization and complex ‘caloulations, Understanding bitwise operations is essential for working with certain algorithms and eystem- level programming. Operators Description a Performs a bitwise AND operation, resulting in only i both corresponding bits are 1. ort) Performs a bitwise OR operation, resulting in if t least one corresponding biti 1. xOR(*) Performs a bitwise XOR operation, resulting in 1when the corresponding bits are different. NOT (-) operator inverts al the bits of anumber, changing s to Os and 0s to 1s. Loftshift (<<) Shifts bts to the left, effectively multiplying the number by powers of 2. Right Shift (>) 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 print(x) #output print (x_result) 4 foutput 8 Bitwise Left shift (> 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 < daily. goal: 4 Asking the user for input (how many steps they've taken today) steps_taken = int (input ("Enter the nusber of steps you've taken today: *)) ¢ Checking if the goal is met or not Af steps_taken < daily 9} FINE ("Keep going! You need " + str(daly goal! ~ steps t aken) +" more steps.") a print ("congratulations! You've reached your goal!™) ‘Tracking Your Daily Step Goal with a While Loop, inthis example, wo use a while loop to track your progress toward a dally step goal, similar toa fitness app. The loop will keep asking you to enter the number of steps you've taken until you reach or exceed your goal. This shows how a while oop is useful when you don't know how many times the loop will run, ‘and you want it to continue until a specific condition (Iie meeting your goal) i ulfiled. Key Point: + Purpose: + Condition: The loop runs as long as steps are less than the goal 190 a while loop to track steps until the dally goal is met. + Usor Input The user inputs their steps. + Output: Displays remaining steps or a congratulatory message once the goal s metprised (skip even numbers n the loop MEAL EEL cnsok se ene number 4 ac Be eee Sceiscial Ueibelp' Re Teraelon (oat mamere) snes) Introducing Transfer Statements ‘ranefer statements are used to change the normal flow of execution inside loops or conditionals. They let you control how a program behaves in certain situations. ‘Types of Transfer Statements + breaks Terminates a loop prematurely. + continue: Skips the current iteration of @ loop land moves to the next one, + pass: Does nothing. it's used as a placeholder in situations where code is required, but you don't want to de anything yetfbreak example cart = [100, 30, 400, 478.10, 20, 432, 650,490,200, 100,130) for item in cart if item > 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 < 100: # Skip cheap items print ("This item is too cheap, moving on!") continue Skip the rest of the loop and go to the next item print ("Adding this item to the order, priced at t" + str(item)) else: print ("All items processed successfully! low continue Skips Items: A Shopping Cart Exampl ‘The continue statement in Python skips the current iteration of a loop when condition is met, moving directly to the next item. In this example, the program processes a cart of items with varying prices. If an item is priced below £100, itis ‘considered too cheap, and the continua statement skips it. Items priced t100 or more ided to the order. This ensures that only relevant items are processed, making ‘the loop more efficient by ignoring tems that don't meet the erkeria#Pass example cart = (1001, 130, 400, 478.10, 120, 32, 490, 200, 130, 50] for item in cart: if item < 100: pass # Do nothing and continue to the next item els print ("Adding item priced at @" + str(item)) else: print ("All items processed.") How pass Skips Processing: A Shopping Cart Example ‘The pass statement in Python is used to skip an action in a loop without interrupting its flow. In this example, the program goes through a shopping cart, and if an item costs less than £100, it does nothing and moves to the next item. For items priced £100 or more, it {adds them to the order. Once all items are processed, the else block runs, signaling that ‘the process is complete. This allows cheap items to be ignored while continuing the loop smoothlyCoding Patterns in Python: Enhancing Logical Thinking In Python programming, printing patterns is @ great way to improve your understanding of loops, logic, {and problem-solving skils. By using loops (For, while), conditionals, and simple mathematical operations, ‘you can create various patterns that help visualize how loops work and develop logical thinking Working with patterns strengthens core programming concepts like iteration, nesting, and conditional. In this presentation, we'll explore a variety of patterns, from right-angled triangles and pyramids 10 number sequences snd alphabet patterns. Mastering these patterns will boost your coding efficiency and problem-solving abilities, whether you're new to Python or preparing for coding challenges. ‘Step-by-Step Guide to Printing Patterns in Python Understand the Pattern: Visualize the pattern you want to print, whether it's a pyramid, triangle, or number sequence, Decide Rows and Columns: Determine how many rows and columns your pattern will have. Ths will guide the loop structure. Use an Outer Loop: The outer oop controls the number of rows, For example if you want § roms, the loop will run § times, {Greate an inner Loop: The nner loop controls the printing of symbols or numbers In each row. This loop runs for each row, determining how many characters to print. Print the Pattern: Use print() to dleplay characters (IIke * or numbers). Control spacing between ‘characters using end=" to avoid extra line breaks, ‘Add Line Breaks: After each row is printed, 1 print() to move to the next line,Rows=6 for 4 in range (0,Rows): for p in range (0, itl} print ("*", end: print ("\r") es see + Left-to-Right Pyramid Pattern of Stars This pattern prints @ left-aligned pyramid of stars, with the number of stars increasing in each row, from left to right ‘Step-by-Step Breakdown: “The code starts with one star on the first line, then progressively adde fone more star on each subsequent line, continuing until the sixth line, Which contains six stars. The loop prints stars in increasing numbers for ‘each row, starting from the top and working downwards.Rows = 6 for i in range(1, Rows + 1): print (" tee rs es wo (Rows - i) + "* " * 4) Pyramid Pattern of Stars ‘This pattern creates @ pyramid shape by printing stars in increasing ‘order, aligned to the center. ‘Step-by-Step Breakdown: “The code iterates through each row, adjusting the number of leading ‘spaces to center the stars. In each row, the number of stars increases ‘progressively, starting from one star in the first row and adding one more star In each subsequent row. This continues until the last row, ‘hich has the maximum number of stars.Word = "Python" ba for i in Word: vti print (v) P Py Pyt Pyth Pytho Python Word Pattern in Python This pattern prints each new ine. 1ch lettor of the word "Python" progressively on ‘Step-by-Step Breakdown: “The code loops through each letter in the string ‘Python’, adding each letter to the variable v and printing the updated value after each ‘addition, This process continues for all sx letters in "Python’, showing the string being built step by step.”Rows = 5 for i in range(1, Rows + 1): print(" "* (Rows - i) #"* " * i) Centered Pyramid Pattern of Stars [A pyramid of stars, starting with one star at the top and increasing by fone star per row. all centrally aligned. ‘Step-by-Step Breakdown: ‘The code begins by iterating through the number of rows (5 in this cease). For each row, it first adds spaces to the left to conter-align the stars. Then, it prints the stars, with the number of stars increasing by cone in each row. The pattern starts witht star and continues to Setars in the last row, creating a symmetric pyramid shape.symbol = "#" for i in range(1, rows): tor 3 4m eangeteou, 0, -1)3 Inverted Right-Aligned Pyramid of Symbols Dar *print(” *, end=" ‘This pattern creates a right-aligned pyramid of # symbols, Each row begine els swith spaces for alignment, followed by an increasing number of symbols. int (ayebol, nde princes) ‘Step-by-Step Breakdown: “The code terates through § rowe, starting with one # symbol nthe fst row and adding one more in each subaequent row For each row epoces are printed frat to aig te symbols tothe right The numberof speces ddecresses asthe cow number increases. Ate priating the spaces the tymbol sprinted forthe remaining columns resulting ina right-aligmed Pyramid shape ee ote ote te te ee oe eeemy_pattern: for i in range (0,my_pattern+1) for j in range( my pattern-i,0,-1) : print (j,end=""J print () 87654321 7654321 654321 54321 4321 321 21 1 Decreasing Number Pattern This pattern displays numbers in descending order, starting from a maximum value and decreasing with each row. The total ‘number of rows s defined by my pattern, set to inthis case, ‘Step-by-Step Breakdown: The code works by using two nested loops. The outer loop determines the current row and calculates the starting number ‘for that row, which decreases as the row Index increases. The Inner loop prints numbers in descending order, beginning from ‘the calculated starting number down to 1. Afterall numbers for @ row are printed, the program moves to the next ine, creating the ‘appearance of a pattern, This process repeats until all rows are completed, producing a pyramid-like structure of decreasing numbers.current_num = stop = 2 rows = 5 for 4 in range (rows) for column in range(1, stop) print (current_num, end="' current_nun += 1 print ("*) stop += 2 213 14 15 16 9 20 21 22 23 24 25 Incremental Number Pattern This pattern prints numbers incrementally, with each row Containing more numbers than the previous one. The number of rows is get to Sin this example, ‘Step-by-Step Breakdown: ‘The outer loop controle the number of rows, while the inner loop prints numbers in sequence. For each row, the count of numbers Increases by two, starting with 1 and progressively increasing with each row. The pattern continues until the specified number of rows (S). The numbers start from 1 and are incremented by 1 after each print, creating @ growing sequence. As the rows increase, the total count of printed numbers also grows.Pattern = int (input ("Enter the number of rows: ")) ry hile 4 <= Pattern: bal hile b em 12 print ((L* 2-1), end=" *) biel teed print 0) $999 iu iu aa BUBB is 1s 18 18 18 18 18 a5 Yaa (Odd Number Pattern This pattern prints odd numbers In each row. The odd number Increases with each row, and each row has the odd number repeated multiple times ‘Step-by-Step Breakdown: The program begins by prompting the user for the number of rows. The outer while loop runs for each row, and the inner loop prints the edd number (calculated as i* 2 - 1) the number of ‘imes corresponding to the row number. Each row prints the current odd number in an increasing sequence, starting from t. {As the program progresses, the odd number increases by 2 In ech following rom, creating @ pattern of increasing odd numbers,az 26 fr i in range(d, Az + i): Alphabetical Triangle Pattern Line =" *" ace =) Line f=" * Jotn(ehe (64 + 4) for _ in range(4)) c= This pattern creates 8 pyramid using letters of the alphabet, print (ine) starting with a’ at the top. Each row has an increasing number of repeated letters, with the number of rows set to 26. ‘Step-by-Step Breakdown: The outer loop iterates through the numbers 1 to 26 (representing rows). For each row, it frst adds spaces to the ‘beginning of the line, ensuring the pyramid shape is maintained, Then, it generates a string with the appropriate letter (using cohr(6é + 1), where I is the row number) repeated I times. These SEs, letters are joined with spaces, and the final string Is printed, ener resulting In an alphabetical triangle where the number of repeated letters increases with each row.Ix = 10 for 4 in range (0, x): for p in range (0, i + 1 print ("@", end="") print () for 4 in range (x, 0, ~1): for p in range (0, i = 1 print ("6*, end=" *) print () ‘Symmetrical ‘@' Diamond Pattern ‘This pattern forms a syrnmetrical dlamond shape with “@ symbole, Starting with one symbol, increasing to the middie, and then decreasing back to the base. ‘Step-by-Step Breakdown: ‘The code first prints the upper half of the diamond, where the (@ symbols increase in number from 1 up to the specified “number (10 in this case). For each row, spaces are added on the eft to center-align the ‘@' symbols. After reaching the peak with the maximum number of '@’ symbols, the code then prints the lower half of the diamond, reducing the number of symbole symmetrically, Each row ie carefully aligned to maintain the diamond's symmetry, creating a balanced, visually appealing pattern.was (oer «spe ecco amar wes“ th mene ene) Hollow Hourglass Pattern This pattern creates a hollow hourglass using @ user-defined ‘symbol, with symmetrical upper and lower halves aligned around the center. Step-by-Step Breakdown: ‘The program first prompts the user to enter the number of rows: land a single symbol for the pattern. The upper half of the hourglass is created by iterating through decreasing row sizes, ‘adding spaces for alignment, and printing symbols at the edges: Cf the hourglass. The lower half is generated similarly, starting from the second row to complete the hourglass shape. Both parts use conditional checks to ensure only the edges of the hourglass are Filed, leaving the inside hollow.‘yo = snout "Enter 4 singi chacacter or number to uses “) Picea) print (onnerated Filled Hourglass Pattern ist *) deper-paie LPP Eee 04 ths for Siete soe ie tang te 2 eine egos sie") reset for sietiageleow 28 sor Stooge te 2 abet emia ent) Filled Hourglass Pattern This program generates a filed hourglass shape using a us defined character or number. It consists of an upper half and 2 ower haif, symmetrically arranged around the center. ‘Step-by-Step Breakdown: ‘The program asks for the number of rows and @ symbol, then ‘generates an hourglass shape. The upper half prints symbols continuously, while the hollow version leaves gape inside the ‘shape. The lower half mirrors the upper, with both using spaces: {for alignment. The key difference is that the filled pattern ie solid, with no gape, while the hollow pattern hae epaces inside ‘the shape, only printing symbots on the borders.#syntax: string = ‘string value! string = “string value” # Using single quotes for a string stringl = 'Hello, World!" # Using double quotes for a string string? = "Python is awesome!" Understanding String Data Type in Python In Python, a string is any sequence of characters written inside ther single () or double (*) quotes. This allows you to represent text, characters, and even special symbols as data in your program Note: Unike other programming languages like C, Cr+, or Java, where a single character enclosed in single quotes ie treated ac ‘2 char data type, Python does not have @ separate char data enclosed in single or Is imply a string, not ‘a character.#triple single quotes stringl = '''This is a multi-line string that spans multiple lines print (stringl) # Utriple double quotes string? = "*"Python makes it easy to work with multi-line strings.""" print (string2) Defining Multi-line String Literals in Python In Python, multistine string literals can be defined using tr ‘quotes, ether triple single quotes (") or triple double quotes (9). This allows you to span a string across multiple lines without needing to use escape characters like \n for new lines.#Indexing word = “Python” # Accessing using positive index print (word[0]) print (word[5]) # Accessing using negative index print (word[-2]) print (word[-6]) Accessing Characters of a String in Python: In Python, you can access individual characters of a string Using the following methods 1.Using Indexing 2.Using Slice Operator What is indexing? Indexing refers to the process of accessing Individual flements from @ sequence (such as e string, lst, or tuple) by referring to their position (index) Positive indexing: in positive indexing, the index starts from 0 for the fst element and increments by 1 as you move through the sequence. Here's howit looks with the string “Python” Python 012345 Nogative Indexing: Negative indexing allows you to access floments starting from the end of the sequence. The last tlement of @ sequence has the index -1, the second-to-last tslemant has the index -2, and 20 on, Hare's the reverse view of the string "Python" using negative indices: Python 65-43241+ siice operator ftera'= veython™ #0 doosn's include index 6 bees [Prine fworaloze)) rine fworalas)} + utpute “hon 4 siice from the beginning to index 4 (exciuding 4) Brinchwoed[as4]) # Output? th" 4 sive with step oize (every second character) [Print (word[ss2})) # ostputt "to" 1 sive with nogative indices (starting from the end) [Print (word[-r-i})# Outputs "tho" Accessing Characters Using Slice Operator ‘The slice operator (In Python allows you to access @ range of elements from a sequence such as a string, ist, fr tuple. It Is a powerful way to get a portion of 8 sequence without modifying the original sequence, You ‘can uso the slice operator with both positive and negative indices to extract parts of a sequencé Syntax: sequence [startend:step] ‘start: The index where the slce starts (inclusive). If not specified, it defauits to the beginning, fond: The index where the slice ends (exclusive). Hf not specified, it defaults tothe end, step: The step size (how much to skip between elements). 1fnot specified, it defaults toBehavior of Slice Operator Forward Direction (+ve Step) ++ The slicing moves from aft toright. 1+ The start Index is Inclusive, and the end index Ie exclusive (begin to end-1) “If the end value is 0, the result is empty, because slicing stops before the first character. Backward Direction (-ve Step) + The slicing moves right to lft. "= The start Index is Inclusive, and the end index le Inelusive (begin to end+1 when moving backward). ‘If the end value Is -1, the result is empty, because “slicing stops before the last character.#1. Concatenation (+) strl = “Hello” str2 = “World” result = strl +" "+ str2 print (result) #2. Repetition (*) strl = "Python Master" result = strl * 3 print (result) Mathematical Operators for Strings In Python, you can apply the following mathematical operations tostrings: ‘:Concatenation (+) + The + operator is used to concatenate (join) two strings. + Note: Both operands must be of string type. 2. Repetition (+) + The * operator's used to repeat a string a specified number of times. + Note: One operand must be a string, and the other must be an integer. Important Notes: + Using + with non-string types will result in a Typetrror. + Example:"Hello"+ Swill throw an error. + Using * with non-integer or nen-string types will also raise a Typetrror. + Example:"HI"*"2" wil throw an error.cease) eles ¢alternative solution using for Loop. a= "Python is my first Development language” # Forward Direction print ("Forward Direction for 4 in print (i, end= print () ‘a = "Python is ny first Development language" print (lenta)) Print ("Length of the strings", lenta)) # Backward Direction print ("Backward Direction: : for 4 in a{ti-1): Brine ("Foryard Direction Eos print (a{n], ende'*) Ss! tel} increment the index print 0) print ("Backward Direction") IRei- i Shite a print (afal, end="*) # B= 1 becresent the index print) Using len() function (in-built function ) ‘The len() function in Python returns the number of characters in @ string. It counts all characters, including spaces and punctuation marks.# Check membership a = “python” print("p" in a)# True print("z" in a)# False print ("y" not in a)# False print("z" not in a)# True Checking Membership Using in and not in Operators We can check whether a character of a string ie @ member of another string using the in and not in operators, Explanation: in operator: Returne True if the specified character of ‘tring is found in the target string, not in operator: Returns True if the specified ch: lr tring i not found in the target string.# compare two strings string] = input ("Enter first string string? = input ("Enter second string: Af ateingl == string2: print ("Both strings are equal.") elif stringl < string2: print ("First string is less than second.") else: print ("First string is greater than second.") Comparison of Strings We can use comparison operators («, <=, >, >=) 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 < and > 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 < symbol aligns the string to the left,» aligns it to the right, and * centers the string within a specified width. You can also add padding to adjust the total width of the formatted string.#Case 6: Truncating Strings with Format text = "Programming" print ("Truncated: { print ("Center aligned and truncated: {:*8.5) .5)".format(text)) # Output: Progr + format (text) ) Case 6: Truncating Strings with Format In Python, you can limit the width of strings and truncate longer ones using the format() method. By specifying a number after the period (.) within the curly braces () you can ‘the maximum number of characters that will be displayed. This Is useful when you n ‘show only a portion of a string, especially in cases where space is limited. Additionally, you ‘can combine this with alignment to ensure that the truncated string fits neatly within a ‘specified width#Case 7: Formatting Dictionary Members info = {"name": "Varad", "age": 27} print ("{name} is {age} years old.".format (**info) ) # Output: Varad is 27 years old. Case 7: Formatting Dictionary Members In Python, you can format string values directly from ng the ** unpacking ‘operator Inside the format() method. This automatically replaces placeholders with corresponding dictionary values. For example, using “tino In the format() method unpacks ‘the info dictionary and replaces {name} and (age) with thelr values. This approach is efficient ‘and keeps the code clean, especially when working with structured di# Case 8: Formatting Class Members class Person: name = "Varad" age = 27 p = Person() print("{p.name), Age is: {p.age)".format (p=p)) fOutput=Name: Varad, Age is: 27 Case 8: Formatting Class Members In Python, you can format values stored in object properties using the format() method. By referencing an object's attributes within the format string. you can easly diplay is values, For exemple, in the Person class, the name and age attributes are printed by formatting them through the format() method, making the code clesner and more readablecase 9: Dynamic Formatting template = "{:(fi11} (align) (width))* print (template-format ("Dog", fill="*", align="*", width=10)) # Output: **#Dog+##+ Print (template. format ("Python", fill="=", aligne"<", width=12)) # Output: Python===—== print (template. format "Code", fill="#", align=">", 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
The Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good LifeFrom EverandThe Subtle Art of Not Giving a F*ck: A Counterintuitive Approach to Living a Good Life4/5 (6125) The Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You AreFrom EverandThe Gifts of Imperfection: Let Go of Who You Think You're Supposed to Be and Embrace Who You Are4/5 (1148) Never Split the Difference: Negotiating As If Your Life Depended On ItFrom EverandNever Split the Difference: Negotiating As If Your Life Depended On It4.5/5 (932) Hidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space RaceFrom EverandHidden Figures: The American Dream and the Untold Story of the Black Women Mathematicians Who Helped Win the Space Race4/5 (954) The Hard Thing About Hard Things: Building a Business When There Are No Easy AnswersFrom EverandThe Hard Thing About Hard Things: Building a Business When There Are No Easy Answers4.5/5 (361) The World Is Flat 3.0: A Brief History of the Twenty-first CenturyFrom EverandThe World Is Flat 3.0: A Brief History of the Twenty-first Century3.5/5 (2283) Devil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New AmericaFrom EverandDevil in the Grove: Thurgood Marshall, the Groveland Boys, and the Dawn of a New America4.5/5 (278) A Heartbreaking Work Of Staggering Genius: A Memoir Based on a True StoryFrom EverandA Heartbreaking Work Of Staggering Genius: A Memoir Based on a True Story3.5/5 (692)