0% found this document useful (0 votes)
54 views83 pages

Python Unit 2

The document provides an introduction to Python programming, covering its history, features, and applications in various fields such as web development, game development, and data science. It explains the importance of programming languages in solving complex problems and highlights Python's ease of use, readability, and versatility. Additionally, it contrasts high-level and low-level languages, as well as compilers and interpreters.

Uploaded by

bruno728070
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)
54 views83 pages

Python Unit 2

The document provides an introduction to Python programming, covering its history, features, and applications in various fields such as web development, game development, and data science. It explains the importance of programming languages in solving complex problems and highlights Python's ease of use, readability, and versatility. Additionally, it contrasts high-level and low-level languages, as well as compilers and interpreters.

Uploaded by

bruno728070
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
OYG UV 44) tS) EXPRESSIONS CONTENTS Introduction to Python programming = The Python Interpreter - Interacting with Python Constants, variables and data types Python Data Types Lines and Indentation & Operator precedence and associativity of operators = Managing Input and output operations ia Illustrative Programs 5 Points to Remember - Review Questions es P ine Exerci & Scanned with OKEN Scanner 1.1 INTRODUCTION To PROGRAMMING LANGUAGES Usually computer software may be classified into application software and jj System software. Application software is the set of programs necessary to carry out operations for specified applications, System software are the general programs written for the system, which provide }j the environment to facilitate the writing of application software. Prt) eer 9 Am a Cn Programming language translators are the best example of system software. |} 1.2 WHY PROGRAMMING LANGUAGES? The purpose of using computers is to solve problems, which are difficult to || Solve manually. So the computer user must concentrate on the development of good algorithms for solving problems. After preparing the algorithms, the programmer | or user has to concentrate the programming language which is understandable by I] the computer. Computer programming languages are developed with the primary objectives of facilitating a large number of people to use computers without the need to know the details of internal structure of the computer. Languages are matched to the type of operation to be performed in algorithms || for various applications. Languages are also designed to be machine independent. Programming fosters creativity, reasoning, and problem solving. The || programmer gets the opportunity to create something from nothing, use logic to turn Programming constructs into a form that a computer can run, and when things don’t l| work quite as well as expected, use problem solving to figure out what has gone || wrong. Programming is a fun, sometimes challenging and occasionally frustrating } activity, and the skills learned from it can be useful both in school and at work even if your career has nothing to do with computers. & Scanned with OKEN Scanner GUAGES some of the popular high-level %y This sect a ications. | of thei appli | : “ ja BASIE spur Srbil n, | 1 stands for Beginnet® 1963 by [Link] [Link] and Thoma panos College UPR who are starting their learning I fF ieveloped for the users be learnt quickly. | 1.3.2 FORTRAN RANslation, which is the oJ des | It sands fr FOR oped by John Backus and his ten Tanguage. This a ee imperative, general purpose computer 1956-57. ene well for scientific computations and numeric Opentin TBA developed it in the 1950s, it soon gained popularity in progrannin | structured and compiled programming language, a revised version of Forza object-oriented programming. 1.3.3 COBOL | It stands for COmmon Business Oriented Language. The work | language began in 1959 in USA, department of defence under the guidance ai Murray Hooper, and further it is maintained by CODASYL (Conference a | SYstem Language), The first formal COBOL was published in 1960 and rev | 1965 and this version was gradually enhanced | | | 1968, 1974 and in 1984. C |. ANSI has si rdized COH! «2/8 and in 1984. Currently COBOL i . standardized for business data processing, ly COBOL is a widely used pon ® ing (13.4 PASCAL lis ad developed ed afer the French " mathematician Blaise Pascal and itis is ates Within 1971. The main obtecras iat methods, °° OW beginners to learn good problem solving and 135 ¢ Cis 4 general : Dennis Beneral pose, hip e nis M. Ritchie 1 develop ie one wg els, r : : ating system. at, Bell Lab d ic ih prog eee PDP-11 computer in 1972. In ay 1.3.6. pyr, KER stander. te frst publicly available esr The follow language, lowing Chapters elabora FRE etaite mace © Scanned with OKEN Scanner il DNs, Tena, Mien 1.4 OVERVIEW OF PYTHON « INTRODUCTION PYTHON 1H & yeneralpurpone lilerieted,, iterietive, olijeetonented, wud hyde Jevel prog einiiniig laniipe, Hh win erented by Guild vin Hani, Ha rie Ja An ennytotenin preque arnt finyingue Hit tine wenn really usetal EH " a vey tinny projmaniner, The code ts quite: enny to tel yen connpated to other proyraminitig lanes, and HE haw an iiteraotive shell bata whieh you can enter your programa and see (hem fine Python th one of Howe rire languages yhich cin eli to he Heth siinple and powerhil, You will find yourself pleasintly surprined 10 see how easy ie i te concentrate on the solution (0 the problem rather thin the syntinr and otrictire oF the language you are programming Hi, Python isan enny (0 learn, powerful programming language, 1 has efficient high-level dati structures and a simple but effective appronuh to objeet oriented programming, Python's elegant syntax and dynamic typing, together with it interpreted nature make 1 an jdeal linguage for seripting and rapid application development in many arenas On MOH platforms, Python in A highstevel, interpreted, Interactive and object-oriented weripiny, language and in designed to be highly readable. 1 unew Hnglish keywords frequently, whore av other languages UNE punetuation, wid It has fewer ny ntactionl constrielons Janguages. preted: Python iv provesed al runtine by the 1 do not need (0 compile your program before An almilar to PERL nnd PHP, iver You can wctually sit at a Python peonipt J Interpreter direwtly to welle your prograni Orlented: Python supports Object-Oriented shinique of progeamming that encapaulates code dnner'd Langungel Python ta a preit Aangunge anerelevel programmers and wee the w wide range of applications fron alniple (Xt WWW browaers to jared, al = «ta the neat neeton © Scanned with OKEN Scanner | 1.5 HISTORY OF PYTHON Python was developed by Guido van Rossum in the late eightieg and je ea, nineties at the National Research Institute for Mathematics and Computer Sein, in the Netherlands. Python is derived from many other languages, including ABC, Modula. C++, Algol-68, SmallTalk, and Unix shell and other scripting languages. eS Many of Python's features originated from an interpreted |, ABC. Rossum wanted to correct some of ABC's problems and keep some of features. At the time he was working on the Amoeba distributed i teq group and was looking for a scripting language with a syntax like ABC but With te access to the Amoeba system calls, so he decided to create a language that ws generally extensible. Since he had some experience with using Modula-2+, j. decided to talk with the designers of Modula-3. Modula-3 is the origin of the syntax and semantics used for exceptions, and some other Python features. In 1989, during the Christmas holidays, he decided to give ita try and design a Tanguage which te later called Python. Just in case you're wondering how the language got its name, well it's ax from those dangerous reptiles. Pytho i series from the seventies "Mont RoE x ‘Easy-to-learn: Python is has an extraordinarily sinple gue SY to get Stared Easy-to-maintain: Python’, Extensive Libraries: The It can help you do various documentation generatio; browsers, etc. Interactive Mode: Python S Suy which allows interactive testing and deb Extensible: If you Need a Titical pi, ‘want to have some piece of Algorith IeCe of that part of your program ang exeey Not dais c & Scanned with OKEN Scanner Extendable: We can interpreter, These customize their tool: Databases: databases, GUI Programming: Python supports GUI applications that can be created and ported to many ibrari i y system calls, librarie: svete! y! ies and windows add low-level modules to the Python modules enable programmers to add to or is to be more efficient, Python provides interfaces to all major commercial Scalable: Python provides a better structure and support for large Programs than shell scripting. Simple: Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English, although very strict English. This pseudo-code nature of Python is one of its greatest strengths. : Free and Open Source: Python is an example of a FLOSS (Free Libre and Open-Source Software). In simple terms, you can freely distribute copies of this software, read its source code, make changes to it, and use pieces of it in new free programs. High-level Language: When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc. Interpreted: Python, does not need compilation to binary. You just run the program directly from the source code. Internally, Python converts the source code into an intermediate form called byte codes and then translates this into the native language of your computer and then runs it. All this, actually, makes using Python much easier since you don’t have to worry about compiling the program, making sure that the proper libraries are linked and loaded, etc. ; : Object Oriented: Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object= oriented languages, the program is built around objects which ionali ful but bine data and functionality. Python has a very powel simplistic way of doing OOP, especially when compared to other languages like C++ or Java. sas fupeaaute You can embed Python within your C or C++ programs to give scripting capabilities for your programs. & Scanned with OKEN Scanner Computer Program 1.7 APPLICATIONS OF PYTHON IN SOLVING VARty ENGINEERING PROBLEMS Python supports cross-platform operating systems which lakes application easier and more convenient. Some of the globally known Dplcain, by as YouTube, BitTorrent, DropBox, etc. : 4 1, Web Development Python can be used to make web-applications at a rapid ate, It iS becaus., the frameworks Python uses to create these applications. There is bee, logic that goes into making these frameworks and a number of libraries that can i, integrate protocols 2. Game Development Python is also used in the development of interactive games, There are libra, such as PySoy which is a 3D game engine supporting Python, PyGame which provi, functionality and a library for game development. 3. Machine Learning and Artificial Intelligence Machine Learning and Artificial Intelligence are the talks of the town as they| yield the most promising careers for the future. We make the computer lear ba! ‘on past experiences through the data stored or better yet, create algorithms which makes the computer learn by itself. The programming language that mostly everyone choose’ It's Python. | | | | | 4. Data Science and Data Visualization Data is money if you know how to extract relevant information which can be? you take calculated risks and increase profits. You study the data you have, perfor operations and extract the information required. Libraries such as Pandas, NumPy be? ‘you in extracting information, — lize the data libraries suc it har ba nee ae such as Matpltlb, Seaborn, which much more, This i a Data Scientist, his is what Python offers you to beeo™* 5. Desktop GUI We use Python to program des that can be used to develop user inter as the wxWidgets, Kivy, platforms, ‘top applications it provides dhe Trier Hiv” | ‘ices. There are some other useful toolkits we int ’ seful to0 PYQT that can be used to create applications on © Scanned with OKEN Scanner Do apps and go ahead and create much more complicated applications 6. Web Scraping Applications Python is a saviour when it comes to pull a lary which can then be helpful in various real-world procs job listings, research and development and much more, mount of data from wen wh as prive connpyar’ || 7. Business Applications Business Applications are different than our normal applications oxvering Goran such as e-commerce, ERP and many more, They require applications whic extensible and easily readable and Python provides us with all they: feauures such as Tryton is available to develop such business applications. 8. Audio and Video Applications We use Python to develop applications that can multi-task and also output media. I] Video and audio applications such as TimPlayer, Cplay have been developed using Python libraries. They provide better stability and performance in comparison to other media l| players. || 9. CAD Applications } Computer-Aided Designing is quite challenging to make as many things have I] to be taken care of. Objects and their representation, functions are just the tip of the !| iceberg when it comes to something like this. Python makes this simple too and the | most well-known application for CAD is Fandango. | 10. Embedded Applications Python is based on C which means that it can be used to create Embedded C software for embedded applications. This helps us to perform higher-level applications | on smaller devices which can compute Python. The most well-known embedded application could be the Raspberry Pi which lj uses Python for its computing. We can also use it as a computer or like a simple }| embedded board to perform high-level computations. We use python in a variety of applications. No matter what field you take up, Python is rewarding. So I hope you have understood the Python Applications and what sets Python apart from every other programming language. © Scanned with OKEN Scanner —_—_——— 18 THE PYTHON PROGRAMMING LANGU age 1.8.1 High vs low level languages ‘The programming language you will learn is Python, gi janguage; other high-level languages you might have Han, The e are also low-level languages, sometimes ref Of ae sembly languages.” Computers can only run progres Mr _ So programs written in a high-level language hate Wig n run, This extra processing takes some time, a: x Is a ) | languages” or | level languag before they cai disadvantage of high-level languages. | | | tg | The advantages are enormous. First, it is much easier to | | level language. Programs written in a high-level language take less tim, a ing are shorter and easier to read, and they are more likely to be correct, Set - Seem, oy Oo | level languages are portable, meaning that they can run on different kinds of with few or no modifications. Low-level programs can run on only one king and have to be rewritten to run on another i 1.8.2 Compilers vs Interpreter An interpreter processes the program a little at a time; alternately ready and performing computations. A compiler translates source code into object code, which is run by ata: executor. ; Due to these advantages, almost all programs are written in bi languages. Low level languages are used only for a few specialized appli Compilers/Interpreters a lesscutanid Input’), Executable (see) Program [> Wands his beta Interpreter: analyzes at i mx languay Exectato ogra can bo geet? program statomen “any tines 2 fan comple a Execution is slowet 69 *> fast execution Easier to debug program © Scanned with OKEN Scanner Two Kinds of programs process high-level languages in to low-level lange interpreters and compilers. An interpreter reus high-level program and exe f meaning that it does what the program says. It proc the program a little at a time, alternately reading lines and performing computations i . r reads the program and translates it completely before the program starts running. In this xt, the high-level program is called the sour code, and the translated program is called the object code or the executable. Once a program is compiled, you can execute it repeatedly without further ation. Python is considered an interpreted language be Python programs are executed by an interpreter, There are two ways to use the interpreter: A compi In interactive mode, you type Python programs and the interpreter displays the result: “>>>2t2_ 4 >>>2.0+1.0 3.0 The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready. If you type 2 + 2, the interpreter replies 4. Alternatively, you can store code in a file and use the interpreter to execute the contents of the file which is called a script. By convention, Python scripts have names that end with .py. 1.8.3 Program A program is a sequence of instructions that specifies how to perform a computation. The computation might be something mathematical, such as solving a system of equations or finding the roots of a quadratic equation, but it can also be a symbolic computation, such as searching and replacing text in a document or compiling a program. The details look different in different languages, but a few basic instructions appear in just about every language: Input: Get data from the keyboard, a file, or some other device. Output: Display data on the screen or send data to a file or other device. © Scanned with OKEN Scanner Computer Programming. Process: Perform a series of actions or steps taken in order to achieve te, Conditional execution: Check for certain conditions and contols the fo, : execution depending on condition. Repetition: Perform some action repeatedly, usually with some varia, So, you can think of programming as the process Me breaking a large, task into smaller and smaller subtasks until the subtasks are simple enough to ke performed with one of these basic instructions. 1.8.4 Debugging Programming is error-prone, for unusual reasons. Programming errors az called bugs and the process of tracking them down is called debugging. Three king of errors can occur in a program, syntax errors, runtime errors and semanti | errors. It is useful to distinguish between them in order to track them down ‘more quickly. @ Syntax errors Python can only execute a program if the syntax is correct; otherwise, the interpreter displays an error message. Syntax refers to the structure of a program and the rules about that structure. For example, parentheses have to come in matching pairs, so (2 + 2) is legal, but 2) is a syntax error. Python is not so forgiving. ii there is a single syntax error anywhere in your program, Python will display an erro message and quit, and you will not be able to run your program. e Runtime errors ‘The second type of error is a run time error, so ‘ not appear until after the program has st ~ So called because the error des E mn farted running. These called exceptions because they usually indicate that something exceptional tae also e Semantic errors 3 ‘The third type of error is u es the semantic your program, it will run successfiy error. If there is a semantic error it : ly in the se ‘any error messages, but it will not do the ‘itt tine | that the computer will not gener it will not do what you told jt to 4, ng. It will do The problem is that the progr. write, The meaning of the pig You wrote can be tricky becayse the program lo. Something else. Specificall Use Program's Semantics is oa me ee Program you wanted © Il requires SIS Wrong. Identifyi i Bs and trying (9 tS YOU LO Work backer’: Mentifying semantic ert 6 (0 figure oy, What it is ae by looking at the output ! © Scanned with OKEN Scanner xpressions, Statements Python is a flexible and dynamic language that you can use in different ways. |] You can use it interactively when you simply want to test a code or 2 statement on lj line-by-line basis. You can use it in script mode when you want to imerpret an emaire file of statements or application program. To use Python interactiv either the Command Line window or the IDLE Development Env: } Command Line Interaction: The command line is the most straightforward | |] way to work with Python. You can easily visualize how Python works as it responds to every completed command entered on the >>> prompt. It may not be the most preferred interaction with Python, but it is the simplest way to explore how Python works. 2.1 STARTING PYTHON | ‘There are different ways to access Python’s command line depending on the |) operating system installed on your machine: @ If you're using Windows, you can stant the Python command line by licking on its icon or menu item on the Start menu. @ You may also go to the folder containing the shortcut or the installed files and click on the Python command line. If you're using GNU/Linux, UNIX, and Mac OS systems, you have & Scanned with OKEN Scanner Command Line Wi ython’s IDLE ° Directly from Comms We use commanss to te 0 do something for you, you hav with. Python will thea tra or device can understand 2.2.1 Using Command line Window To see how Python works, y the De Prin Command © Print te hes, | Program “Hello Python” L Open Python's co 3. Press enter tg YOU're doy ‘ OMMAN tine ene With your command. ing line: line Window wi ge JOUE com Nill display Hello, B TO exit fry Dm Py Ython, Ucan LYpe an ; — “PE ANY OF these o exit”) Contry & Scanned with OKEN Scanner . Data Types, 2.2.2 IDLE: Python's Integrated Development Environment (IDE) The IDLE (Integrated Development and Learning Environment) tool is included in Python’s installation aa TEs Package but you can choose to download more sophisticated ; The IDLE tool offers a more efficient platform to write your code and work interactively ‘with Python. You can access IDLE on the same folder where you found the command line icon or on the start menu. As soon as you click on the IDLE icon, it will take you to the Python Shell window. 2.2.3 The Python:Shell Window The Python Shell Window has dropdown menus and a >>> prompt that you have seen earlier in the command line window. Here you can type and enter statements or expressions for evaluation in the same way that you used the command line earlier. This time however, IDLE’s editing menu allows you to scroll back to your previous commands, cut, copy, and paste previous statements and make modifications. IDLE is quite a leap from the command line interaction. eRe pois, 22:26:58) (HSC v.2016 92 bir (Intel) © ini? eiucense ()" or sore informacion. oF Her (wS-7-Seetsecéedi2, Mar 25 NCopysighe", "eredits” oF ment used previously in command line Let us try with the same print state! stag T-avertectedl2, Mar 2 Fisemeips, “eopyesghe”, "erect Pe prise raeaze Fyenen") & Scanned with OKEN Scanner The Shell and Debug menus provide capabilities you would fit wes | Sreating larger programs, My ‘The Shell menu allows you to restart the shell OF Search the sa, find the most recent eset, ; ‘The Debug Menu has usefiil menu items for tracing the SOUT fe exception and highlighting the erring line. R The Debugger option will user in an interactive debugger wingoy & Will allow you to Step through the running program. 2 The Stack Viewer option displays the current Python stack through 2», window. x The Options window allows You to configure IDLE to suit your Python wag: ‘The Help option opens Python Help and documentation, 2.2.4 The File Window The items on the File menu allows yy open an 8 You to y file, open a module, and/or save Your session, ane = scanned with OKEN Scanner Data Ty SS | Types, ‘pressions, Statements When you cli ; ick on the *N a simple and standard vie sartion ' oe . you will be tak it tletsintonire a alter where you can type or edit your ends, ‘iaaly nam but its name will soon change as you save your cote, s r code. Oreene_ Z tere Wintre_p VE (9.641, Hav War 23 3087, TRAiba) ha A800 Be baw Cea)” Tython 3. on wins? xo" SSOpIEtghede. Zemdten® os, cLtemen|) for, mate sat Pg aetna ee dee ist ia hs we oe ee a Se a The File window’s menu bar varies only slightly with the Shell Window. It doesn’t have the ‘Shell’ and ‘Debug’ menu found in the Shell Window but it introduces two new menus: the Run and the Format menu. ‘When you choose to Run your code on the file window, you can see the output on the Shell Window. sasgenee gt 208 nore canyon tbe © Scanned with OKEN Scanner Computer Progr ammine Ps gram W #Program to add two number a =10 b =20 © = ath Print('sum o¢ @ and Br" e) of @ and b: 39 & Scanned with OKEN Scanner ressions, Statements 2.3. PYTHON VIRTUAL MACHINE We alrea at ci ady know that computers can only understands machine codes comprises 0° ea te } reba O's Pers 1's, so it is necessary, we should convert any program into | machi code fore it is submitted for executio So to attain this we should use }} the compiler, it converts program source code into machine understandable form i.e. machine code. So, the Python compiler used to convert the source code into byte code, Byte I} code represents a fixed:set of instructions that represents all oper rations, which runs || on any operating system. The size of each bytecode instruction is 1 byte and hence the name. We can find the Python program's bytecode in the .pyc file. Program Output The role of PVM on Vi Machine) is to convert the bytecode Pyth irtual ine) i can execute these machine conversion ‘Python Virtual, with an Interpreter vi into machine code i i Inter | it convert the pytecode int Machine equipped ith machine code for ex' the Python V tual Machine is also ecution, SO shine code, SO yut. & Scanned with OKEN Scanner PYTHON's CHARACTER SET The character set is the RR QR code fundamental raw materials of any nL language and they are used to represent PPT for this information. Like natural languages, computer language will also have well defined character set, which is useful to build the programs, | 3.1 topic | The classical method of learning English language is learning fitst thy alphabets or characters used in the language. Thus, learn to combine these alphabets to plan for words, which in turn are combined to form sentences Sentences are combined to form paragraphs. Similarly, the characters Used tp write Python programme are basically of two types, namely; i) Source character set ii) Execution character set 3.1.1 Source Character Set zu a lank space, Horizontal tabs Vertical labs, New line, Form feed. © Scanned with OKEN Scanner } 3.1.2 Execution Character Set These are employed at the time of exes H also called as non-graphic characters because, Cannot be printed or displayed directly. These ch being executed. Executio ) followed by a character. These Il when the program is | represented by a backslash (\ as ‘escape sequences’. less than left parenthesis left bracket MATA AT ate blank plus - minus * asterisk comma + period semicolon + colon apostrophe * question mark dollar % perce tilde | vertical bar exclamation & ampersand > greater than ) right parenthesis ] right bracket left brace } right brace number sign @ at symbol _ underscore - hyphen = equal to * caret Beep sound Moves previous position Moves next horizontal tab Moves next vertical tab. Moves next line Moves initial position of next page Moves beginning of the line Present Double quotes Present Apostrophe Character with octal value 000 Present _back Character with hex value hh... © Scanned with OKEN Scanner cution. This set of characters are these characters are invisible and aracters will have effect only n characters set are always are also called Computer Progr 3.2 IDENTIFIERS AND RESERVED WORDS oe to a functi A Python Identifier isa name given on, ¢ module. or other objects that will be using in Python program. SoS ~ in Python should be appropriately named or identified as they wil fee your program. ie Identifiers: Identifiers are names given to various program as variables, functions, lists etc. Identifiers are described by the TEIN, & | definitions: SEE in letters lowercase | uppercase lowercase uppercase digits identifiers. @ An identifier should not begin with a number. Eg: Ia is but al is acceptable. @ Python is a case-sensitive language and this behaviour identifiers. Eg: VRB, Vrb and vrb are different i Python. @ Python keywords cannot be used as identifiers. @ Use underscores to separate multiple words in your isc: 2 Class identifiers begin with an uppercase letter, but the rest of BE identifiers begin in lowercase. @ Choose always an identifier that make sense. @ Starting an identifier with a single leading underscore i that the identifier is private. Starting an identifier with two I strongly private identifier. HW the identifier also ends with two trailing underscores, identifier is a Janguage-detined Special name. leading underscores indi © Scanned with OKEN Scanner 3.3 KEYWORD There are certain res eee seh certain reserved words called keywords, that have standard and me se yeaning in Python language. Which cannot be changed and they are e basic building blocks for program statements. Logical and Part of the With-as_ statement ‘Assert that something is true | Stop this loop right now Define a class 1) Continue the loop” while True: continue Define a function def AQ): pass Fpelete from dictionary | del ADT g Else if condition if, A;_elif: Bi else: C ise condition if Ay elif: Bs alse: C For any exception, xcept ValueError, ¢: print & “pyiho ‘exec print “hello” Hf condition —_ y s[imipore module Part of for-loops ___ | eh eps Pas print ‘this SE eS def AQ: return Bs & Scanned with OKEN Scanner )4.2 INTRODUCTION | Type represents the Kind off vale and derermings, DOW the vai, used. ‘All data values in Python are encapsalaant in relevant Odie Sy Everything in Python is an object and every odect has an Nentity, ae a valve. Like another object-oriented language such as va or C44, gee” several data types which are built into Python, Extension madaks wdig © written in C. Java, or other languages can define additional ypex 7 § To determine a variable’s type in Python you can use the dye) The value of some objects can be changed, Objects whose vale C2 NE dan, are called mutable and objects whose vale is unchangeable, ante Rey ae eng are called immutable. Data type is the type of the data, that are golag © ASS Wi y program. ‘Python’ supports different data (ypes. each date LYRE TAY hee predefined memory requirement and storage representation, Python Rants several data types to facilitate the needs of programmers an appa: developers for workable daa. 5 The data stored in memory can be of many types. For exampk, : person’s age is stored as a numeric value and his or her akklress 18 stared alphanumeric characters. Python has various standand data types Rat Ae BS to define the operations possible on them and the storage methad for awh et them. None is a special constant in Python, It is a null value. None is WX &% same as False. None is not 0. None is not an empty string, Comparing to anything other than None will always return Balse. In other languages Java it is called as ‘null’ object, but in Python it is ‘None’ object. scanned with OKEN Scanner SSS ype (Nona) Solage ‘Noneltype > SS None ee Pale Paleo DS None = 0 Falae >>> None ee Falae >>> None == None teve >» a & None >> a =e None ‘weve >> b = None >» ae b Seve >> None is the only all value, It has its own datatype (NoneType). You can assign None to any variable, but you can Not create other NoneType objects. ‘All variables whose value is None are equal to each other, 4.3 PYTHON NUMBERS ‘One of the many conveniences of usi have to declare a numeric value to distinguish its type. one data type from ‘another when you write and run your statement, It has built-in numeric dati (ypes. Python can handle normal long integers, based on the operating system, Python long integers ™ ‘on available memory, floating point numbers, octal and and complex numbers i.e, numbers with an imaginary component, Numbers are created by numeric literals, Numeric objects are immutable, which means when an object is created its value cannot be changed. Python has three distinct numeric (ypes: integers, Moating point numbers, _ Integers. represent negative and positive integers without vhereas floating point numbers represents negative ancl positive ional parts. In ‘addition, Booleans are subtype of plain integers. ing Python is that you don’t really Python can readily tell four maximum length determined } naximum length dependent hexa-decimal numbers, ——_—_— © Scanned with OKEN Scanner s different numerical types. Python support: Integer: 1234, -39 Python integer: 999999999L Float: 1.234, 5e6, 2e-4 Octal: 013, 0134 Hex: Oxf32, OX13FA Complex: 2+4j, 33, 4.0+1.5) Number data types store numeric values. Number objects are cree, 3. cere when you assign a value to them. Here are some examples of numbers, *). 15 3.175 92931308L ios 9 | oes -9293 -92.9 9.322e-13} | 0138L 4. a 013 | 313+e1s | 356) -1208 | -50. -.9293-+0I 01290 | -39.32e100 | 3er137 | 0 0x58 70.2-E12 4.53e-7j 7218852985291 4.3.1 Integers Integers are whole numbers without deci i it n lecimal point. They can be positit or negative as long as they don’t contain a decimal point that would fae number a floating number, a disti » i in Python. istinct numeric type. Integers have unlimited si The following numbers and literals 1, Regular integers; Normal are recognized by Python: integer numbers & Scanned with OKEN Scanner ORAL Reorats : a . {hase §: To indie eee BW oF 00 ¢ \ indicate an octal number, (POND WY followed by either a lowercase oi Ml uae the OF Uppercase letter > ee > print o) 3s » Rexadecimal literal te Bs Chase 16): To i Jaa Gea prot oe grates To indicate hexadecimal literals, you be iN x” (zero and uppercase or lowercase letter >>> hex_vareOx9A_ >>> print (hex_var) Asa >» Binary literals (base 2): To signify bi i ary ‘ : ‘To signify binary literals, you'll use th SOB? or ‘Ob? (ero and uppercase or lowercase * ae >>> bin=dbll1 >>> print (bin) is >>> 4.3.2 Converting Integers to their String Representation mand converted literals to their makes it possible for you to work the other way to their literal representation, To convert an integer you can Use the functions hex, bin(), and oct(). Earlier, you have seen how the print com equivalent in integers. Python around by converting integers: into its string representation, er 6 to its octal Jiteral, type and enter ‘oct(6) on the ‘a To convert the intey "IL get the output ‘006% command prompt. You’ >>> oot (6) ‘006! >>> & Scanned with OKEN Scanner @ To convert the integer 154 to its hexa-decimal litera) ype \ hex(154) on the command prompt. You'll get the output “Orga! % >>> hex (154) "Ox9a' >>> i its bi id enter bin @ To convert the integer 15 to its binary, type an 15) 0, command prompt. You'll get the output ‘ObII11’. 4 >>> bin(15) "Ob1111' >>> 4.3.3 Floating point numbers Also known as floats, floating-point numbers signify real numbers, Flog, are written with a decimal point that segregates the integer from the fraction, oumbers. They may also be written in scientific notation where the uppereis or lowercase letter ‘e’ signifies the 10th power. >>> 3.3e3 3300.0 >>> 52.5e2 5250.0 >>> 112.9e2 11290.0 . >>> 12345. 6e2 > 1234560.0 >>> 15, 5e4 155000.0 4.3.4 Complex numbers Complex numbers are the form ‘a + py’ where ‘a’ netic ote a is a float and the real the square root of an ; a ora Sani fa imaginary number -], — id J’ or its lowercase. indica This makes ‘b’ the imaginary mo & Scanned with OKEN Scanner ee Ba pes Byron Wines | >>> yeteay >>> neKty >>> print (x) (9454) >>> 4.3.5 Conversion of Number Type You can expect Python to convert expressions with mixed types of numbers to a common type to facilitate evaluation. In some situations, however, you may have to convert one number type to another explicitly, like when the conversion is required by a function parameter, You can type the following j| expressions to convert a number to another type: (ESSE) To convert ‘x’ to a float: To convert ‘x’ to a integer: >>> float(15) >>> int (15.2) 15.0 15 Dre kanaabe >>> (Sener) To convert ‘x’ to a complex number: >>> complex (15) (15+03) >>>complex (15.2) (15.2405) >>>. 4.3.6 bool datatype ae Boolean is a data type, having two values usually jenoted True and False, intended to represent the BET values of logic. It is named after “George Boole”, i ic i id 19% The ebraic system of logic in the mid 19% century. ab spe is re aan: result of conditional statements, which allow change control flow depending on whether a programmet- ndition evaluates to True or False. >>> print (2!=2) False >>> a=(2>3) >>> print (a) False & Scanned with OKEN Scanner 4.4 SEQUEUNCES In Python, sequence is There are s¢ clements or items. Strings are amongst the the generic term for an ordered set gp everal types of sequences in Python @ bytes «Br oe asterisk (*) is the repetition Operator, Most popular types in Python. We can Create the, simply by enclosing characters in quotes, 4.4.2 Accessing Values in Strings Python does not suppor length one, thus also consider To access substrings, index or indices t0 obtain yo [ESE] >>> print 4.4.3 Updating Strings 27? str=!VRB Publishers! VRB Publishers ri a character type; these are treated as Strings « red a substring. use the square brackets for slicing along with the ur substring. oe (str) ipdate an existing string by reassigning a variable to anothe You can y string. The new value’can by different string altogether, 4 e re it i elated to its Previous value or to a. completely ald) tongs) 1 & Scanned with OKEN Scanner 4.4.4 String Formatting Operator operator Is unique to strings and makes up C's printf) family, Here is the list of complete set of symbols which can be used along with % fe | | 4.4.5 Built-in String Methods One of Python's coolest features is the string format operator %- This for the pack of having functions from Pctaracier SUL LEULOSLE Tt theta Siring conversion via str() prior to formatting Sig %i Signed decimal_integer gned decimal integer s Unsigned decimal integer Octal integer Bs Hexadecimal integer (lowercase Jetters) Hexadecimal integer (UPPERcase letters) Exponential notation (with lowercase ‘e’) ‘| Exponential notation (with: UPPERcase ‘E’) Floating point real_ number i P| The shorter of %f and %E Python includes the following built-in methods to manipulate strings. capitalize(): Capitalizes first letter of string. center(width, fillchar): Returns a space-padded string with the original string centered to a total of width columns. count(str,beg=0,end=len(string)): Counts how many times str occurs in string or in a substring of string. find(str, beg=0 end=len(string)): Determine if str occurs in string or ina substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. index(str, beg=0, end=len(string)): Same as find(), but raises an exception if str not found. © Scanned with OKEN Scanner rue if string has at Jeast 1 character and all Chatag, isalnum(: Returns t » 6 are alphanumeric and false otherwise. 7 isalpha(: Returns true if string has at least 1 character and all charace, are alphabetic and false otherwise. aa 8 _ isdigitQ: Returns true if string contains only digits a false Other ise 7 if stri it least 1 cased character : 9 islowerQ: Returns true if string has a ¢ and cased epicter ‘are in lowercase and false otherwise. al] 10 isnumeric(Q: Returns true if a Unicode string contains only numeri, characters and false otherwise. ‘ 11 isspaceQ: Returns true if string contains only whitespace characters any false otherwise. 12. istitle(: Returns true if string is properly "title cased” and false otherwise, 13. isupper(Q: Returns true if string has at least one cased character and al] cased characters are in uppercase and false otherwise. 14 join(seq): Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string. 15 len(string): Returns the length of the string. 16 lower(): Converts all uppercase letters in string to lowercase. 17 max(str): Returns the max alphabetical character from the string str. 18 min(str): Returns the min alphabetical character from the string str. 19 replace(old, new[,max]): Replaces all occurrences of old in string with new or at most max occurrences if max given. 20 strip({chars]): Performs both IstripQ) and rstrip() on string. 21 swapcase(): Inverts case for all letters in string. 2 title: Returns “titlecased” version of string, that i st with uppercase and the rest are lowercase, @ll words begin 23 transilate(table, deletechars="”); P - translation table str(256 chars), reaping ne string according 10 24 upper(): Converts lowercase letters in strin to recast 25 isdecimall: Returns true if @ Unicode ening Gen ha * Unicode string contains only decimal characters and false otherwise, ins only 4.4.6 bytes The byte data type is the numbers are ranging from 0 19 25 Cf byte numbers like an array. By negative numbers. In i clusive, byte array can not even sto Syntax: encodingl errors) | & Scanned with OKEN Scanner bytes (sources, lai BE a! Remar a new “hytes” imregers in the range 0 byven” ject, which Us a Aynnnutahle: sequence at stall tyes is an hae <= 8S 38 ut a ANC haat Ney Aiyptayen ‘ rn toarray’ een Wathods and the same itdexing. and Melng sien Hho Ane NO NNUAL Weems 10, 20,.90, a0, 80 Doo ambytentitems) 1 print(a{0l) print(al2}) 4.4.7 bytearray This is similar to bytes datyy ss a vy tes ype, but bytes datatype array can not be modified, whereas the bytearray (ype array ean be moditied, ae enn err : Return a new array of bytes, The bytearray type iw a mutable sequence of integers in the range 0 <= x < 256, IL has most ‘of the usual methods of mutable Set described in Mutable Sequence "Types, as well As most methods that the bytes type has, jo aes optional source parameter can ye used to Initialize the array ina ww different: Ways: @ Ifitisa string, you must also give parameters; bytearray() then converts the st [Link](). @ If it is an imteger, the array with null bytes. @ If it is an object conforming to the puffer interface, & read-only buffer of the object will be used (0 initialize the byles Array. @ Ifitis jterable, it must be an iterable of Integers In the range ag the initial contents ‘of the array. 0<=x< 256, which are used Without an argument, a array of size () is created. p>> a = bytear >>> print (a) pytearzay (b' python Bytes!) >> x pytearray ({101) >>> print (x) pytearray (b' \n') Syntax the encoding (and optionally, errors) ing, to bytes using will have that size andl will be initialized ton") yay ("Python BY & Scanned with OKEN Scanner Computer 4.4.8 Lists are the most versatile of Python's compound data y separated by commas and enclosed within square brack, Ay List contains items : { The values stored in a list can be accessed using the s} a I (UC ] and [:]) with indexes starting at 0 in the beginning of the list ang Won their way to end -1, The plus (+) sign is the list concatenation Operator risk (*) is. the repetition operator, 1 ay >>> list=['VRB!,9293,13.08, 'Nuni', 70.5] >>> smlist=[456, 'Muni'] >>> print (list) ['VRB', 9293, 13.08, 'Muni', 70.5] >>> print (list[0]) VRB i >>> print (list[2:]) (13.08, 'Muni', 70.5) >>> print (smlist*2) (456, ‘Muni', 456, ‘Muni'] >>> print (list+smlist) U'VRB', 9293,13.08, 'Muni',70.5, 456, 'Muni'] 4.4.9 Tuples A tuple is another sequence data type that is similar to the list, A tuple consists of a number of values Separated by commas. Unlike lists, however tuples in differences between lists and tuples and their elements and size can & >>> tuple=(‘vRB- >>> smltuple= +9293,13.08, "Muni’,70, (456, Mani j 70.5) (VRB', 9293, 13.08, a Print (tuple[o)) ‘Muni’, 70.5) uple[2:]) ni’, 70.5) Ant (emltuple*2) aga * 456, Ytuniry >>> print (t 13. y >>> pr © Scanned with OKEN Scanner 4.4.10 The range datatype The range dat i numbers in the ge cata a in Python very useful to generate sequences of r + “ 7 e given i ” ft The gumbers tn the range are not octane eee For example, a=range(10) genei i fg eee amin Reanget generates a list of 10 values, the legal indices 33> a=range (10) >>> print (a) range(0, 10) >>> for i in a: print (i,end=" ') 1.2 34.5 .6.7.8 9 >>> ; It is possible to’ let the range start at another number, or to specify 2 different increment (even negative; Sometimes this is called the step’). >>> a=range(1,10,2) >>> for i in print(i,end=' ') 13 5)..7.. 9: >>> 4.5 SETS ‘The data type "set", which is a collection type. A set contains an unordered collection of unique and immutable objects. The set data type is, as the name implies, a Python implementation of the sets as they are known from mathematics. The element may not appear jn the same order as they entered into set. There are below sub types of set available in sets. Sees >>> x = set ("Python") >>> print (x) Flot yp tals (Bhs eters: >>> not have accept duplicate elements, if we pass a tuple with A set does 7 I] reappearing elements to the set function, from the below example 20 doublets are in the resulting set of cities. © Scanned with OKEN Scanner \ aon(( Rangalorel, ‘Ohennad!, = utente Yenannad’, 'Dedvie')) 4 PRAASS sonwnnad’ oKodkatas "DANK >» Rroreaset GaP WHE SAME AN Neh but the elements in diiisde, Whereas he steantents ot Qosonvet cannot be modified, >> faefronenaet ("xy") NOUN cay he >> print (fa) frorenaet({'e', ty!) x") 4.6 MAPPINNG (DICTIONARY) A Python's dictionaries are Kind of hash table type. They work tile asouiative arrays of hashes found in Perl and consist of key-value pals, 4 Sesiomary Rey can de almost any Python type, but are usually numbers OF string, Values on the other hand, can be any arbitrary Python object, Dictionaries are enclosad by curly Draces ({ }) and values can be assign! and accessed using square braces ([]), >>> dict={} >>> dict[‘one’]="first one” >>> dict[2]="sacond two” >>> midict={ ‘name! :/Nuni! oda! « ESS scant (atet{ ‘one’ }} 219293", dept: 70” ) first one >>> print(dict [2)) second two >>> print (smidict) Uipame! : "Muni ‘code! Print (smldi dict keys ({ name YS (0) >>> print + de ‘dept’ )) £9293", ‘dept’: ixm") ‘I )) Dictionaries © say that the Gayle 2 NO cones clements cept of are “our ne | OUET AMONA elemento 16 ta dnasttl scanned with OKEN Scanner 4.7 DATA TYPE CONVERSION Sometii So netimes, You may need to perform conversions between the built-in types. ‘ert between types, you simply use the type name as a function, are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value. int(x [,base]) Converts ‘x’ to an integer. base specifies the base if ‘x’ is a string. specifies the base if ‘x’ is a string. Converts ‘x’ to a floating-point number. Creates” a complex number. Converts object ‘x’ to a string representation. (Converts object ‘x’ to an expression string. Evaluates a string and returns an object. Converts ‘s’ to a tuple. Converts ‘s’ to a list. Creates a dictionary. ‘d’ must be a sequence of (key,value) tuples. (Converts ‘s’ to a frozenset. Converts an integer to a character. Converts a single character to its integer. Converts an integer 10 4 hexadecimal. string. Converts an integer to an octal string. ————— & Scanned with OKEN Scanner 5.1 INTRODUCTION f statements in a program or script, Usuay k is a group of sta sted Nl comics Of Ci one statement a ea Bialbend — the ing or scripting : os on the programming Sua structured language. Generally, blocks cata nese so we get a nested block structure. locks a , un A block in a script or program functions as a mean to Brig Slaten, be treated as if they were one statement. In many cases, it also ser ; Hee to limit the lexical scope of variables and functions. Python programs get structure defined by their indentation. But in ty not a matter of style. This code. d through indentatio © case of Python, it’ N, i€., code blocks at 's principle makes it easier to Sa language requiremet "ead and understand Pye Python provides no braces definitions or flow Control. Blo is rigidly enforced, sof te blocks of code for class and func ks Of code are denoted bY line indentation, whit The number of Spaces in the j i is. | within the block must fe inden ing station sng but al at amount, sae ais. & Scanned with OKEN Scanner >>> if True: print (‘true’) els print (‘False’) True >>> 5.2 MULTI-LINE STATEMENTS ae ee Python typically end with a new line. Python does, however, ales of the line continuation character (\) to denote that the line should sum= vVar_1+\ Var_2+\ var_3 print (sum) Statements contained within the O, {}, or © brackets do not need to use the line continuation character. >>> days=[ ‘Mon’ "Tue! ,/Wed', bu! ,/ Fri’ ," Sat’ 7 sun’) >>> 5.3 QUOTATION IN PYTHON i F iple accepts single ()), double (") and trip! string literals, as long aS the same type of quote st The triple quotes are used to span the string acros (" or "") quotes to denote tarts and ends the string. ss multiple lines. bis © Scanned with OKEN Scanner (Noe re >>> word='word’ >>> sentence="This is a 5 >>> paragraph=' It is made up of multiple >>> print (word) word >>> print (sentence) This is a sentence >>> print (paragraph) This is a paragraph. >>> 5.4 COMMENTS IN PYTHON characters after the # and up to the end comment and the Python interpreter igno1 >>> Computer Programmi ‘This is a paragraph. It is made up of multiple lines and senten >>> # This is a comment >>> print(‘Hello, Python!/) # This is another comment Hello, Python! entence” lines and senten; A hash sign (#) that is not inside a string literal begins a Comment, 4 of the physical line are Part of thy res them. 5.5 USING BLANK LINES A line containing only whitespace, as a blank line and Python totally ignores it, : In an interactive interpreter session, line to terminate a multiline Statement, Possibly with a comment, is know. » You must enter an empty physi the single line given tht! @ sample snip using th © Scanned with OKEN Scanner 5.7 MULTIPLE STATEMENT GROUPS AS SUITES a oe - oa Con staifnent, which make a single code block are and class require a header fine eat ti anne, ecw Shine, | | Header lines begin the statem: i ] ; rent (with the keyword) and terminate + i a colon (:) and are followed by one or more lines which make ip te ae i 5.8 DOCSTRING IN PYTHON Doestring is short for documentation stri | or docstrings provide a convenient way of associ modules, functions, classes, and methods. | ‘An object's docsting is defined by including |] statement in the object's definition. It's specified like a comment, to document a specific segment of code. ! Unlike conventional source code comments, the docstring should describe 1] what the function does, not how. All functions should have a docstring. This allows |] the program to inspect these comments at run time, for instance as an jnteractive }] help system, or as metadata. ent in a module, function, It is a string that occurs as the first statemi ; . class, or method definition. ite what a function/class does in the || docstring. Triple quotes are used while writing docsti def double(num): «aapyunction to return 2*num ing. Python documentation strings ‘ating documentation with Python a string constant as the first in source code that is used, We must wr rings. For example: double the value””” © Scanned with OKEN Scanner specifies an operation to be performed on the operands, The data items that operators act upon are called operands, Some operators require two operands called binary operators, while other acts upon only one operand called unary OPERATORS An operator is a symbol that operator, variables or constants, though some are restricted to ‘The operators usually form a part of mathematical or logical Python programming language provides several or, © mJ different kinds of operations. Python operators generally work On mary =| work on cena — The symbols which are used to perform logical and Mathers, operations in a Python Program are called Python - Python oma Join individual constants and variables to form expressions. E | Operators, functions, constants and variables are combined foeede form expressions, | operands and these Where “+? is Operaioy and @, y» Consider the : 1S isc The Operators expression atas OnStaN and ak xe Where, > +, * are operators. +) 'S an expression, tell the con to pey Perform the Specified operatic’ '| i ; mpute are Used j Puler IN progran '0 manipulate data and variabl* | © Scanned with OKEN Scanner ons, Statements 6.2 TYPES OF OPERATORS Python provides a rich set p Sa set of operators, depending upon their o They are classified as: nla @ Arithmetic Operators. ~ @ Comparison (Relational) Operators @ Logical Operators -@ Assignment Operators @ Bitwise Operators _ @ Membership Operators - @ Identity Operators: @ Unary Arithmetic Operators @ Boolean Operator 6.2.1 Arithmetic Operators Python allows us to carryout basic arithmetic operations like 3 subtraction, multiplication, and division, The following table shows the Arithmetic Operators and their meaning. Let_as assume x = 10, y =20: ‘Addition-Adds values on either side of the operator. Modulus-Divides left hand operand by right hand operand and returns remainder Floor Div! ion-The divi a operands where the result is the quotient in which the digits after the decimal point are But if one of th negative, the res & Scanned with OKEN Scanner F 2 30 sentey,_ Petia L ourn, jared Ls & = ot = STi 2 Gs 50 conten s SSMTRA-9 ourTT,) 3urzd Bg xe cess Cvs @= ST “Zz Jo sentes-c SONTRA-G eUTT,) quTIZd Rex ez ST 2 Jo sentes-y SONTeA-p euTT,)quTad Rp ow ee ST Z jo senTea-¢ SONTPA-E PUTT) JuTId Beg Ra ts ST Z FO senTep-z SONTeA-Z eUTT,)QuUTAd A - * = 2 ST Z JO SONTeA-T senTeA-T. euTT,)3uTAd K+x = 2 0 = 2 or = A oz = * @ Scanned with OKEN Scanner 22k wuenuade susmgrue fe 2: saowuado apaunppre jo ous ap ayeansnyy op uTEssy i © scanned with OKEN Scanner Computer Programmings 6.2.2 Python Comparison/Relational Operators ~\ Relational operators are used to compare two or More Operands may be variables, constants or expressions, Por © ee " compare the age of two persons, or the price of two items ang ta: comparisons can be done with the help of relational Operators, Ly The following table shows the Relational Operators, If the values of two operands are equal, then the condition becomes true. If values of two operands are not then condition becomes true, If the value of left operand is greater than the value of right operand, then condition becomes true. If the value of left Operand is greater than or equal to the value of right operand, then condition becomes true. If the value of Jer than or equal to operand, then co; {l operand is Tess the value of right ndition becomes true, nies are used on either side of iit arithmetic expression will 6¢ re: then thn ear. CeSsion Wi © Scanned with OKEN Scanner Reaetional 0 xt ois Kk roCeN y are QPONAOER AEE Ute it \ AL LW dewision aval S RANEY Boed HE connetitionsal, aawl conteat statements epee Tay Progra to . we various relational operators and display thelr Eee yes Fhiee Bee iy equal Y) prdeechtaee Lay xed equal @ yy) =F x prow(*hake Aw & Ket equal toy") peda Line Ax equal @ Y") me prden("hdee Se ay less that y" ) pane oe as not less that y") igor >yk | priee(*Line dv is greater thane Y eters prbee( "Line fx Bs OF greater than ¥") = = 20 cx Value of z is ", 2) 7 - Value of z is ", 2) im - Value of z is", z) a + Value of z is ", z) 2B 1. is " a - Value of z is ", z) 16 a 17 | print ("Line 6 - Value of z is ", 2) 18 |z = x 7 19 | print ("Line 7 - Value of zis ", 2) ourpur: Line 1 - Value of z is 39 Line 2 - Value of z is 59 Line 3 - Value of z is 1000 Line 4 - Value of z is -50.9 Line 5 - Value of z ig 2 T= Line 6 - Vatue Ff zis 1048576 os Line 7 - Value of z ig 52428 _ EXPLANATION ; This 62.5 Bitwise Operators Bitwise operato on integers only. Bitwi binary digi 5. Tt operate Program reads enon on inp for assignment op rs are 4 at © operators erators, values from input manipulate the dat act on operands a ence the name ta i bit level. To nent 'S if they were string he oa new programmers, " © be honest, you eos re md » oma However, " Should have a general ide? © Scanned with OKEN Scanner wie oN tse operators supported by Python language, assume it Now in inary format they will be ax follows E100) Binary AND = Operator copies a) (Ay) (eatts OOK \Binary Left Shift - The left o s value is moved left [by the number of bits specified iby the the right ope Program to demonstrate bitwise operators. sere pinwise operator gO = DOLL LLL ro Sag = 0000 100 weg &) is ("Line 1 > Value of ois 8 xiy . pine 2 ~ Value af = 8% opine 3 + Value of = i Nn A we a how print (( = 7% © Scanned with OKEN Scanner Computer Programy 712- Pye 2) print ("Line 4 - Value of z is pexr<< 2 is a) print ("Line § - Value of z is '", 2 x>> 2 a i | print ("Line 6 - Value of z is '", z) — a Line I~ Value of zis 10 Line 2 - Value of zis 63 ts Line 3 - Value of z is 53 a Line 4 - Value of z is -63 | Line 5 ~ Value of z is 248 i Line 6 - Value of zis 15 EXPLANATION : This Program prints the result of bit operands x and y, vhich Were assigned at the starting, 6.2.6 Membership Operators Python’s member: as str ship operators test for membership in a ; below: Ss. There are two membership Operators as ings, lists, or tuple al ex Evaluates to tue if it finds a Variable in the speci Pecifie Sequence and fal 4 & Scanned with OKEN Scanner a=2 if (x in list): rint(" ie int("Line 3 = x is available in the given list") prin("Line 3 - x is not available in the given list") OUTPUT: Line 1 - x is available in the given list Line 2 ~ y is available in the given list Li is_available given list EXPLANATION : This program explains the members operators in and not in operators. 6.2.7 Identity Operators Identity operators compare the memory locations of two objects. is and is not are the identity operators in Python. They are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical. There are two Identity operators explained below: x is y, here is results in Evaluates to true if the variables on 1 if id(x) equals id(y). either side of the operator point to the same object ‘and false otherwise. | Evz bles. x is not y, hereis not e “|results in 1 if id) ; not equal 0 id(y)- trate Identity operators —— % Program to demonstrate Tdentity operator x2 = 20 if (x is y): ue print("Line 1 - * and y print("Line 1 - * and y do nol if (id) id(y)? print("Line 2 - have same identity") else: t have same identity") x and y have same identity") ae y do not have same identity") prin("Line 2 - x and ee & Scanned with OKEN Scanner > 30 if cet "Line 3 - x and y have same identity) prin ("Line 3 - = and y do not have same téentiyn aie Ole etal 4-8 and y do not have same idendyny 10 | else: print ("Line 4 - x and y have same identity”) Line 1 - x and y have same identity Line 2 - x and y have same identity Line 3 - x and y have same identity ine 4 - x and y have same identity EXPLANATION : This operands x and y, ae program prints the result of Ident i which were assigned at the starting. 6.2.8 Unary Arithmetic Operator All unary arithmetic operations © The unary have the same priority, ~ (minus) operator yields the ti “i ne yi Negation of its nune, >>>" aso Print (-a) b=20 >>> bey Print (b) © Scanned with OKEN Scanner 6.2.9 Boolean Operators A Boolean expressi ; True or False, Py foe See logical expression evaluates to one of two states or Troe. Many ae the Boolean type that can be either set to False Boolean opérators are et ote returns Boolean objects. ire three a—True and b=False, le in Python as explained below. Let us take Boolean and operator, if both ‘a’ » oth ‘a’ and a and b False are True then the result is True a a orb —» True Boolean not operator, if ‘a’ is True not a —» False then the result is False else True 7.1 INTRODUCTION } An expression represents data iter interconnected with operators as per the s) }} is evaluated using assignment operator. m such as variables, constants and are yyntax of the language. An expression evaluated first from left to right. the expression | value is assigned to the variable In the above statement ssion the final H After the evaluation of the expre from right to left. optional and adds only to improve The blank space around an operator is readability of the program. & Scanned with OKEN Scanner CO OOTY, f Algebraic expressions and Python EXPTESSion, les 0 Examp! Precedence is used to determine the order in which different operac in a complex expression are evaluated, Associativity is used to determine the o1 Precedence are evaluated in rder in which operators with ss @ complex expr. ession. Usually the Arithmetic Oper the precedence of o Talors: are ight wet Perators When the ©, VAluated from left to righ! Parameters. “xPression is written without & The Arithmetic Operator Preceden ce ation ig . Pression, > “@ttied our using the two pis ity One, i Priorat Te evaluated in the expres SPerators. are evaluated in a © Scanned with OKEN Scanner | where, x = 3,y = 92 = 1 sum = 3-93 +77*3-1 ] This expression is lH} revalued in two phases, as follows: |] First phase + H sum = 3-3 +77*3-1 sui = 3-3 + 231-1 || Second phase : sum = 0 + 231 - 1 ] sum = 231 - 1 sum = 230 ‘This is illustrated in figure. However, during the evaluation of expression, the order of evaluation can be changed by putting the parenthesis in an expression. (eee) G-913+7*7B-) = 6B + 71.* > Y - 63 +77 *2 -2 + 154 = 152 LES FOR EVALUATE GUE the wib expressions from jeft to right if parenthesized. uate the arithmetic expression from left 10 right using the rules of precedence. f a The highest precedence is given to the expressions with in ive rule, ON OF EXPRESSION if more operators of the same most sub expression if the parenthesis are & Scanned with OKEN Scanner Computer Progra 8.3 PRECEDENCE AND ASSOCIATIVITY OF OPERy When more than one operator appears in an expression, the evaluation depends on the rules of precedence. For mathematical a, hy) follows mathematical convention. The acronym PEMDAS ig g Usefy ry} remember the rules. P Parentheses first E Exponents (Powers and Square MD Multiplication and Division (left-t ‘Addition and Subtraction (left-to~ has a precedence associated with it jow an expression involving more tha: Every operator in Python precedence is used to determine hi operator is evaluated. j The operators at the higher level of precedence are evaluated first 1 operators of the same precedence evaluated either from left to right or sgt left depending on the level is known as associativity. Hierarchy of operators in Python are summarised below: al x3 the Any expression within parenthesis is first evi than one pair of parenthesis are present, parenthesis is evaluated first. Unary operators are evaluated first in an express! Then priority is given for multiplication and divisit Then subtraction and addition are performed. Then relational operations are performed. Then equality checking is performed. Then logical operations are performed. Then the conditions are checked. Finally, the assignment Operation is carried out. eencevrvcen Wind : the com in doubt, always put parentheses in your expressions '° Putations are performed in the order you intend, | © Scanned with OKEN Scanner 1 Haweent \v at ATEN. TUG [lhe ail uw idl Meattipty, divinte, quaatile rer dlonnannnt ile Operator Precedence: Progen w avon Hracedene reauounteate OPE tregeaye (0 at) o* eo ie ae ra ; eedd agen aed ‘ wae al ye cn se ao ra a wit fa hang hah ots pit fig 4, we fay iy HM swe print fovaine at Fenians , 0 | } i u he at * * and ye fe amie (aenell? tine as andy ue wwe welt | bine te’ “ addy Wa ve went | tine oh aud & nave 8 se (aden tll scanned with OKEN Scanner We know that input, process, output are the three essential features of computer || program. The program takes some input data, processes it and gives the output. We have two methods for providing data to the program. @ Assigning the data to the variables in a Program; @ By using the Input/Output statements. Python provides numerous built-in functions that are readj us at the Python prompt Y ani Standard input Most programs need : the j a user to perform ii . i = ool that you Pick up at the hardware i Interesting operations. Jus When performing some task ‘ore, a program can be a pov 1s important to ky : = them with a way to see, py POW © get input fr how tf coming back,» ‘° 8° how the ‘Om the user, and how to The basic iny Fs : Iput and : and there’ Output : : = 5 plenty of sample eae 7 ee in Python are explained ar his Som ; 9 input and me the function like in Set You started with your own pre? ite Tepeetively Nd printd are Widely used for st vel 9.2 PYTHON INPUT - Hi Python's is often Caled yt function ti os 3 user {0 Ente FOMPL bec 8 @ single . ? enter ‘omething because it containg eter that is a string. This ome helpful text promptitt To ali Python, ye hate Alexin & Scanned with OKEN Scanner Where prompt is the string, we wish to display on the screen. ft is optin y mi. It is optional >>> n= input (‘Enter the Enter the num:92 Here, we can see that the entered value 92 is js a s a str mom To convert this into a number we can use int() or float) fi ing, St 8 somiber >>> n = input (‘Enter the num:’) Enter the num:92 >> n 192" >>> int(n) 92 >>> float(n) 92.0 >>> If we want to ask the user a question, like What is your name? or How old are you?, we are asking the user for some input. We'd like to pose 2 !] question, give a prompt, and wait for the user to enter in the answer. >>> input (‘what is your name?:") what is your name?:Muni ‘Muni’ >> | By using the input statement along with a string containing the question, you'd like to ask the user, you can get the response you're Tooking for. In this case, the interpreter is actually waiting for some input from us, and we don't | yet see the >>> prompt, because we haven't given our name. Let's finish things jf || up, and type in a name. >>> input (‘what is your name?:’) what is your name?:Muni ‘Muni’ >>> After giving the input, why it just printed out our ans our calculator examples by print typed in 4 + 9 at the prompt, iL will show immedaitely, You might be wondering wer at the end. It's acting in a similar way © |] ing out the result ‘of the statement, When we it primed 13. © Scanned with OKEN Scanner i statement asking for the User'y When we typed in a staten My, : came Way. . sult in the same wa ici dks san pt fnetion prints out your nein = 8 0 the nN § od was for you to enter — back the mo rk . . i: hit When it's all done, it gives: y' cu" are hit. >>>name = ee ae your name what is your name? :Mun: >>> e dec! C, se it to ca t! We ¢ iable called name, and use ii Ye declare a variable cal n ; t, input res to us. Adding variable assignment gives Python q ay inpu s . cony . iy to hold the value, Now, you can print that value assigned 10 the vac >>>name A | ea >>> The input function always returns a string, let us take the below eu | the age given in input as 40, whereas it is considered as string ‘49 >>> input (‘What is What is your age ‘40r >> (ESET) Program to Demonstration of input function,” your age ?:/) 0 | # use of inp Sanction name=inpui('En | course =input('Entey Shoat cu Jour marks in subt;"yy rks in sub2:") our marks in sub3: » er Your ma loatlinput(' Ente ye fotal= 11+ m2 4m 3 98 =total/3 | PAM Your Toray Marks:', toy, im 2 total Print’ Your Average Mar} , ovtrur ; 7 1 3 4 5 6 8 9 1 0 & Scanned with OKEN Scanner 9.3 PYTHON OUTPUT "The simplest way to st Wa produce output is usi oi) ‘Cl es ze " ‘ sin you cat pass zero or more expressions Sahint byron Ea eee a converts the expressions you pass into a string and write: the es This funtion output, Wwe Use the print() function to output data to the Sawn Pies lard output device (screen). Bach time we use one of the functit i functions like input or int wit i f the func withot or wee oeecing a variable name into the inirpreer Aba » printing out a value, We're not really print ing , rin . iy printing anythi don't yet have a way to use these values oh ial assignment, it appears as U for the user, and we way. ‘The print built-in function allows us to do all i print information, you're telling Python to send some ono Coin or the user to see. It's not printing to a printer, but printing to the available display, like the interpreter window. We can also output data to a file, but this will be discussed later. ‘An example use is given below. ; >o> print (‘Output to the screen') output to the screen >>> a = 9293 >>> print (‘The value of & is’, a) the value of a is 9293 an notice that a space was added tement, we Ci s by default, but we can In the second print() stal between the string and the value ‘of variable ‘a’. This is change it. a Syntax: | inted. The sep separator is used 5 the value(s) (0 be pri fter all values are Here, objects i between the values. It defaults into @ space character. Al printed, end is printed. It defaults into a new line. are printed and its de! The file is the object where the values are | 1 is [Link](screen). Here are some example to illustrate this. >>> print (1/2/3 12345 >>> pesne cna Se S/N 20g eaed >>> print (1, 1H2H3HAnss& >>> fault value 4,5) 2,3,4/5/80R='# yend=" 6") & Scanned with OKEN Scanner 9.3.1 Output formatting Sometimes we would like to format our Output to 2 This can be done by using the [Link]() method, Thig ™Metho ‘lt . Vi string object. >>> x = 10; y = 20 >>> print (‘The values of x is{}and y is {}'. format (x,y)) The values of x is 10 and y is 29 >>> Here the curly braces {} are used as placeholders, We can os order in which it is printed by using numbers (tuple index), i » I am studying BEandCSE >>> We can even use keyword arguments to format the string, >>> print(‘Hello {a}, {b}’. format (b = ‘good morning’,a = ‘Muni’)) Hello Muni,good morning We can even format strings like the old sprintf) style used programming language. We use the % operator to accomplish this. x = 123.456789 print('The values of x is %3.2£'%x) values of x is 123,46 print('The values of x is %3.3£'%x) values of x is 123.457 ?>> print('The values of x is %3.4£'%x) The values of xis 123.4568 Print (‘The values of x is $3.5£' 4x) values of x is 123. 45679 Print ('The values of xis %3.6£'%x) values of x is 123. 456799 & Scanned with OKEN Scanner Data Types, Expressions, Statements Tn addi tes coated 7 eg ne —— bhed can also include a format modifier bet e % and haracter. Format modifiers may be used to left- isiy or right justify the value with @ specified field width, Modifiers can ee be to specify the field width along with a number of digits after the decimal point. number | %20d Put the value in a field width of 20 jide, Put the value in 2 field 20 characters W right-justified. Pat the value jma field 20 Tharacters wide, fill in with leading zet0S- Put the value in a field 20 characters wide with 2 chars 10 the right of the decimal point. the supplied dictionary key. ight si is a ction of values that will ‘The right side of the format operator is a collection © ] i mat Fe collection Will tbe either a tuple oF 3 the, for tion We aeted in. order of POS S. be inserted into . ict mat SM upie, the values ins ‘ dictonary ee Me onary. the ‘values are inserte according (© their keys. se. the modifier 1 specify. the name If the collection is # i In this case all format characters must of the key- © Scanned with OKEN Scanner Computer Program wl 9.4 PYTHON IMPORT vs bigger, it is a good idea to py cn our program gros bigger, i ; eR patie a le containing Python definitions and sa proach ¢ t filename and end with the extension .py, : modules have & inverucsine interpreter in Python, We use the import keyword | " nitions inside a module can be imported to another Module {0 do yi" ce file as a module by i You can use any Python source 7 - a Y execu i we statement in some other Python source file. ® ; @O+=zc When the interpreter encounters an import statement, it imports the may, if the module is present in the search path, A search path is a list of die : that the interpreter searches before importing a module, For example, to | the module support, Py, you need to put the following command at the gy the script. math module by typing in import ma fi >>> import math >>> print ([Link]) 3.141592653589793 >>> We can import the Now all the defini can also import the from keyword, itions inside math module are available in our scope, some specific attributes and functions ‘only, us >>> from math >> pi import pr 3-141592653589793 >> While import Sys-path. It is a ig ing a module, i 1 Py Of directo thon loo} Ks at define #| TY locations, at several places Ba © Scanned with OKEN Scanner

You might also like