0% found this document useful (0 votes)
2 views115 pages

Python Notes (1)

The document provides an overview of Python programming, covering topics such as installation, input/output, logical operators, loops, recursion, and object-oriented programming. It emphasizes Python's simplicity, versatility, and wide applicability in various fields like web development, data science, and artificial intelligence. Key features include its readability, large community support, and extensive built-in libraries, making it an ideal choice for beginners and experienced developers alike.
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)
2 views115 pages

Python Notes (1)

The document provides an overview of Python programming, covering topics such as installation, input/output, logical operators, loops, recursion, and object-oriented programming. It emphasizes Python's simplicity, versatility, and wide applicability in various fields like web development, data science, and artificial intelligence. Key features include its readability, large community support, and extensive built-in libraries, making it an ideal choice for beginners and experienced developers alike.
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
Mica a) H e N eee STEP-BY-STEP ree —— ( EASY NOTES SERIES ) —— Seanad ee ad + Installing Python & Setup ALEC ay Se eed tes + Input & Output ( input(). print) Be Sees Se eed + Logical Operators eae) Ue ke “Taking Input ( input() ) Dette) Formatted Output Seed UC Un UA At Ruan Mt Seu ees a eee) rca ee ia Mba) *]) Bem STEP-BY-STEP | | —— { EASY NOTES :SERIES:) —— ae eae + match-case Statement (Python 3.104) LOOPS IN PYTHON eee ere) Bee ee ec Sed 7 tring Formatting Fstrings) LISTS IN PYTHON eoneca aCe ae eee ey rece ieh CS aid eer) cS) aaa ene = Mast re ar 4 PYT ia 0] N Peery STEP-BY-STEP ees —— (EASY NOTES SERIES ) —— Ce beer Been eter Sere Rea eo) are eT aaa eee AZ ce Nay Se Say tn} aes ary + Recursion | Reet ar eT a + Reading Files Strong Concepts Today, ae Pa eee ae | + File Modes (, a, rw) | Coo ates 99 Se aed Oe | Suics LO aoe han ae PYTHON SF :) 3) | | ee —— ( EASY NOTES SERIES ) —— Soe terete od 001 OBJECT-ORIENTED PROGRAMMING f i See Ewe cy 5, eee > Se Ree 1G] : GeCurciien 73 betes BUT a NAO te (eid Saeco) Your Future is to Wi @ + Simple Galeulator leet CRia oa » a areaiead a ed aosrererneey PS You're All Set! _ eae) ead Deas Python is not just @ language, it’s a superpower: * Python isa high-level, interpreted, programming language. It is known for its simple syntax and readability. ; thon is a language that helps us Simple Words: }—> 4 eae fp Peo uep tell the computer what to do in a: ED, --- earea © To make i comec laren aie Python was created by to learn and use. Guido van Rossum and. © Te increase developer (AUER © To build code that is QE released in) 1190 ‘readable and maintainable. Ce Key Takeaway: Python's simplicity lets you focus on ‘problems instead of worrying about complex syntax. ony fe PYTHON?~ uss" Accepted! @ Python is loved by developers because it is: Ye Easy) to learn and use ' Saves time and increases (productivity Works on ‘multiple platforms ' Has a huge Gahinity support Used in a wide range of seats { ee? eel | GHD on! Ersish-ike tax | Think of Python as a “Universal Remote”. No need to worry about complex | “es Just like a remote \ controls rules and structures a iB deics (TV, AC, Music System), | WD Focus more on logic and solutions ae) Ge) ie can handle rather than confusing syntax nt tasks Lots of learning resources) available GSAT Date Ss) A One language, ae ot B) eis possibilities! Key Takeaway This is why Python is the Python is (easy to learn, oilérful to use, @ FRED langage to cart and widely used in the ‘real world, gour coding journey! 3. FEATURES OF (tjitons jest 7 (make it a top choice PYTHON © “2; worldwide! Joy eee : Python has simple and Python's syntax is easy to syntax, similar to English. read and write. It focuses Perfect for beginners! on readability. 3. Interpreted quage 4. Platform Independent Python is an interpreted i Write Python code once, and run it anywhere ~ language, which means code Windows, macOS, Linux is executed (RERIGEEGE eal eee (5 tee Set ag) gy (Wel) Python comes with a large Python is used in Web Dev, collection of ‘built-in libraries Data Science, AI, Automation, for almost everything. & EB _— Game Dev and inileK more? 7 Large Cnmaiy Sport (6 pen Ser) Huge developer community means Python is completely open source you'll never be stuck, Get help open source and free to use. Anyone can anytime, anywhere! contribute and improve it! a Did You Kaan? } - (Rey Takeaway | Ye Python's features make coding simpler, faster and more enjoyable. ‘top 3, most popular programming That's why millions of developers languages in the wer choose Python! te Learn Python Today, Build Your Better Tomorrow! * Swipe Next => Python is consistently ranked in the ~~ 4. PYTHON IN Python is REAL WORLD®: ==" Python is used in a wide range of industries | and real-world applications. 1. Web Development (2. Data Science (3. Artificial Intelligence Python powers popular Used for data analysis, Python is the backbone websites like Instagram, visualization, machine | of AL tools like ChatGPT, learning and AL. | Siri, and. self=driving 5. Data Handling 6. Game Development Automate boring and Python helps in collecting, Used in game engines repetitive tasks to save cleaning, storing and | like Panda3D, Build your time and effort managing large data. oun games with Python! Real Example: Netflix Recommendation System } {More Examples | © (GaiGle uses Python for Search & YoiTibe N = ea Y = © WASA uses Python for Space Research NETFLIX Colac guar Aralyees your Recnmandh © (Dropbox uses Python for Backend atch hilory preferences shows /movies = uses Python for Recommendations sing Python you'll love! Ose Lea Aithn Toda, o + GG AETRRE RT Build the World of “Temorris! 5. PYTHON EXAMPLE Best way to), understand Python? Task: Write a Python program to (great) the user with their ‘name, @ Python asks) the user for their name name = input ("What is your name? “) @ The wee ae print("Hello, " + name +"! Welcome to Python! @ Python prints a personalized greeting message. {iy Just aa) teiyof tsaa) What is your name? Rohan can do something useful. Hello, Rohan! Welcome to Python! © Python makes coding simple, fun and practical. You can build ‘real-world applications Forms & + Login User n Surveys & Registration sess fe erica Keep Practicing, Python + Your Ideas Keep Building, Keep Growing! ¥y Swipe Next —> 6. KEY TAKEAWAY & Python is simple, eS powerful and SUMMARY: | S22: Perfect choice to ae es start your coding 5 2 3 | journey! _... {What We Learned Today }=__ |“! ©@ Python is a high-level, @ It is powerful, versatile “interpreted programmi and works on ‘multiple language. platforms © Huge ‘community support and tons of resources available. aly © With Python, the possibilities are Keep Going! Consistency today, Mastery tomorrow. Practice. Learn Build. Repeat. You've got this! ~-—-Found this helpful? Python is not just a programming language, A Q it's a tool to turn your ideas into ‘Reality Ye LIKE SHARE SAVE FOLLOW for more such notes! Keep Learning. Keep Building. Keep Growing! VARIABLES & on DATA TYPES (rite x=sy Let's create a variable and store A variable is a container that stores data = some data in it. values. You can use the data stored in variables throughout your program. Se ae ae Rohan # string # integer height = 5.7 # float is_student = True # boolean Name: Rohan Age: 20 : a Height: 5.7 stored differ ‘ Student: True tes of dated Python has several built-in data types. Here are the most common ones: (@ String (et) _] | (@ Integer (int) | [@ Float (float)| | (@) Boolean (boot) | | (G) bist (ist) Text data. enclosed Uahole numbers ‘Decimal numbers |' | Represents one of | | | Ordered. collection in single, double (positive, negative (numbers ith fo values: “Thue of tems. Can store or triple quotes or zero) decimal point). || or Fale different types Example: Example: Evan Example Example (map = ato) yon )| | | [eount = a2 (ots samass || | (Gcactnerernraey) | | | (Gem = per) @ 123 3.14 | BB Ww Key Takeaway ( {Pro Tip @: (77 {Real Life Analogy: 2 Variables store data ie RGAID veil | Think of variables as labeled bores Python has diferent dave types ie \ in a room. Eack bow (variable) has © Choosing the right data type makes your code efficient and ervar-free. (Pune J sie sve Q muon | Se Te PYTHON a ae DATA TYPES* @3332:5) Data types tell Python what kind of value a Wariable is holding 3._ str (String) 4. bool (Boolean) Sequence of characters | Represents one of two enclosed in quotes. Numbers with decimal Used for tet, names, messages, words, ete ' 1 earl ' ' 2. TYPE NONE None represents the absence of @ value data type to each value Te means “nothing” or you store in @ variable. no value” 3. QUICK SUMMARY Data Type | What it holds Use in Real Life Rasidig dite Yipes int Whale numbers 3 Counting, nding, gt, done pieced es float | Decimal munbers x= 3.14 | Price, height, temperature we [tegen | ae [aio magna bool True or False x= True | Conditions, checks, logic NoneType | No value at all x= None | Empty value, default value pt ep a Se Strong (HEEB today, powerful code tomorrow! yp Swipe Next —> TYPE CHECKING Pifhon has 0 bltcin | ease “nt'> | a age _y [ope ( celass ‘int'> print (eype(y)) cele “fost | || seine eypetey) clas float’ print (type(b)) class ‘str'> ins =tikaat 5, { Oo 1 print type(c)) Sun iees ee print (type(d)) | print(type(name)) print (type(e)) y | print (x == y) ® Using string in nes print(x * 2) if = str(x) iw te) } Ly = into |_,f Dee bias” $4 * tate) | Ueintg” J] re a - i + cect Outputs 123 Opt: 3.14) ry Output 7) © {5 KEY TAKEAWAYS ----- $e 0 ani rta w tye asics 1 Coe et | Master the basis today, @ Some van, diffrent tpn + fret thavir. | @ Cormct data types = erie programs! | | Build the future @ Use type) to check and avid mistakes. — | | tomorrow! oy CALETA IIIIIAT D vite sf tis helped! |Z shart with gour friends! | [save for tater! | By ils for more such notes! PYTHON BASICS < VARIABLES & DATA TYPES quick summary = @ +A variable is a container Python has different data types: [int [whale numbers | x = 10 float | Decimal numbers | x = 3.14 [ie Grete | | gets) =. alae tts ures salle type(3.14) > ties type(True) (4 REAL-WORLD USAGE & ConveRsTONS | ___-[ 5. COMMON MISTAKES (avonD THESE) A Real-World Usage | @ Type Conersion @® Mitte 1: 10" + 20" — Store Information | int(*0") #10 Adding strings lads to eonctenation; Output: "1020" ames, age, pres, e | font "3.14%) # 3.18 ot addition! Net 30!) Aepliations | secs) a o99" Hiels 2° oF aD an cetats, gs, tang} (7.89) #7 (decimal eeigiad "10" == 10 Data Analysis part cemoved) are aad nl a pe Comparing thom seve ED pares, Cone tapes han rnd edo eens Pe teed Sip "10" (string) #10 (integer) OY | KEEP PRACTICING! | @g tite sou tered sonathing @ has ‘date, different. values t Se Ss ee ent || cy ay, as tk (cose Sev © Cart pr nh nnd & | Brighter fate alas! BR Save tis pest for rose! Ab tredineimacesteybeomen bate ‘ & Fellow for more such @ Rr as @ Strong basics —» Strong foundation —» Strong future See you in the next topic! @ What are Operators? ‘p: L Operators are symbols used to perform operations on data. 4X Think of operators like math signs + — x +. c They help Python calculate, compare, and make decisions. Types of Operators —y Example —y @ Arithmetic Operators te Key Takeaway: Operators = Action tools in Python eee RS ¢ e Topic 3) Slide Slide 2/6 AP ax aes Operators ‘Sb Addition ‘Subtraction Maltiplication | Division Floor Division Modulus (Remainder) Exponent | Power) Used in calculations like: © Total bill in. shopping opps © Calculating interest in banks © Scores, distance, salary, and more! a= 10 b=3 print (a print (a print (a print (a print (a print (a print (a 13 7 30 3.3333333333333335 3 Subtraction Multiplication # Division Floor Division Modulus Exponent Arithmetic operators help Python do math for us easily! Slide 3/6 Comparison Operators = = x Comparison operators are used to compare) two They return True or False. gee SYNTAX | Operator | Name & = 100! b=5 Returns True if Ehud te I ahastvoroseual will print (a = | Returns True if as print (a I || Bs | tte te |evahies are aetsqadli| > > print (a t print (a Tras if loft ahi is D> Grester than pw a3 print (a | ue le fre < [twee [Pttinee| acs Greater than or | True i greater or . qual to equal pane Lae acer ee ealiey a? |e. ‘aual’te cna se4 Aly " @ ae al | ---SReWeTAReAWap-——- © Validating age (oge >= 18) Covipartscnoperaturs..halpi Pyitsén ioale: © Sorting data (price > 1000) w decisions by comparing values and Slide 4/¢ 4/6 = qa Operators wey @ [* Logical operators are used to ‘combine conditional statements. ¥| They return True or False. EXAMPLE, = 10 print (a >5 and b<10) # True print(a>5 or b> 10) # True print (not (a > b)) # False print (not (a < b)) # True ® syntax & MEANING Operator | Name | Meaning | Example Returns True (5 > 3 and AND only if both 2<4) | conditions are True True | Returns True (5 >3 or OR if at least one 2>5) | condition is True True | Reverses the result. Returns: not | NOT | fit cmaition | ot (523) | is False, ond False I vice versa. "2 Login systems (username and password) = Access control (user role or permission) Logical operators help Python make smarter Filtering data with multiple conditions Decision making in games and apps conditions. of control flow! @ decisions by combini Slide 5/6 Operators [:¢: Assignment operators are used to assign values to variables. They update the value of a variable. TYPES & SYNTAX Operator Lal's start with x = 10 = 10 +25 Example | Same as Meaning 10 10 Assign value ete 5 | x= +5 | Add and assign ex-3 Subtract and assign x= 2 | x = x #2 [Multiply and assign x/=4 | x= x14 | Dwide and assign Final value of x = 1.0 G | Updating scores in games Adjusting vues in calculations Counting or tracking with increments Financial apps (balance update, interest, ete.) Assignment operators make your code shorter and cleaner by updating variables in one step! | Use smart operators, Write smart code, Become a better developer! } Slide 6/6 es in Python (<>) ws ho @ PE We've covered “4 types) of operators in Python! They help Python perform calculations , comparisons, decisions, and assignments. eR Arithmetic Comparison | { @ Logical [ @& Assignment Operators (e Operators | e Operators | ° Operators For mathematical Foe ‘comparing For ‘combining For assigning, values operations two values: | conditions to variables and True if both ' result Power and assign 1k Mallpteatn | 1 conditions True |] || = Subtract and assign | / Bivision { Goan ! Multiply and assign | 1 t | or True iF at leas [| 7 Divide and assign | Ice: See ei {aru condton Tru |] | Som Modal and assign | ee, eS tht | ite Flow dvi end | | x Exponent | ||| mot Reverses the i SS ' KEY TAKEAWAY XX Arithmetic (Comparison | Logical | Assigneent as7 be3 . ' 1a iani6 © Operators are the building rrint(a > b) | print(a > 5) and (b< 5): printfa +b) | c | printCa) blocks of lagie in Python. hee Output: True | Outputs True udp a Pai aule ah a them! @ if age >= 18: Ql, print (“Eligible”) CFogic 4 opie 4) Slide 1/6 aes Statements 23° Ss > in Python < Control statements decide how your code runs. Think of it Uke traffic signals Q t @ control whether your code should ( stop, go, or choose a path. ! portent Types of Control Statements oes | if ifeelse elif nested if §——_match-case ' — — — (modern Python) age = 18 Used to make decisions in your program. | XX KEY TAKEAWAY: Control Satenents = Decision waking in Python @ } | © opie 4 Chopic # Slide Slide 2/6 Statement f= 18: print ("You are eligible to vote.”) You are >] eligible to Check eligibility (age, marks, etc.) Validate login credentials Allow access te features Make decisions in games/apps NOTE w In Python, indentation (spaces) is mandatory. Without proper indentation, you will get an ercort Slide 3/6 ss SLY The if-else statement is used to choose between two blocks of code. Tf the @6RAHEGR is True, the if block runs. Otherwise, the else block runs. v) x SYNTAX 74x) —— if condition: age = 20 ye | block of code if age >= 18: | else: print ("You are an adult.") | # block of code else: } else part is executed only print(*You are a minor.") | when the condition is False. © Login / authentication ‘ti © Check eligibility Price caleulation (discount or net) Bxecite © Access contra in appe/websites block = a C 9 [if makes a decision, but if-else makes the better decision! ej): YX KEY TAKEAWAY: if-else = Choose the right path when there are two options. Slide 4/6 = aa Statement Se. “ SAv_ The elif (short for “else if") statement lets you @®-> @p: check multiple conditions one by one. @o "ie It runs the block of the first True condition. Or ums S —(evaLE) — | BE) es marks = 72 if marks >= 90: Grade: B 8% # block of code | elif condition2: t # block of code | mated 8) | Because 72 is elif condition3 elif marks >= 75: | between 60 ond 9) # block of code print(*Grade: B") L else: elif marks >= 60: anes print("Grade: C*) Ee g => elif can be used multiple times. else: | Only Sreficgh is f a print("Grade: Fail") || condition’s. block 0 | else is optional will un ° REAL-WORLD USES © Grading systems © Discount based on amount Age category dasitcation ecu @ Aihara ramen go es KEY TAKEAWAY: Use elif to check multiple conditions in order. @D) Slide 5/6 ‘a Statement SLT A nested if means an if statement inside another if (or elie) block so It helps you check conditions within a condition. SYNTAX — EXAMPLE if condition: age = 20 if condition2: | has_id = True # ‘block of code iF age >= 18: = if asi > 4 block of code 4% te) ' sas: Ls aL es | @ ge = 16, has id = True else: { # block of code | print("You need an 1D card") @ ge = 20, has_id = False ® Indentation shows the level | | else: | | ae = 17, he of ‘nesting print("You are not eligible.") ——SFUOWCHART) REAL-WORLD USES 7 YT Proper indentation is + ten ontens very important. © Age verification + Ecmmere cers WP + Aces cnt stems @) YE Too many nesting levels + Gane ens & permis RT a ake os aoaeke ) = — ‘Shy KEY TAKEAWAY: Nested if helps you make deeper and smarter decisions by checking conditions i | Sen ‘match=case Statement 9: Slide 6/6 {BAe The match-case statement is a modern way (introduced in Python 3.10) | to handle ‘multiple Ik is cleaner and easier to read in many situations. conditions. ‘SYNTAX match expression: case valued 4 code block case value2: # code block # default block = case _ is optional and works as default (like else). ‘EXAMPLE - doy = 3 match day: case 1: print (Monday) case tc Tuesday") case ‘rint(*Wednesday") it matches case 3 cose Woop and prints tt Friday") | "Wednesday" “orine(* Weekend”) | \ Ran "PORTANT NOTES © Menu driven programs BE match-case con be more readable than multiple elif Command line ols WE Use case — for default behavior. He Be wrks vith nenber, strings, | end patterns © Routing in applications Som State handing © Persing commands YE KEY TAKEAWAY: Choose the right tool! Use if, if-else, elif for conditions and match-case for cleaner multi-way decisions. — @® LOOPS IN PYTHON WHAT ARE LOOPS? Loops are used to execute a block TYPES OF Loops of code multiple times. 1. for loop They help us [Link] writing 2. while loop the same code again and again. 1. FoR Loop > Used to iterate over a Sequence EXAMPLE : (list, tuple, string, range, etc.) See > The loop runs for each item for i in range(1, 6): in the sequence. print (i) SYNTAX = OvTPUT: 12345 2. WHILE LooP EXAMPLE : > Used when we don't know how ied many times the loop will run. while i <= 5: > The loop runs as long as the condition is True. print (2) beiet SYNTAX = OuTPUT: 12345 FLOW OF Loop Start ‘ KEY PoINTS © Use for loop when you know the number of iterations: i i © Use while leep when the number of iterations is unknown. | ; No i © Use break to terminate the loop early. ! <> End ' 1 1 © Use continue to skip the current iteration. © Use pass as a placeholder (does nothing). Practice more, Code more, Master Loops! iy FOR LOOP Iterate, Automate, Repeat - That's the Power of FOR Loop! WHAT IS FOR LOOP? | A for loop is used to iterate over a | Sequence (like list, tuple, string, range, etc.) | and execute a block of code multiple times. SYNTAX: for variable in sequence: 4 code block TYPES OF FOR LOOP 4. FOR LOOP WITH RANGE() ‘The range() function generates a sequence of numbers. Repeat. with IN PYTHON parpse HOW FOR LOOP WORKS? + The loop takes the first item from the sequence, + Executes the code block + Moves to the next + Continues until all items are processed item. “FLOW OF FOR LOOP 4 oie nn. ————— 2. FOR LOOP WITH LIST erate over each item in a list Example | example: Output: | (Fayuts Sotrapplt Poona, Fmcngary ) Duta for i im range(t, 6) : site = Capps ; ae ol for Fruit in. fruits E 5 || print Frait) world Ue ‘ — Real-world Use a apectfie number of tines. Print al tens in «shopping ist i Example: Printing 4 to 100 mambo. NW [ shopping = Comilk’, “Dread”, “egge'D | foe item tm shopping Yor i im vangeC, S04) inh fone ae print (°Bug', item) 3. FOR LOOP WITH STRING 4, FOR LOOP WITH TUPLE Tterate over each character in a string | Tterate over each item in a tuple Example: Output: | Example output: mame = "Python fro crordinates = (40, 20, 30) pea li deo i for point in coordinates print (ch) t Print Cpoint) Real-world Use $ Realowerld Use: Coot characters, vale f seal for Fed cllctine tie @ en ea edie GPS carina, days oth Tin © tape Ealar @ Gord dags = Con, "Tua", "wed", Tha") for hin wen for day in days print (oh). print (day) 5. FoR LOOP WITH DICTIONARY | Tterate over keys, values or key-value. pais ) Herts ver byt shadent = (‘name's Ram, “age™= 20} ‘output: eee is print Chay) Use (6) Raate over vanes for value in student values() ae print value) 2 Real-world Use Diaplag all deteile of «student record Toe ean eioee a) aon ae eee COMMON USE CASES OF FOR LOOP 6. FOR LOOP WITH SET Tterate over unique items in a set (order is nat guarentend) Example: output: numbers = (3, bs 4, BY poem for mim in pumbeos 1 Print Gnum) 2 =f E x Real-world Use 4 reetaeorite al ements eerie 7. NESTED FOR LooP A for loop inside anather for loop output: Example Yor 1 tm vangety 8 ta) 42) a3 Feat rage 42 fa 33 printcry 3) 21032 38 ea world Use Vee in patterns, matrier, tables, gomes, ae We Master the for Loop, and you can automate almest anything in Python! ly | WHILE LOOP IN PYTHON |: seas. Execute Keep Going Until the Condition is No Longer True! Repeat. WHAT IS WHILE LOOP? HOW WHILE LOOP WORKS: A while loop is used to execute a block of code * First, the condition is checked. + Tf True, the cade block is executed. * After execution, the condition is checked again 4 This continues until the condition becomes False. ~ FLOW OF WHILE LOOP ~ ‘as long as a given condition is True. The loop stops when the condition becomes False. SYNTAX ‘Start |—> Yes (True) i KEY POINTS © The condition is checked before executing the code block. EXAMPLE ourPuT bea 1 mS ; 1 Tf the condition is False at the beginning, the loop print(i) i will not run even once pred 5 © Make sure to update the variable inside the loop, otherwise it may cause an infinite loop Explanation: i starts from 4 and the loop rans © Use break to exit the loop early. fas long os £ <5 Use continue to skip the current iteration. # While loop is useful when we don't row how many Himes the loop will run COMMON USE CASES OF WHILE LOOP @ counting uwTi. A conorrton © REVERSE A NUMBER Feigad Pr mache fret 030 zane: Reran the dgjts of « nanber ame = 12345 bea while i <= 10: Setpets rev = 0 ee spe cre ba © sum oF N NATURAL NUMBERS print ("Reverse =', rev) ieaieu bah dant row Example: Sum ef first m natural numbers. original, number. © menu pRIveN PRoGRAM PATER HER YI total = 0 shila 2

You might also like