[Go to site: main page, start]

0% found this document useful (0 votes)
4 views18 pages

Python

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum in 1991, known for its simplicity and readability. It is widely used in various fields such as web development, AI, data science, and automation, and has a large community and extensive libraries. The document also covers Python's features, advantages, installation process, data types, functions, and control flow statements.

Uploaded by

prabhaskota777
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)
4 views18 pages

Python

Python is a high-level, interpreted, and object-oriented programming language created by Guido van Rossum in 1991, known for its simplicity and readability. It is widely used in various fields such as web development, AI, data science, and automation, and has a large community and extensive libraries. The document also covers Python's features, advantages, installation process, data types, functions, and control flow statements.

Uploaded by

prabhaskota777
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
PYTHON PROGRAMMING 1. Whot is Python? . Python is a high-level, interpreted, and object-oriented programming language. It was created by Guido van Rossum and released in 1991. Python is easy to learn becouse of its simple and readable syntax. It is widely used in Web Development, AI, Data Science, Machine Learning, Cyber Security, Automation, Cloud Computing and Software Development. \ 2. Why- Python ? Easy to learn and write. Simple and readable syntax. Free and Open Source. Large community support. Huge collection of libraries. Platform independent. Supports Object-Oriented Programming. Used by top companies like Google, Netflix, Microsoft, Instagram, Spotify. Page 4 _ PYTHON PROGRAMMING 3. Feotures of Python Feature Description Python has simple and readable syntax which is easy to learn. Easy Syntax Python is an interpreted language, Interpreted La: pole "983° | so no compilation is required. Object-Oriented It supports OOP concepts like clase, objects, inheritance, etc Python is a high-level language, High-Level. Lo ee NEG | close to human language. Python is free to use and open source. Open Source Python is platform independent Tk runs on Windows, Linux and Mac. Portable Python has a large collection of Se ee etry ede elidees Sol Uiertes Variables are not required to declare Dynaiest T oa the data type explicitly. E Audemalc Memory Naragenet| Python has garbage collection to manage memory automatically 4. Applications of Python + Web Development. * Automation / Scripting * Artificial Intelligence (AI) + Data Analysis + Machine Learning * Game Development * Data Science + Desktop Applications + Cyber Security * Cloud Computing Ethical Hacking Quick Note : — Python = Simple + Powerful + Versatile * { PYTHON PROGRAMMING 5. History of Python + Python was created by Guido van Rossum. + He started working on Python in December 1989. + The first version, Python 0.9.0, was released in February 1994. + Python 2.0 was released in 2000 with many new features. + Python 3.0 was released in 2008, which is fully new and not backward compatible + Python 3.x is the latest and most used version. Timeline of Python Versions Page 3 Version Release Year Python 0.9.0 1994 Python 1.0 1994 Python 2.0 2000 Python 2.7 2040 Python 3.0 2008 Python 3.x Latest. (Recommended) Creator of Python Guido van Rossum Born : 31 January 1956 (Netherlands) 6. Advantages of Python * Easy to learn and use * Readable and clean syntax. + Large community and support. * Many built-in libraries and modules * Platform independent + High-Level language. + Supports multiple programming paradigms Python is a great choice for beginners as well as professionals. * Increases productivity and reduces development time. 8. OHO Pw RE PYTHON PROGRAMMING 4. Installation of Python Go. to [Link] «Click onthe. “Downloads” menu. Download the latest version of Python. Run the installer file. Important: Check the option “Add Python to PATH”. typing: python. =-version . Click on “Install Now” and wait for installation. . Click on “Close” after successful installation. . Verify installation by opening Command Prompt and — > It will show the installed Python version. Python IDEs (Integrated Develo ) ent Environment, Page 4 IDLE ~ Default IDE with Python installation. Simple and easy to use. PyCharm. ~ Powerful IDE with many advanced features. VS Code ~ Lightweight and supports many extensions . Tupyter Notebook- Used for data science and machine learning. Spyder = Good IDE for scientific programming. 2. Steps: elie Open ang IDE (IDLE / VS Code / PyCharm) Create a new file with .py extension (example: hello py) |. Write your Python code. . Save the file. . Run the program 9. Writing and Running Python Program Example: # This is a simple Python print (“Hello, World! ") name = “Monika” print (“Weleome,”, name) Outputs Python is a case-sensitive language. Hello, World | Welcome, Monika. “Python”, “python” and “PYTHON” are different program PYTHON PROGRAMMING 10. Variables in Python +A variable is a container used to store data values. ‘+ In Python, we de not need to declare the type of variable. Tt is automatically taken care by Python. + The value of a variable can © Variable name must start with a letter (a-z, A-Z) or underscore (_). bbe changed during program execution. + Variable name cannot start with a number. + No special characters allowed except underscore (.) + Python is case-sensitive (age, Age and AGE are different) Example : Velid Variable Names Tnvelid Voriable Names X + namet23 + Name + aget + totalMarks © Aname (starts with number) * name@123 (special character) fotal-marks (hyphen not allowed) my name (space not allowed) fage (special character) 11. Declaring and Assigning Variables Page Rales for Variable Names 1. Must stort with o letter or underscore (_) 2. Con contain letters, digits ard underscore only 3. Connet stort with a namber 4 No special characters allowed Cexcept -) 5. Cose-sensitive + Th Python, we can declare a voriable and assign a value in one line Example x = 40 # integer variable name + “Monika” # string voriable pis 3th # float variable is-student = True # boolean variable 12. Mul Assignment. © We can assign values to multiple variables in a single Line Examples : 1% Quick Note We do net use any keyword. like int, float, etc. to declare @ variable in Python. 1. Assigning same value atbecs5 #555 print(a, b, ¢) 2. Assigning different values x. yet = 10, 20, 30 printle, yz) # 10 20 30 3. Using multiple assignment iq * 100, 200 print(p) # 100 print(q)# 200 % Variables make our programs flexible and reusable. * PYTHON PROGRAMMING 13. Data Types in Python * Dota types specify the type of value a variable can hold. Page 6 * Python has the following built-in data types. Data Type Description Example Type | int Integer (whole number) 410, -5, 0, 100 int + | Float Floating point number 3.44, -0.04, 2.0 Float i [se String (sequence of characters) | ‘Hello’, “Python” str | [boot Boolean value (True / False) True, False bool 1 list Ordered collection (mutable) sane list 1 tuple Ordered collection (immutable) Gy 2,3; 1A) tuple | set Unordered collection of unique items iy ap3¥ set dict Key-valiue pair collection {iname’:'Monika’, ‘age':21} | — diet Example : i] a= 10 # int 1 e+ (1, 2, 3) lick i b= 3.14 # Float fa Gt vares) # tuple 1 c= “Monika” — # str | g= {4, 2, 3} # set | d= Tre # bool | = {'name’:"Monika’,‘age':21} # dict | z 14. Type Conversion in Python | ¢ We can convert one data type into another data type | = Ths process ts called Type caning, Common Type Conversions : ‘Gorrron, “Type Conversions £ — Function Description Example as5 int) Converts to integer | int (3.44) —> 3 Fiscl() mu |lcagectatar tine float (10) —> 10.0 Baap lost se Az str() | Converts to string | str(100) —> ‘00° ete eto) aS Beek) lll Covverds- 15. becleny Wl | [etssU 0) nes uralee tis beh (=) True PYTHON PROGRAMMING et 45. Operators in Python + Operators are used to perform eperations on variables and volues. © Python supports the fellowing types of operators Type Operators Deseription Arithmetic | +, -, #,/, %, //, ** | Performs mathematical operations Comparison | =, I, >, €, >=, Compares tue valu nites [ny tn | Assigns vlues to variables Logical and, or, net Combines conditional statements Bitwise BLA, =, ce, >> | Perform bit-lenl. operations || ee fe | hehe alee wpe | | tad isa tet Chas Wadi of algets J} Exenele || .- 49, b-3 laerueta # Bidaise atbe 3 # Arithmetic ! “on” in “python” —> True # Membership o> bk + Tee # Comparicen | wis b > False # Ldentity ats 5 4 a=15 Assignment | ais not b > True + [entity | | a> Sand b<10 + True # Logical | 16. Control Flow Statements © Control flow statements are used to control the execution of a program. © Python has the folleuing contrel flow statements Control Flow Statements 1 I t i Iteration 9 (Looping) or if | [ifeelae | [iF-elif-elee] [for loop | [while loop break | [continue] [pase Example : | [2 statement 2. for lovp 3, dale tp tea x= 10 for i in range(t, 4): ei ore fx >: print (i) ret) 4 Output: print("x is greater than 5")| | # Output: 1 2 3 tag 123 | } | PYTHON PROGRAMMING Fess 8 17. Functions in Python © A function is a block of code that performs a specific task Tt helps to reuse code ond make programs more modular def function_name (parameters): def ae b): , # code to be executed Ne bce lice result = add(5, 3) print (result) # Output: 8 18. Types of Functions Type Description Example Built-in Function Predefined functions in Python. | print(), type(), len(), input() User-defined Function | Functions created by the user. | def my—func(): ... esas Pens Functions without a nome 5 Anerymows Function | F ecg qi lambda x: x # x 19. Modules in Python © A module is a file containing Python code (functions, variables, classes, etc.) © It helps to organize code in separate files and reuse it Example : 1. Create a file named mymodule py 2. Write some functions in it 3. Import the module in ancther program using import. 20. Comments in Python © Comments are used to explain the code, # Tr mymedule. py def greet (name): return “Hello, " + name # Th another file import mymedule print (mymedule. greet ("Monika”)) # Output: Hello, Monika, + Python supports single-line and multi-line comments. Single-line Comment Multi-line Comment # This is a single-line comment ww This is a eae as multi-line comment "** print(*Hello") # This prints Hello print (* *) ( g Fanctions, modules and comments make the code orgenized, * i readable and easy to maintain. ' | PYTHON PROGRAMMING ey 19. Tuples in Python 1 tuple isan ordered, immutable collection of hems. © Teplas are. written sning porenthens {). 5 | = ee a Date + = (0, 20, 39, 20) eek) | Miners memtar of eters) | nt} z priok(t count (20)) #2 ; ea Thala afi prink(t indes(30)) #2 indent a C0) | ecarener of « eee — 2 prick (Lan ()) a4 ent) | Returna lanth of ple lent) + ie lea pee ear antl) » pedicnin) ae Te ee want) 0 20. Sets in Python J sa a ser wl allt of ene“ + Sets do nok alls dapliate alate y Method Denigtin a 0 [ee tang [tea reveals) [Bem domed fan or fn rd {1 3) waaits) #1234) shams) | Rens din « Ou ww fk poo) a ermen(2) 811, 3.9) ro enclose Te sy || sdmeats) 811,34) eetsape HV ees (ramon) pene) 4 ramaining ot | seer) |e Sets one useful whe you need only unique items and fast 21. Dictionaries in Python A ilies elites oP Negrin . + Detirin we mabe and card Cae fg 3.7 iene ‘age’ BS, ‘elly!="Tedae!) peak. getttmame'D) Mike peak ([Link]}) 8 ek bes) ghee ee Se Ser tnt) |B | pettdcctont)) Eek 3) sscay> | eareeteymih pee | aimee dat std. tema) eh sama .1) ae 0 | Rog cogs tame | fapacrag 260) PRE | pl ty aw | Sete | eed Sw peta yet da opting) | Renrar by nd nto pop") “ate pend pop Cel’) Tere prpilont) | Mansa lat inurta and. papiten() | Cage ah Eee) eee) ' renie + cree 0 fee fae lo aa toa) [tee ie doe Pint 3 = pe ae | se Tuples cre immutable, Sele contain unique items and Dictionaries store 1) ALL three are importank data structures in Python PYTHON PROGRAMMING *s* | 23. Functions in Python || © A function is a block of code that performs a specific task. Z 1+ Ik improves code reusability, readability and reduces repetition, s | + Functions are defined using the def keyword. def function_name( parameters) statement(s) return value # (optional) | | Types_of Functions 4. Built-in Functions > Provided by Python. 2. User-defined Functions —+ Created by the programmer. 3. Anonymous (Lambda) Functions —+ Small, unnamed functions. coors Type Example Code Description Output A. Built-in print (len( "Python" )) len() returns length 6 Function print(max(10, 20, 5)) mox() returns largest velue 20 def add(a, b): User-defined function 2. Meda sum = a+b that adds two numbers. 12 | Becton return sum | print(add(5, 7)) (| 3. Lambda. square = lambda x: x © x | Lambda function to a | Function print (square(6)) calculate square | Function with Different Types of Arguments Explanation Esarple Progra: 1. Poikoul Arguments | def adda, 6) lute ove paved vcore ribo + & pole! wie lef multiplyCa, b) ats, 7) return a # b 2 Kaperd Agneta | east + 7, a 3) ilans we passed wing | ferent names yee 3% Deak nets | ee gets» Gast): | Km le pnt | | y 5 PRCcHats sane) | Sete, el | weet) result. + mutiply(x, y) |] vette tenn arguments | def total Conambers): | Com amept ang mamber of | | print ("Result =", result) | po |e ees [sou Gael | print(estalt, 2, 2, 49) Mista PYTHON PROGRAMMING = xu 24. Modules in Python ice aa eeenaaaE ea te ere HES ee eee File math [Link] (Madule) A. Create «Python file | Eaample: [Link] dat atta, 8) with py extension. | (This is a module file) ita wt = we fats, | agen pote emma | | oe les or variables | cits the fla, gee im that file = tee 3, Import the module | Syptan: import medule_name Files main. py (Using Mode) tm enother program | oy from module name import name | | ingot math utile — & importing mode ting import. result © moth uils-adld(S, 7) resalt2. = math_utils square) 4. Une the fnetione | the with woe same fnctin named) | | i addtin «", rant) | at eet, print Square =", rent?) eee resi print ("Malue of FE =*, math til FL) Built-in Modules (Some Common Examples) Soest: Medal Deseriptisn ‘Adttion + 32 “math | Provides rutherntical functions and constant Square = 6 eed for quencing random amber olan of PL = 3.8416 Uatetinn | Pvides aver for maniplting dala ond tne a Ponies inte. neat with te epwling wlan =e Troviden wun ty tm wralin dw rata by bn Importing Modules - Different Ways ‘Syntax | ‘Explanation leper elecrers. Tepes Hn olen ble th ole from madulename impart name a ee ee eee A [get at hace Faw cals be ame | Tapes mek with w aherter olin | an alias: Freon. A, Using math module 2 ning random module 3. Using datetione module Nec eee SS aio) was tan © random rendioh (A, 10) ma a ae A" Currant date ond thew") fans emt pre PEC Reade mies med | oo print ("Aron of circle =", area) | | tet: Dat: Carver do an en fof cra» [Link] | | San mer 7 (up may sry) || aOnN-oseu8 fe-36 2212556 _ Modules make your programs wall - pend anny to walntain. Mik oe sakes We Cae ea bl Oe ea ae PYTHON PROGRAMMING = ®&«# 2. in. 5A pokage so collection of module, # Peckages help in organising related modules in a drectary hiarercy Packages are importad att like modules, Creaking and Using Packages Sap Explanation Cea enter package mama) | Exner! (Te lr page) 2. Ad inti e ak Dal Plt thal. is direclry i rly. ae 3 Aa meds (py Flas) inside | Examples mypacinge/ nym the phage . tmpert ond ne | Span: from pestagesnone pet males the madales, = Mmprodile addC0, 209) 4 30 at ecg nitaiaauateepaascass|| | Sutpet: Hells, Maniha! a0 26. File Handling in ‘= Fle handling lima ut te ceante, read, write, update and dalvie files ‘Camano Fils: Meliods + Pgthon provides bullt-in fuetions te work with files [real Renda ls Opening = File eatin) Rand fit» arate : T 2 ondline) Bn ome int enlist) Baad lh Gus at ak state) We sing te fle seitalin ist) Wie Uk fas tose) Sau tha fle Hint la por te pti, Aaurn care fle per Gon fe my (hen maT Coser fe py a et Tren the file 1. iling tole 4 Reading Lina by ea fo pent date tat", “HD fap) erie “lin Python ta" for Une in f arta “ile being ng" | | print conten) Fecenet Ft ing rip DY f cone) Fidocal sce focosat) ‘at in daa. tt: Oetpat, Walle Ryton! Hallo Python! Halle Python! fy ea hs PYTHON PROGRAMMING = &# 2, Ereaption Handing in Python + Encnpllone are serena that scour during program. execution ie Eitplin, Kavli, pei ipiny th cd. lees ear. fib ‘se use boy, sumaph, aloe, nally locks Common Exceptions ta Pylhon 1 1 |2== oe as ' TeratuaalonErrer | sad whan dn or easly re an mre | tae ! dad hen meet at Weatead of quran | ee TT ae ata = nn mee otra 1 en ' ae caine gem ne base || ] te an at of apap ps | tn ae Se lt | seg I tackier Pteencs Seueee omen 14 etn i posta} 1 feet Gas | eee ere 1+ ec cai |p ea a a tM ta A EE tease! 28. List in Python. |e Lak Conpratnsan paves a cnc ny bt eusta, Lstt Enpmpls (5H fe el mr al han ti ges Basic: Syntax, ‘fs oath fen reltit) of et8e) tem Crm spon, 304") 8 Bed Miiplanton Tala proc Culpa: CEL 230. O28 41 Ob MD cee elma) te 1B Uae in Bilin Farclans ia et ag ele es eetfngelnkie #2) a) aie " 0 Fk ma eg lide aie | seed, bagreta a ee PYTHON PROGRAMMING 30, Map(), Filter() ond Reduce() Those wee bel in Right ardar Patines ‘hag are ured ith iderabe (Lube Uist, tuple te.) and a function |] 9 Thay Rap te etka loan, ark aed alfa anda, Returns Ae faratr Cmap objet) th raelte afler pls fanaion An tarlor (filer objet} sath theme for which fimetion ‘(From fanchela madula) mduin fossa tata] Prinkequaren) ae [4 9, 46, 25) 7 One © Objet tn alan of = alee Syrian Enanglas 1 Wang wp 2 Wig fited? 3 ang race) mee 1 A me Fo et ee bah ered ef et mene 2 (2 7 mn nes mes EoD ef alts 9 sper = aGmaphaqare, meni) | | ane + Ga ita Cea, md rare rink (evens) Sete Baad St. Classes and Objects Python Mp Copies) For akg jet e Chamuan Daly: ln erguraing ade ard slag COP cance somal = rude, mara) |» Pratur ul) errs s | team a ee | oem | pend ‘lane Clasaone Bef abst aef, peranatend ieee eee Sf meted mafia, argent nated bed ne Costing apt jt ep 2 danny Het hj rathed_rama orgurante} 32__Inheritance_in Python a ef dlaping otf) Frok(E’ Rene | faclf save) Peek Age | bald age POAC RL We ath ld) slats PoraniClaee {he Tees comaphe are pref tte in Ff, Practice then all to bald efficent ond rumba prgrene ie et (Eo | A Kay Points aif copromele Oe tere: o_O) ie the comtrucr Metres slave da Maes define babe pA we wake rg, tgs Sade yal-pouonay, © Taran ale mane (GAL na) A hard bldeatnn aed mathe frm mnt cane (pare: ase) (+1, prometen smd resnablty ond mapperte [Link] PYTHON PROGRAMMING = Ps = | 2 Nia and Dewtory Feregerst 1 Pyfhon's ot ale proven fonction te Laaract with the operating pte. © san orale, dilate; name les and dirwaerian ae © tus omg fe apn Wee vet Bio Convnen_ox Module Functions Fett Carr Bestary a ptt) Ut Fn wd flies eit Edn") ee) iti wm ttaet} Ce cern Oe} = pitt) opted Pill teh “Gen dred) | Stain in omni ‘abc i ei | msaseep wince) | [rename act) Rane fl (emo fle poh etd | chain path oir "Meeer™) ercteeeral aap A} | =) | Steen vty sty | sented armies) | | Seon ness sn ranavalpath) Detaten a file renewed Fie tat”) se ee en anon 0 fw ane) |e | wirserntore, st} Gemendareea) |e omeun : S| cones: Canes, nto“ re io Deed cay cea 34. with JSON in 2 SSN Geese pe Be) bagged fom: 2 ee el wd de fo he wd mane [grt fm © hysesta c ten jom male eet tr BG at | 0 Hn ie ante fm “abies (Ryan, “it 7) | pa 1 Coat te ON rng pod = a mpi, tat) runt TSW Sevqi'n", jams) We Ble ji apa ch? te fn a ON ag jem leaded ee sgn Fife on Leaf) nk JED it from fn | 35. Ey in Python, 1 Rela eprom (nga) or pins and tn mah carer eek 6 sige ipl bat ec ele te eh apace Common Ragen Functions ‘a mthgetenteng) | Che fr mth ny bg a eee) | phe Mastering file handling, JEON, and Regular Expressions malas your Python lle powerful | L for real-world epplizations tke automation, date processing and web dawelopment | a, [Ef te mma fr file ae desing mene gma Left agen to cemreh. canal rd maple te, P [Eft pnd ohne stared den ffily | [Zt meget tld sng programing ll PYTHON PROGRAMMING = & 36. tg actly Gis goal Thine Examgla Program Sigs glee cae Si daa wa era 2B hale a femasing, citing od menting dain eed tine efi al pe of eplenin are ake Rng = SERASA18 1.95 28 EN Tony's ate 204-028 mated Bale 25-08-2008 Tate oer 10 day 828-0605 Ape voining oe = TS ASS 38 ALAN ef deste, pepe ere seth PYTHON PROGRAMMING 39. Therators and Generators in Python Se Deshes we ete Mhak alee gow te rae teegh lt te tee, Enangla sng Tater ‘9 Marersars ari: sep, vA eos tibet te ion are 5 My on cerry. oad wend far large abn. Sasi Darators probit) A SS | cen oe ae ost Kneifial) et aks | anes tna}. || Deter — ke 0 ad ot by as tag at) = — = oe : prin Gantt | ert) Rearea ov sarte st, | etnplint 1: ae darn nt mn fm | ty he oe pe an IZ Ses (Singers ns Stirs def sate, 41 8 seer def sul meg) sa a peasy ant: on oer Sate, Meat Ung phage nase from maeahnge ajo mutha, rage Peoteniape aus, 1) Posbaringpe sei alle?)} 8 HELL SA. Unit Testing in St a kang ee pce of tang ibe epee fo pope fh ban a bleh le lad ta Se ety ete at ly aia Eoapla with satan ‘Sample Men Campa g [ie aces af atte, 0. | leeet iets von 6 | ip gs ipa is wat ar om atSampa aan Taran oleae “ef ease) 2 eet, 23, 89 ef mast raf eee anny btw, 32, 22 Tn te Rin tea Som bk fle PYTHON PROGRAMMING = *# 42. Error ing with try... ese, © Gere handing woken wr peg bh a rhs 2 a Re pd oe ed pe pi Sie Se ee pei Saya Barge yy = LULL Eater ain: 7) 1 peait = 107 1 io oeee| iaph. EenapllasTypa os ein aed [8 ee pina © hanan the emvapion prinitlevad inpul! Mensa aniar a mane“) | 4 dee seek Tarabinienbnee LM Finally Hak so eft pa Ss age dias rink Gere divide by seret"? Finnlly naa cha ee 1 preiC-Mendl =", rosa? { Folly print (Enerlion complied *) 4 Tips aie | 1 | nts oty Soren omar a at appease .

You might also like