You are on page 1of 230
Lares aot} s grees fy ook oF Python For B.B.A.(C.A) : Semester - V [Course Code CA-504 : Credits-03] ICBCS Pattern} As Per New Syllabus, Effective from June 2021 Dr. Ms. Manisha Bharambe M.Sc. (Comp. Sci.), M.Phil, Ph.D (Comp. Sei) Vice Principal and BCA Coordinator NES Abasaheb Garware College, Pune 4 Price % 300/- Syllabus ... L 3. Introdu ul 12 13 14 1s 16 7 18 19 ion to Python [Lectures 16] History, Feature of Python, Setting-up Path, Working with Python Interpreter, Basic Syntay, Variable and Data Types, Operators. Conditional Statements - If, I-Else, nested if-else, Examples. Looping - For, While, Nested Loops, Examples Control Statements - Break, Continue, Pass. String Manipulation - Accessing String, Basic Operations, String Slices, Function and Methods, Examples Lists - Introduction, Accessing List, Operations, Working with Lists, Function and Methods Tuple - Introduction, Accessing Tuples, Operations Working, Function and Methods, Examples. Dictionaries - Introduction, Accessing Values in Dictionaries, Working with Dictionaries, Properties, Function, Examples. Functions ~ Defining a Function, Calling a Function, Types of Function, Function Arguments, Anonymous Function, Global and Local Variable, Examples. Modules and Packages Lectures 6] 2a 22 23 Built in Modules 2.1.1 Importing Modules in Python Program 2.12 Working with Random Modules. 2.13 Eg. built-ins, time, date time, calendar, sys, etc. User Defined Functions 2.21 Structure of Python Modules Packages 23.1 Predefined Packages 2.3.2 User defined Packages Classes, Objects and Inheritance [Lectures 8] 3 32 Classes and Objects 3.11 Classes as User Defined Data Type 3.12 Objects as Instances of Classes 3.13 Creating Class and Objects 3.14 Creating Objects by Passing Values 3.15 Variables and Methods in a Class Inheritance 3.21 Single Inheritance 3.22 Multilevel Inheritance 3.23. Multiple Inheritance 3.24 Hybrid Inheritance 3.25 Hierarchical Inheritance 3.26 IS-A Relationship and HAS-A Relationship Exception Handling [Lectures 4] al 42 43 44 4S 46 GUI Program 51 52 5A 55 5.6 57 58 Python Exception Common Exception Exception handling in Python (try-except-else) The except Statement with No Exception Multiple Exception The try-finally Clause Custom Exception and Assert Statement 9 [Lectures 10] Introduction Tkinter Programming Tkinter Widgets Frame Button Label Enty Python Libraries [Lectures 4] el 62 63 64 65 Statistical Analysis - NumPy, SciPy, Pandas, StatsModels Data Visualization - Matplotlib, Seabom, Plotly Data Modelling and Machine Learning - Scikit-learn, XGBoost, EliS Deep Learning - TensorFlow, Pytorch, Keras Natural Language Processing (NLP) - NLTK, SpaCy, Gensim a Contents 4. Introduction to Python Modules and Packages Classes, Objects and Inheritance Exception Handling GUI Programming Python Libraries 14 24 34 44 5.1 6.1 1.84 2.30 3.30 448 5.32 6.28 Introduction to Python [Learning Objectives... a) To ean base Conceptsin Pytton fl To study Basics of Pythor '] To understands Data Types, Variables, Constants etc. in Python. INTRODUCTION * Python is a high-level, interpreted, interactive and object-oriented programming language. Today, Python is the trendiest programming language programming. * There are several reasons for why Python programming language is the preferable choice of the programmers/developers over other popular programming languages like C++, Java and so on, + Python is popular programming language because of it provides more reliability of code, clean syntax of code, advanced language features, scalability of code, portability of code, support object oriented programming, broad standard library, easy to learn and read, support GUI mode, interactive, versatile and interpreted, interfaces to all major commercial databases and so on. + There are two major Python versions namely, Python 2 and Python 3. Python 3.0 was developed with the same philosophy as in prior versions. + Python 395 is the newest major release of the Python programming language. Python scripts normally have the file extension .py. + Some common applications of Python Programming are listed below: 1. Google's App Engine web development framework uses Python as an application language. 2. Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API. 3. Linux Weekly News, published by using a web application written in Python programming 4. Google makes extensive use of Python in its Web Search Systems. Python [BBA (CA - Ser. V) 12 Introduction te Python 5. The popular YouTube video sharing service is largely written in Python programming, 6. The NSA (National Security Agency) uses Python programming for cryptography and intelligence analysis. 7. iRobot uses Python programming to develop commercial and military robotic devices. 8. The Raspberry Pi single-board computer promotes Python programming as its educational language. 9. Netflix and Yelp have both documented the role of Python in their software infrastructures. 10. Industrial Light and Magic, Pixar and others uses Python programming in the production of animated movies. History * Python laid its foundation in the late 1980s. Python was developed by Guido Van Rossum at National Research Institute for Mathematics and Computer Science in Netherlands in 1990. * Inspired by Monty Python's Flying Circus, a BBC comedy series, he named the language Python. * Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol- 68, SmallTalk, and Unix shell and other scripting languages. ‘* ABC programming language is said to be the predecessor of Python language which was capable of Exception Handling and interfacing with Amoeba Operating System. + Like Perl, Python source code is now available under the GNU General Public License (GPL). In February 1991, Guido Van Rossum published Python 0.9.0 (first release). In addition to exception handling, Python included classes, lists and strings. + tn 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce which aligned it heavily in relation to functional programming. * Python 2.0 added new features like list comprehensions, garbage collection system and it supported Unicode. * On December 3, 2008, Python 3.0 (also called “Py3K") was released. It was designed to rectify fundamental flaw of the language. In Python 3.0 the print statement has been replaced with a print() function. ‘* Python widely used in both industry and academia because of its simple, concise and extensive support of libraries. + Python is available for almost all operating systems such as Windows, Mac, Linux/ Unix etc. Python can be downloading from http://www.python.org/downloads. [EEE] reatures of Python * Features of Python programming language are given below: 1. Simple and Easy-to-Learn: Python is a simple language with few keywords, simple structure and its syntax is also clearly defined. This makes Python a Python [BBA (CA - Ser. V) 13 Introduction te Python 5. beginner's language. In Python programming programs are easy to write and execute as it omits some cumbersome, poorly understandable and confusing features of other programming language such as C++ and Java. Interpreted and Interactive: Python is processed at runtime by the interpreter. ‘We need not compile the Program before executing It. The Python prompt interact with the interpreter to interpret the programs that we have written. Python has an option namely interactive mode which allows interactive testing and debugging of code, Object-Oriented: Python supports Object Oriented Programming (OOP) concepts that encapsulate code within objects. All concepts in OOPs like data hiding, Operator Overloading, inheritance etc. can be well written in Python, It supports functional a3 well as structured Programming. Platform Independence/Cross Platform Language/Portable: Python can run on a wide variety of hardware and software platforms and has the same interface on all platforms, such as Windows, Unix, Linux and Macintosh. Fig. 11 shows execution of Python code by interpreter. Interpreter g We e Compiler Bye Mita 5 & br source cove Running code Library modules Fig. 1.1: Execution of Python Code Python source code goes through Compiler which compiles the source code into a format known as byte code. Byte code is a lower level, platform independent, efficient and intermediate representation of the source code. As soon as source code gets converted to byte code, it is fed into PVM (Python Virtual Machine). The PVM is the runtime engine of Python; it’s always present as part of the Python system, and is the component that truly runs the scripts. Technically, it’s just the last step of what is called the Python interpreter. Scalable: Python provides a better structure and support for large Programs than shell scripting. It can be used as a scripting language or can be compiled to byte code {intermediate code that is platform independent) for building large applications. Extendable: You can add low-level modules to the Python interpreter. These modules enable Programmers to add to or customize their tools to be more efficient. It can be easily integrated with C, COM, ActiveX, CORBA, and Java. Dynamic: Python provides very high-level dynamic data types and supports dynamic type checking. It also supports automatic garbage collection. Python [BBA (CA - Ser. V) 1a Introduction te Python 8, GUI Programming and Databases: Python supports GUI applications that can be created and ported to many libraries and windows systems, such as Windows Microsoft Foundation Classes (MFC), Macintosh, and the X Window system of Unix Python also provides interlaces to all major commercial databases. 9. Broad Standard Library: Python's library is portable and cross platform compatible on UNIX, Linux, Windows and Macintosh. This helps in the support and development of a wide range of applications from simple text processing to browsers and complex games. 10, Free and Open Source: Python programming language is developed under an OSI approved open source license making it freely available at official web address. The source code is also available for use. The Python software can be freely distributed and any one can use and read its source code make changes/modifications to it and use the pieces in new free programs. Setting-up Path + Before starting working with Python, a specific path is to set. + Your Python program and executable code can reside in any directory of your system, therefore Operating System provides a specific search path that index the directories Operating System should search for executable code. + The Path is set in the Environment Variable of My Computer properties. + Steps areas follows: 1. First install the python. Then go to this pe (My Computer) and Right click on My Computer and click on properties. This should open up the System Properties window. Go tothe Advanced tab and click the Environment Variables button: aan Ropes x Conte Nine “Hane Moros! Sen Piecion | Rete Youmatbelognd on at an Annies mie these ching Feomanie aul fs. pocenor sheding menage and wiser) erin Deshop mage yar ee Seino amg and Recover Spun tain tanta, nd buns fomaton Python [BBA (CA - Ser. V) 1s Introduction te Python 2. Click on new tab of user variables. once Cente ante be Ctsmteuppoestacning bd ‘tse penne ens) [ea [ae rome conn anand oo coat hens Mme ocrRcesons§ oe) | ee Fig.13 3. Write path in variable name. erties arable x Vane nme Varabevaue frowe Deed | | Brome. (po) Fig. 1.4 4, Copy the path of Python folder and Paste path of Python in variable value. New Use Voabie x Warablename: [path Varablevaive [Evian pat Rosming Wicrero Windows Sian Mend Programa 3 Browse Brecon... [Browse Fle. oe Caneel Fig. 15 Python [BBA (CA - Ser. V) 1s Introduction te Python 5, Click on Okbutton: emp coe Cea ouane SEreanene Mees = Ce eR i Freres < z Erentiecenreried a as toiee Eeeaneme soe Cer oe a a eT Fig.1.6 6. Click on Ok button: Close all windows. Now you can run python.exe without specifying the full path to the file: EER] working with Python Interpreter + An interpreter is a kind of program that executes other programs. When you write Python programs, it converts source code written by the developer into intermediate language which is again translated into the native language / machine language that is executed. Starting Python in different Modes: 1. Starting Python Command Line: + APython script can be executed at command line also. This can be done by invoking the interpreter on the application. + Im command line mode, we type the Python programming program on the Python shell and the interpreter prints the result. The steps are given below: Python [BBA (CA - Ser. V) a7 Introduction te Python Step1 : Step2: Step3: Press Start button, (See Fig. 17) Click on All Programs and then click on Python 3.9 (64 bit) as shown in ig. 17. Wewill see the Python interactive prompt in Python command line. fF, Dan BE, 5:08:21) (SC WAS “rect” or “LSceee” for sore infra Python command prompt contains an opening message >>> called command prompt. The cursor at command prompt waits for to enter Python command, A complete command is called a statement. For example fo bie (| ow To exit from the command line of Python, use Ctrl#z or quit() followed by Enter. Python [BBA (CA - Ser. V) 28 Introduction te Python 2. Starting Python IDLE: ‘When we install Python 3, we also get IDLE (Integrated Development Environment). IDLE includes a color syntax-highlighting editor, a debugger, the Python Shell, and a complete: The steps. Step1 : Step2 : copy of Python 3's online documentation set. are given below: Press Start button and click on IDLE (Python 3.9, 64-bit) options as shown in Fig. 110, ‘We will see the Python interactive prompt i. Esha385 interactive shell. =o x Fe E51 Shel Debug Options Window Help Dé4)} on wins? ~ . frype *help", "copyright, "credits or “License()* for more information 2982) (MSC v.1628 GF BLE GM Fig.1.10 Python interactive shell prompt contains opening message >>>, called shell prompt. A cursor is waiting for the command. A complete command is called a statement. When we write a command and press enter, the python interpreter will immediately display the result. 7 LES 355 =o x File Est Shell Osbug Options Window Help Pychen 5.9.6 (tags/¥s.8.6r@38876, Jun 28 102i, 15376 ea} on wana [Type thelp", "copyright, “credits” or *License()* for more information. >>> pranc("ielic, i Zi) (MSE vAisiS oa IE GE Fig.1.1 Executing Python Programs Scripts: In Python IDLEs shell window, click on File, and select the New File or press Ctrl+N. Tie) cast es cae wereaite” or "21 me orm: eee carer feredite™ or *License()" for more information. Recent ies, » Path Bowser Sees. Cho Shites Save Copy. AkoSHiteS cue Choe aire eat cea — Oo x Jl Debug Options Window Help apsee76, Jun 26 202i, 1S:26:21) [MSC ¥.1620 €4 Bit GM Fig.1.12 19 Introduction te Python Python [BBA (CA) - Sem. VI ‘As soon as we click on New File, the window appears as shown in Fig. 1.13. i ents =o x File Est_Farmat_Run Options Wadow Help fpr ee Sere eee ioe Hp Fig. 1.13, + Write Python program in script mode. (See Fig. 1.14) Fle_Eait_ Format Run Options Window Hel 4 chis is python procram print ("hello pythos") peine(’ dase is carer scrape”) Fig. 1.14 the filename py. Here, we save the script with file name test py. Save the above code with filename. By default, python interpreter will save it using 1 testpy-C/Uses/HP/AppDaa/LacalProgam/Pyhon/Python3tet py(395) - 0 file Edi Format fun Options Window Help # this is python program pranc ("nelle pytnos") print () This ia fart script") x Fig. 1.15 To run the Python program, click on Run and then Run Module option or we can press Ctrl+FS. ax 1 tetpy- CMses/¥® /AgpDatallecaVrogamsPythen/Pvthon3itespy 638 Fle Edit Farmat [RA] Options Window Help chs esse Run Customized Snes PARE" TRS 5 Check Module ARK Python Shel Fig 1.16 After clicking Run Module, we will get the output of program on Python shell. iD OLE Shera. Fle Ese _Shell_Debug _Optiene Window _Help a Python 3.0.6 (rage/wi.8.e:abite76, dun 28 2021, De4)} on win32 type “ne1p", "copyright", "credits" or “1icense()" for more information. > JHeti0 Python Jewen= RESTART: C: /Users/4P/appData/Local/Programs/Python/ Pythons9/tes: Jnexic python This is faze script Fig 1.47 Python [BBA (CA - Ser. V) 110 Introduction te Python Ee Basic Syntax Python progeam is set of instructions. Python programs are typically organized with one statement per line. Before to write and run @ Python program we understand structure of a Python program. ‘+ Fig. 1418 shows a typical program structure of Python programming. ‘+ Python programming programs are structured as a sequence of statements. A Python statement is smallest program unit, + Statements are the instructions that are written in a program to perform a specific task. A Python statement is a complete instruction executed by the Python interpreter. + By default, the Python interpreter executes all statements sequentially, but we can change order of execution using control statements. Documentation Section Import Statoment Global Declaration Secton Class Section Optional Daia members Member functions Subprogram Section Pisyoruna secon | Eset Tig. 1.28: Typical Program Structure of Python Programming + Program structure of Python programming contains following sections: 1. Documentation Section includes the comments that specify the purpose of the program. A comments that is a non-executable statement which is ignored by the compiler while program execution. Python comments are written anywhere in the program, 2. Import Section is used includes different built in or user defined modules. 3, Global Declaration Section is used to define the global variables for the programs. 4, Class Section describes the information about the user defined classes in the Python program. A class is a collection of data members and member functions called method that operate on data members. 5. Sub Program Section includes use defined functions. The functions include the set of statements that need to be executed when the function is called form anywhere, 6, Play Ground Section is the main section of Python program and the main section starts where the function calling. Python [BBA (CA - Ser. V) an Introduction te Python + Python has twobasic modes namely, script and interactive. 1, Interactive Mode: + The interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory. + Interactive mode is used for quickly and conveniently running single line or blocks of code. Here’s an example using the python shell that comes with a basic python installation. + The “>>>" indicates that the shell is ready to accept interactive commands. For example, if we want to print the statement “Interactive Mode", simply type the appropriate code and hit enter. 7 DLESpeIa96 =a x Fle Edt Shel Debug Opions Wodow Help fPyehon 3.9.€ (cags/v3.9.<:@B3€076, Jun 2? 2021 Dea) on wins p35 pesnetmseaio s) SS> 368, le p> peancentsceractive mode") Ferzeeire i) BSE v.1928 e Bie aw ox PLicmesth" fe nose infomation Fig. 139 2. Script Mode: * The normal script mode is the mode where the scripted and finished py files are run in the Python interpreter. ‘* In the standard Python shell we can go to “File” — “New File” (or just hit Ctrl + N) to pullupa blank script to write the code. Then save the script with a “.py” extension. ‘+ We can save it anywhere we want for now, though we may want to make a folder somewhere to store the code as we test Python out. To run the script, either select. “Run” > “Run Module" or press F5. ‘* We should see something like the following, (See Fig. 120 (a) and 1.20 (b)) 1 tetpy- Cie /AppDaialLecaVProgamd/ython?ython3Stepy 086) =o x fie Edt Fermat Ran Optons Window Help prize ("script * | Fig. 1.20 (a) i DLE Shel 386 = File_fit_Shet_Debug Options _Windew Help Python 3.9.€ (cags/v3.9.€:abatf76, Jun 28 2021, 18:26:21) [MSC v.1929 64 B} 64) ] on wins2 Type thelp", "copyright", "credits" or "License()" for more information. ssovno= RESTART: C: /Tsers/HP/AppData/Local /Progzams/Python/Python39/ test Pi script mode Fig. 1.20 (b) Python [BBA (CA - Ser. V) 12 Introduction te Python + Following simple Python program shows structure of Python program: Program 1,1: Calculate Area and Circumference of circle using class. # Documentation section inport math # import. statement radius=5 # global declaration Section class Circle(): # class section def getarea(self) return math.pi*radius*radius def getCircunference(self): return radius*2*math.pi def showradius(): # sub Progran section print ("Radius =",radius) showradius() # Playground Section c-Circle() print("Area =",c.getArea()) print("Circunference=", c.getCircumference()) Output: Radius = 5 Avea = 78,53981633974483, Circumference = 31.41592653589793 J 2.2 | BASICS OF PYTHON ‘+ In this section we will study various basic concepts if Python programming such as data types, variables, identifiers, control flow statements and so on. Data Types ‘* The type of data value that can be stored in an identifier/variable is known as its data type. + The data type determines how much memory is allocated to store data and what operations can be performed onit. * The data stored in memory can be of many types and are used to define the operations possible on them and the storage method for each of them. + Python handles several data types to facilitate the needs of programmers and application developers for workable data. + The data stored in memory can be of many types. For example, a person's age is stored as anumeric value and his orher address is stored as alphanumeric characters. + Python has various standard data types that are used to define the operations possible ‘on them and the storage method for each of them. Python [BBA (CA - Ser. V) 113 Introduction te Python + Data types in Python programming includes: 1. Numbers: Represents numeric data to perform mathematical operations. Numbers can be integers (like 1 and 2), floats (like 1.1 and 1.2), fractions (like 1/2 and 2/3), or even complex numbers. 2, String: Represents text characters, special symbols or alphanumeric data. String is sequence of Unicode characters. List: Represents sequential data that the programmer wishes to sort, merge etc. Tuple: Represents sequential data with a little difference from list 5. Dictionary: Represents a collection of data that associate a unique key with each value 6. Boolean: Represents truth values (true or false). 7. None: Python defines a special variable None denoting a “null object” + To determine a variable's type in Python programming we can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable. + Let us see above data types in detail: 1. Boolean (bool Data Type): + The simplest build-in type in Python is the bool data type, it represents the two values, ‘True and False. Internally the true value is represented as1 and false is 0. Example: vo size = 4 de> size <0 False vo» size = 0 >>> size <0 False >>> size < @ True 2. None Data Typ’ * Python defines a special variable None denoting a “null object”, which is convenient to use when a variable is available but its value is considered undefined. ‘+ None in Python is used for defining null variables and objects. None is an instance of the NoneType class Python [BBA (CA - Ser. V) 1a Introduction te Python None object is accessed through the built-in name None. It is a data type of the class NoneType object. answer = None >> ante >>> a 10 © Todetermine the type ofa variable type() function is used, >>> type(a) In Python programming one can write integers in Hexadecimal (base 16), Octal (base 8) and Binary (base 2] formats by using one of the following prefixes to the integer. Sr.No. Prefix Interpretation Base 1__| Ob’ or‘OB" Binary 2 2.__| "00" or'00" ‘octal 8 3.__[ 0x or 0X" Hexadecimal 16 Python [BBA (CA - Ser. V) 11s Introduction te Python Example: Integers in binary, octal and hexadecimal formats. >>> print (ab10111011) # binary number 187 >>> print (801) # octal nunber a >>> print (OxFF) # hexadecinal number 255 (i) Floating Point Numbers (Float Data Type): © The float data type represents the floating point number. The floating point number is a number that contains a decimal point. o Examples of floating point numbers, 0.5, -3.445, 330.44. For example, num = 2.345, © Floating-point number or Float is a positive or negative number with a fractional part. © A floating point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. For example, 1 is integer, 1.0 is floating point number. One can append the character e or E followed by a positive or negative integer tospecify scientific notation. : Floating point number. >>> x = 101 >>> y -10.5 >>>. print(72e3) 72000.0 print(7.2e-3) 0.0072 Gi) Complex Numbers (Complex Data Type): © Acomplex number is a number that is written in the form of a+bj. Here, a represents the real part of the number and b represents the imaginary part of the number. © The suffix or j after b represents the square root value of -1. The part aand b may contain the integers or floats. For example, 3+5j, 0.2+10.5j are complex numbers. © Complex numbers are written in the form, x+ yj, where x is the real part and y is the imaginary part, Python [BBA (CA - Ser. V) 16 Introduction te Python Example: Complex number. >>> x = 34g >>> print(x.real) 3.0 >>> print (x.imag) 4.0 4. String Data Type: ‘+ String is a collection of group of characters. Strings are identified as a contiguous set of characters enclosed in single quotes (") or double quotes (’”) * Any letter, a number or a symbol could be a part of the string. Strings are unchangeable (immutable). Once a string is created, it cannot be modified. ‘+ Strings in python support Unicode characters. The default encoding for Python source code is UTF-8. So, we can also say that String is a sequence of Unicode characters. ‘+ Strings are ordered. Strings preserved the order of characters inserted. Example: For string data type. >>> si="Hello™ # string in double quotes b> s2="Hi" # string in single quotes >>> s3="Don't open the door" # single quote string in double quotes >>> sd='T said "yipee"’ # double quote string in single quotes >>> sh “Hello" doo s2 oa >> 83 "Don*t open the door" ds st 'T said "yipee"’ 5. List Data Type: + Lists are the most versatile of Python's compound data types. List is an ordered sequence of items. It is one of the most used data type in Python andis very flexible + List can contain heterogeneous values such as integers, floats, strings, tuples, lists and dictionaries but they are commonly used to store collections of homogeneous objects. ‘* The list data type in Python programming is just like an array that can store a group of elements and we can refer to these elements using a single name. + Declaring a list is pretty straight forward. Items separated by commas () are enclosed within square brackets |]. Python [BBA (CA - Ser. V) a7, Introduction te Python Example: For list. >>> first=[10, 20, 38) "one", "Two", >>> secon hree" >>> first (1e, 20, 39] >>> second ‘One’, ‘Two’, 'Three'] >>> third=[10, "one" ,20, "two" >>> third (16, ‘one', 20, 'two"] >>> first + second (10, 20, 30, ‘One’, ‘Two', 'Three"] # homogenous values in list # homogenous values in list # heterogensous values in list # prints the concatenated lists ‘* Lists are mutable which means that value of elements of a list can be altered by using index. Example: For list with updation /alteration/modification, >>> Firste[10, 20, 30] >>> first[2] 30 >>> first [2]=50 >>> first (1e, 20, 59] >>> first[2] 50 >>> print (Farst*2) 1€, 20, 38, 10, 2, 30] List and Strings: # print second value in the List # change second value in the list # print second value in the list # prints the list two times * A string is a sequence of characters and list is a sequence of values, but a list of characters is not same as string. We can convert string toa list of characters. Example: For conversion of string toa list. >>> pe"Python" >>> p "Python" >>> Lelist(p) yo [Py tyty * Python [BBA (CA - Ser. V) us Introduction te Python 6. Tuple Data Type: ‘+ Tuple is an ordered sequence of items same as list. The only difference is that tuples are immutable. Tuples once created cannot be modified. + Tuples are used to write-protect data and are usually faster than list as it cannot change dynamically. Its defined within parentheses () where items are separated by commas (). + A tuple data type in python programming is similar to a list data type, which also contains heterogeneous items/elements. Example: tuple_obj=(70,2.50, "tybea") + Tuples are immutable objects whose contents cannot be altered: words = (‘flower', ‘honophone’, ‘Flour ) words[1] = ‘and’ # illegal - Python issues an error message 7. Dictionary Data Type: + Dictionary data type in Python is an unordered collection of key-value pairs. Dictionaries in Python work like associative arrays or hashes found in Perl and consist of key-value pairs. + When we have the large amount of data, the dictionary data type is used. The dictionary data type is mutable in nature which means we can update modify/update any value in the dictionary. + Items in dictionaries are enclosed in curly braces { }and separated by the comma ()). A colon () is used to separate key from value. Values can be assigned and accessed using square braces ((). Example: For dictionary data type. d9> dicte(1:"Finst™, "Second" :2) poe dict {1: ‘First", "Second >>> type(dict) celass ‘dict'> yoo deals] >>> diet {1: "First", "Second >>> dict -keys() dict_keys([1, "Second", 3]) >>> dict.values() dict_values({'First', 2, ‘Third'] 2) Third” 2, 3: 'Third’} Python [BBA (CA - Ser. V) 119 Introduction te Python + Avvariable is like a container that stores values that we can access or change. It is a way of pointing toa memory location used by a program, ‘* We can use variables to instruct the computer to save or retrieve data to and from this memory location. + Avariable isa name given toa location in the computer's memory location, where the value can be stored that can be used in the program. ‘+ When we create a variable, some space in the memory is reserved or allocated for that variable to store a data value in it ‘+ The size of the memory reserved by the variable depends on the type of data it is going to hold. The period of time that a variable exists is called its lifetime. ‘+ The variable is so called because its value may vary during the time of execution, but at a given instance only one value can be stored in it. ‘Variable Declaration: + Avariable is an identifier that holds a value. In programming, we say that we assign a value to a variable. Technically speaking, a variable is a reference to a computer memory, where the value is stored, + Basic rules to declare variables in python programming language 1. Variables in Python can be created from alphanumeric characters and underscore) character. 2. Avariable cannot begin with a number. 3. The variables are case sensitive. Means Amar is differ the 'AMAR' are two separate variables, 4, Variable names should not be reserved word or keyword. 5. Nospecial characters are used except underscore (_) in variable declaration. 6. Variables can be of unlimited length. ‘+ Python variables do not have to be explicitly declared to reserve memory space. The variable is declared automatically when the variable is initialized, i.e, when we assign avalue to the variable first time it is declared with the data type of the value assigned toit + This means we do not need to declare the variables. This is handled automatically according to the type of value assigned to the variable. The equal sign (=) ie.. the assignment operator is used to assign values to variables. + The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the literal value or any other variable value that is stored in the variable. Syntax: variable=value Example: For variable. >>> ase >a 10 >» Python [BBA (CA - Ser. V) 120 Introduction te Python ‘+ Python language allows assigning a single value to several variables simultaneously. Example: a=p=¢=1 All above three variables are assigned to same memory location, when integer object. is created with value1. ‘+ Multiple objects can also have assigned to multiple variables: Example:a, b, ¢ = 10,5.4,"hello" In above example Integer object a assigned with value 10, float object b assigned with value $.4 and string object c assigned with value “hello”. Example: If x, y, zare defined as three veriable in a program, then x = 10 will store the value 10 in the memory location named as x, y = 5 will store the value S in the memory location named as y and x + y will store the value 15 in the memory location named as z(asa result after computation of x +) >>> x = 18 poo yes >>> mame = "Python" o> zexty >>> print (x); print(y); print(nane); Print (z) 10 5 Python 15 EEE] input/output Functions * A python program needs to interact with the user to accomplish the desired task or result this can be achieved using Input-Output functions. +The input( function helps to enter data at run time by the user and the output function print() is used to display the result of the program on the screen after execution + Input means the data entered by the user/programmer in the form of program. In python, the input( function is used to accept an input from a user. Syntax: variable_nane-input() f without any argunent variable_nam Example: For input in Python, >>> input () Hello python ‘Hello python >>> x= input (“Enter data Enter data: 11.22 >>> print (x) 11.22 put(‘String’) # with argument Python [BBA (CA) -Sem. VI aa Introduction to Python + Output means the data comes from computer after processing. In Python programming the print) function display the input value on screen. Syntax: print (expression/constant/variable) Example: For output in python. >>> print ("Hello") Hello “python” >>> print (a+b) Output: Hellopython Formatting Output: ‘+ Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format() method. This method is visible to any string object. x= 10; y= 20 print('The value of x is {} and y is ()'.format(x.y)) Output: The value of x is 16 and y is 20 + Here the curly braces {) are used as placeholders. The output is printed according to the order given as follows print(‘T love {2} and {1}*.format( ‘apple’, milk')) # Output: I love apple and milk print('T love {1} and {@)' .format( ‘apple' , "milk" )) # Output: T love ilk and apple FEZ] operators Python language supports the following types of operators. o Arithmetic Operators © Comparison (Relational) Operators © Assignment Operators © Logical Operators © Bitwise Operators © Membership Operators © Identity Operators + Arithmetic, logical, Relational operators supported by Python language are same as other languages like C, C++. 1. arithmetic operators: + Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication ete. Python [BBA (CA - Ser. V) 122 Introduction te Python Operator Meaning Example + ‘Add two operands or unary plus K+y+2 = | Subtract right operand from the left or unary x-y-2 minus * | Multiply two operands xy 7 _ | Divide left operand by the right one (always x/y results into float) % | Modulus - remainder of the division of left| x %y (remainder of x/y) operand by the right + The new arithmetic operators in python are: (2) ** (Exponent) - Performs exponential (power) calculation on operators Example: a’*b = 10 to the power 20. (0) // (Floor Division) - The division of operands where the result is the quotient in which the digits after the decimal point are removed. But if one of the operands is negative, the result is floored, ie., rounded away from zero (towards negative infinity) Example: 9//2 = 4 and 9.0//2.0 Program 1.2: For arithmetic operators we will take simple example of addition. 15 4 print('x + y =".x+y) # output: x + y = 19 print(*x - y =",x-y) # Output: x - y = 11 print('x * y =",x*y) # Output: x * y = 60 print('x / y ="yx/y) # Output: x / y = 3.75 print(*x // y =",x//y) # Output: x // y = 3 print(*x *# y =") x*#y) # Output: x ** y = 50625 2. Logical operators: + The logical operators are used to perform logical operations like (and, or, not) and to combine two or more conditions to provide a specific result i.e. true or false. Operator Meaning Example and _| True if both the operands are true | xandy or ___| True if either of the operands is true xory not __ | True if operand is false (complements the operand) not x Python [BBA (CA - Ser. V) 123 Introduction te Python Program 1.3; For Logical operators we will take simple example. x24 print (x print (x > 2 and x < 18) > 2or x < 18) print (not(x > 10)) Output: True True True 3. Relational /Comparison operators: + Comparison operators are used to compare values. It either returns True or False according to the condition. Operator Meaning Equal to - True if both operands are equal Not equal to - True if operands are not equal <__| less than- True if left operand is less than the right xey <= | Less than or equal to - True if left operand is less than or | x<=y equal to theright > __| Greater than - True if left operand is greater than the right xy Greater than or equal to - True if left operand is greater than | x>=y | or equal to the right <> | This is new Relational operator in Python. If values of two | x<>y operands are not equal, then condition becomes true. Program 1.4: For Relational operators. yee print (x print (x print (x print (x print (x print (x Output: False True Toue False False True returns False because 4 is not equal to 2 returns True because 4 is greater that to 2 seaaae returns True because 4 is not equal to 2 returns True because 4 is greater that equal to 2 returns False because 4 is not less that to 2 returns False because 4 is not less that equal to 2 Python [BBA (CA - Ser. V) 124 Introduction te Python 4, Assignment Operators; ‘+ Assignment operators are used in Python to assign values to variables. + a =5 is a simple assignment operator that assigns the value 5 on the right to the variable a on the left. + There are various compound operators in Python like a 4= $ that adds to the variable and later assigns the same Itis equivalent to a=a +5. ‘+The following are assignment operators in python. Operator Example oli xe 2 print (x) y+ print(y) z=9 2/23 print(z) a-2 a /i=3 print(a) bes bts 3 print (ey Output: 8 1s 3.0 4 as. Python [BBA (CA - Ser. V) 125 Introduction te Python 5. Bitwise Operators: ‘+ _Bitwise operators act on operands. It operates bit by bit, hence the name is bitwise. + For example, 2 is 10 in binary and 7 is 111 +The following are bitwise operators in python which are same as in C C++, Operator Meaning & _| bitwise AND: Sets each bit to 1 if both bits are 1 bitwise OR: Sets each bit to 1 if one of two bits is 1 ‘®_| bitwise XOR: Sets each bit to if only one of two bits is 1 ~__| bitwise nor: Inverts all the bits << | bitwise left shift: Shift left by pushing zeros in from the right and let the leftmost bits falloff >> | bitwise right shift: Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off Special Operators: + Python language offers some special type of operators like the identity operator or the membership operator. They are described below with examples. 1, Identity operators + sand 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. Operator | Meaning Example is ‘True if the operands are identical (refer to the same object) _| xis True isnot | True if the operands are not identical (do not refer to the | xis not True same object) Program 16: For Identity operators m5 yles x2 = 'Hello’ y2 = ‘Hello’ x3 = [1,2,3] yo = [42,3] print(xi 1s not 2) # Output: False print(x2 is y2) # Output: True print(x3 is y3) # Output: False Python [BBA (CA - Ser. V) 126 Introduction te Python ‘+ Here, we see that x1 and y1 are integers of same values, so they are equal as well as identical. Sameis the case with x2 and y2 (strings). + But x3 and y3 are list. They are equal but not identical. It is because interpreter locates them separately in memory although they are equal. 2. Membership operators ‘+ im and not in are the membership operators; used to test whether a value or variable isina sequence. (string, list, tuple, set and dictionary). Ina dictionary we can only test. for presence of key, not the value. Operator Meaning Example in ‘True if value/variable is found in the sequence Sinx notin ‘True if value/variable is not found in the sequence | 5 notinx Program 1.6: For Membership operators. x = ‘Hello world’ = {4:'a",2:'b'} print('H' in x) # Output: True print(‘hello" not in x) # Output: True print(1 in y) # Output: True print(‘a’ in y) # Output: False * Here, ‘Ht is in x but ‘hello’ is not present in x (remember, Python is case sensitive). Similarly, 11s key and ‘a’ is the value in dictionary y. Hence, ‘a’ in y returns False. rl CONDITIONAL STATEMENTS-IF, IF-ELSE, NESTED IF-ELSE Python programming language provides following types of decision making statements. (i) Ifstatement: if statement is the most simple decision making statement. It is used to decide whether a certain statement or block of statements will be executed or not ie. if a certain condition is true then a block of statement is executed otherwise not. syntax: Af expression: statement (s) ‘+ Afew important things to note about if statements: 1. The colon (:) is significant and required. It separates the header of the compound statement from the body. 2. Theline after the colon must be indented. It is standard in Python to use four spaces forindenting. Python [BBA (CA - Ser. V) 127 Introduction te Python Program 1,7; Program for if statement, a=10 b= 20 if b >a: print("b is greater than a") Output: b is greater than a (ii) IE-ELSE Statements: * Else is also called a two-way selection statement, because it leads the program to make a choice between two alternative courses of action. Syntax: if expression statenent(s) else: statement (5) Program 1.8: Program for else statement. a= 30 b= 20 ifboa: print("b is greater than a") else: print("a is greater than b") Output: a is greater than b Program 1.9: Write a program to check whether the number N is even or odd. Naa if NX == 0: print(*Number is Even') else: print(* Number is odd") output: Number is Even (iii) IF...ELIF...ELSE Statements: © When a program contains seversl testing conditions that involve more than two alternative course of action. In multi-way if statements program checks each condition until one evaluates to true or all evaluate to false. When a condition evaluates to True, the corresponding action of condition is took place. If no condition satisfy means evaluate to true then the corresponding action of trailing else is performed. Python [BBA (CA - Ser. V) 128 Introduction te Python Syntax: if expression sequence of statenents-1 elif condition- sequence of statenents-n else: default sequence of statements Program 1,10: Program for IF...ELIF...ELSE Statements. as4 b if boa print("b is greater than a") elif a=: b: print("a and b are equal") else: print("a is greater than b") output: a and b are equal (iv) Nested IF-Else Statement: + Anested if is an if statement that is the target of another if statement. Nested if statement means an if statement within another if statement. syntax: if (): statement (s) if (): statements) else else: if (): statement(s) else Statement (s) Program 1,11: Program for Nested if-else Statements. a= -10 fare print("Positive Number") Python [BBA (CA - Ser. V) 129 Introduction te Python else: print(“Negative Number”) nested if if -10 <= a: print("Two digit Negative Number") ‘Output: Negative Number Two digit Negative Number -& LOOPING-FOR,WHILE,NESTED LOOPS * Ina situation where you need to execute a block of code several number of times, Programming languages provide control statements with repetition statements Known as loops, which repeat an action. 1. while loop: + A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. In while loop, condition is checked first. The body of the loop is entered only if the condition evaluates to True. After one iteration, the condition is checked again. This process continues until the condition evaluates to False. syntax: while condition: statement(s) Program 1.12: Write a program to display numbers from 1to 10. tea while i <1: print(i) i¢ea. output: a 2 3 4 5 6 7 8 9 Python [BBA (CA - Ser. V) 130 Introduction te Python 2. for loop: + The “for” loops in Python executes a certain block of code for a known number of iterations. The speciality of “for” loop in Python is that the block of code can be iterated for the number of items existing within a list, dictionary, string variable, over a particular range of numbers in counted number of steps, and for the number of items existing in a tuple. It has the ability to iterate over the items of any sequence, such asa list ora string. Syntax: for iterating var in sequence: statements (s) + Iterating by Sequence Index: An alternative way of iterating through each item is by index offset into the sequence itself. + syntax: for i in [Python Iterable]: expression(i) Example: Here “Python Iterable’ can be a list, tuple or other advanced data structures. for x in"Hi': print x Program 1.13: Example for “for” statement. fruits = ["apple”, “banana”, “cherry"] for x in fruits: print (x) for letter in 'Python" print(letter) print("Good bye!" Output: apple banana cherry P Good bye! y Good bye! t Good bye! h Good bye! ° Good bye! n Good bye! Python [BBA (CA - Ser. V) 131 Introduction te Python Iterating by Subsequence Index: * The function range() generates lists containing arithmetic progressions. * We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers), We can also define the start, stop and step size as range(start,stop,step size). step size defaults to 1if not provided. Syntax: range(start-value, end-value, difference between the values) ‘+ This function does not store all the values in memory, it would be inefficient, So it remembers thestart, stop, step size and generates the next number on the go + We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate though a sequence using indexing. Program 1.14: Program to iterate through a list using indexing. genre = [‘Folkl', ‘Classical’, ‘jazz'] # iterate over the list using index for i in range(len(genre)): print("Z like", genre[i]) Output: I like Folk I like Classical T like jazz + Python has another range function called xrange() Syntax: xrange(start-value, end-value, difference between the values). + The xrange() allowing the memory to be freed, when the range list is not in use because xrange() populates its range list whenever it is accessed by means of such as for loop. 3. Nested loops: + When you have a block of code you want to run x number of times, then a block of code within that code which you want to run y number of times, you use what is Known as a ‘nested loop". In Python, these are heavily used whenever someone has a list of lists - an iterable object within an iterable object. Program 1.15: Program for Nested loops. num_list = [1, 2, 3] alpha_list = ['a', 'b', 'c'] for nunber in num_list: print (number) for letter in alpha_list: print(letter) Python [BBA (CA - Ser. V) 132 Introduction te Python Output: 1 ra CONTROL STATEMENTS-BREAK, CONTINUE, PASS Python supports the following Loop Control Statements: 1. break Statement: + Break statement is a jump statement which is used to transfer execution control. It breaks the current execution and in case of inner loop, inner loop terminates immediately and resumes execution at the next statement. The break statement can be used in both whileand for loops. Syntax: break Program 1.16: Example for break statement. for letter in 'sybca': if letter == 'b': break print('Current Letter:', letter) Output: Current Letter: s Current Letter: y Program 1,17: Example for break statement. var = 10 while var > @: print(‘Current variable value:', var) var = var -1 if var break print(*Out loop") Python [BBA (CA - Ser. V) 133 Introduction te Python Output: Current variable value: 1 Current variable value: 9 Current variable value: 8 out loop 2. continue Statement: + It returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops. Syntax: Continue Program 1.11 for letter in ‘Sybea if letter == "b continue :xample for continue statement. print( ‘Current Letter:', letter) Output: Current Letter: 5 Current Letter: y Current Letter: ¢ Current Letter: a Program 1.1: :xample for continue statement. while var > ©: var = var -1 if var == 3: continue print("current variable value:", var) print(‘In loop") Output: Current variable value: 4 In loop Current variable value: 2 In loop Current variable value: 1 In Joop Current variable value: @ In loop Python [BBA (CA - Ser. V) 134 Introduction te Python 3, pass Statement: + It Is used when a statement is required syntactically but you do not want any ‘command or code to execute. The pass statement is a null operation; nothing happens when it executes. Syntax: pass Program 1.20: Example for pass statement. for letter in ‘sybca": if letter == 'b': pass print("This is pass block") print( ‘Current Letter: Output: This is pass block Current Letter: S letter) This is pass block Current Letter: y This is pass block Current Letter: b This is pass block Current Letter: ¢ This is pass block Current Letter: a STRING MANIPULATION-ACCESSING STRING, BASIC OPERATIONS, STRING SLICES, FUNCTION AND METHODS, EXAMPLES * A Python string is a sequence of characters. Python Strings are immutable (unchanging) sequences of Unicode points. # all of the following are equivalent Examples my_string = ‘Hello’ print (my_string) my_string = "Hello" print(my_string) my_string = ''‘Hello'** print(my_string) Python [BBA (CA - Ser. V) 135 Introduction te Python # triple quotes string can extend multiple Lines my_string = "*"Hello, welcome to the world of Python’ print (ny_string) When you run the progran, the output will be: Hello Hello Hello Hello, welcome to the world of Python String Representation * In Python, Strings are stored as individual characters in a contiguous memory location, + The benefit of using String is that it can be accessed from both the directions (forward and backward). + Both forward as well as backward indexing are provided using Strings in Python. © Forward indexing starts with 0,2,2,3 © Backward indexing starts with -1, Example: Forward Indexing Oo 40 2 3 4 58 arf P ] Y Pt ] 4] 0 7 N}—Backward Indexng . 5 8 3 2 ot Fig. 1.22 str[0] « 'P = str[-6}, str{a] = 'Y'= str(-s], str[2] <'T ‘o' = str[-2], str{5] tr[-1]. | Accessing String Python does not support a character type; these are treated as strings of length one, thus also considered a substring. Square brackets can be used to access elements of the string, = str[-4], str[3] = str[-3], str[4] = ‘+ We can access individual characters using indexing and a range of characters using slicing. Index starts from 0. Trying to access a character out of index range will raise an IndexError. The index must be an integer. We can't use floats or other types, this will result into TypeError. Python allows negative indexing for its sequences. ‘The index of -1 refers to the last item, -2 to the second last item and so on. Python [BBA (CA - Ser. V) 136 Introduction te Python Program 1.21; Accessing values in strings. msg = ‘Hello World!" #first character print (*nsgi[o]~ ", msg1{o}) Wlast character print("nsgi[-1] - *, megi[-1]) output: msgife]= H msgif-1]= | Basic Operations + Assume string variable a holds ‘Hello’ and variable b holds ‘Python’, then: Operator Deseription Example + | Concatenation- Adds values oneither | a+ b give output as HelloPython side of the operator «| Repetition - Creates new strings, a°2 give output as -HelloHello concatenating multiple copies of the same string {| Slice - Gives the character from the | aft] give outputase given Index [:] | Range of Slice - Gives the characters | a[1:4] give output as ell from the given range in| Membership - Returns true if a | Hina given output asi character exists in the given string notin | Membership - Returns true if a | Mnot inagivenoutputas1 character does not exist in the given string % _| Format - Performs String formatting Program 1.22: Python program for concatenation of two strings. stri = "Hello! str? ="World!' # using + Operator print(‘sted + str2 = ', stra + str2) output: str] + str2 = HelloWorld! * The “slice” syntax is a handy way to refer to sub-parts of sequences -- typically strings and lists. The slice s[start:end] is the elements beginning at start and extending up to but not including end. * We can access a range of items in a string by using the slicing operator :(colon). Python [BBA (CA - Ser. V) 137 Introduction te Python As an alternative, Python uses negative numbers to give easy access to the chars at the end of the string: s[-1] is the last char'o’, s[-2] is '' the next-to-last char, and so on. Example: Suppose we have s = "Hello [1:4] is'ell'-- chars starting at index 1 and extending up to but not including index 4 s ‘ello’ - omitting either index defaults to the start or end of the string s[}] is 'Hello’ -- omitting both always gives us a copy of the whole thing (this is the pythonic way to copy a sequence like a string or list) s[-1]is'o' -- last char (1* from the end) sl-4]is'e’ 4 from the end Program 1.23: Program for array slicing msg1 = ‘Python’ print ("msgi[1:S] = ", mega[1:5]) Output: msgi[1:5] = ytho (ER2] Function and Methods Python has several built-in functions and methods associated with the string data type. In Python, the following built-in functions and methods used to manipulate and modify strings. 1. Capitalize(): Capitalizes first letter of string 2. count{str, beg= 0, end=len(string)): Counts how many times str occurs in string or in a substring of string if starting index beg and ending index end are given. 3. endswith(suffix, beg=0, end=len(string)): Determines if string or a substring of string (if starting index beg and ending index end are given) ends with suffix; returns true if so and false otherwise. 4, isalnum): Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise. 5. isalpha(): Returns true if string has at least 1 character and all characters are alphabetic ané false otherwise. 6. isdigit(): Returns true if string contains only digits and false otherwise. 7. islower(): Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise. 8. isnumeric(): Returns true if a unicode string contains only numeric characters and false otherwise. 9. isspace(): Returns true if string contains only whitespace characters and false otherwise, 10, istitle(): Returns true if string is properly "titlecased” and false otherwise. 11. isupper(): Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise Python [BBA (CA - Ser. V) 138 Introduction te Python 12, join(seq): Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string, 23. len(string): Returns the length of the string. 14, Ijust(width{, fillchar)): Returns a space-padded string with the original string left-justified to a total of width columns. 15. lower(): Converts all uppercase letters in string to lowercase. 16. Istrip(): Removes all leading whitespace in string. 17. maketrans);: Returns a translation table to be used in translate function. 18, max(str): 49. min(str): Returns the min alphabetical character from the string str. 20, replace(old, new [, max}}: Replaces all occurrences of old in string with new or at ‘most max occurrences if max given. 21. rfind(str, beg=0,end=len(string)): Same as find), but search backwards in string. 2, rjust(width,[, fillchar)): Returns a space-padded string with the original string right-justified to a total of width columns. 23. rstrip(): Removes all trailing whitespace of string. 24. split(str=", num=string.count(str)): Splits string according to delimiter str (pace if not provided) and returns list of substrings; split into at most num substrings if given. 25. splitlines(aum~string.count(\n'): Splits string at all (or num) NEWLINEs and returns 2 list of each line with NEWLINEs removed 26. swapcase(): Inverts case for all letters in string. 27. titleQ): Returns “titlecased” version of string, that is, all words begin with uppercase and the restare lowercase. 28. translate(table, deletechars=""): Translates string according to translation table str(256 chars), removing those in the del string. 29. upper(): Converts lowercase letters in string to uppercase. E.g print s.upper() #s is string. 30. zfill(width): Returns original string leftpadded with zeros to a total of width characters; intended for numbers, zfill( retains any sign given (less one zero), 31. isdecimal(): Returns true if a unicode string contains only decimal characters and false otherwise. 32, center(width, fillchar): Returns a space-padded string with the original string centered toa total of width columns. jeturns the max alphabet -al character from thestring str. 33. encode(): Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with ‘ignore’ or ‘replace’. 34, index(): Returns Index of Substring 35, find(str, beg=0 end=len(string)): Determine if str occurs in string or in a substring of string if starting index beg and ending index end are given returns index if found and -1 otherwise. Python [BBA (CA - Ser. V) 139 Introduction te Python Program 1.24; Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string length is less than 2, return instead of the empty string. stringsraw_input(“Enter string:") count=3 for i in string: count=count+1 new-string[@:2]+string[ count-2:count] print("Newly formed string is:*) print(new) Output: Enter string: Hello world Newly formed string is: Held Examples: Program 1.25: Write a Python program to get a string from a given string where all occurrences of its first char have been changed to's’. strlinput:{"Enter a String:",} print ("Original String:",strl) char = stra[o] str1 = stri.replace(char, '$') sted = char + stri[1:] print ("Replaced String:",ste1} Output: Enter a String: onion Original String: onion Replaced String: onign Program 1.26: Python Program to Replace all Occurrences ofa’ with $ in a String, string=raw_input(“Enter string:”) stringsstring. replace('a','$") string=string.replace(‘A','$") print ("Modified string:") print (string) Output: Enter string:Asia Modified string: $sif Python [BBA (CA - Ser. V) 140 Introduction te Python Program 1.27; Write a python program to count repeated characters in a string Sample string: ‘thequickbrownfoxjumpsoverthelazydog import collections stri = 'thequickbrownfoxjumpsoverthelazydog' d = collections defaultdict (int) for ¢ in stra atc] #1 for ¢ in sorted(d, key.d.get, reverse.True): if d[c] > 1: print('%s %d" % (c, dic])) Output: zen NNNNw LISTS-INTRODUCTION, ACCESSING LIST, OPERATIONS, WORKING WITH LISTS, FUNCTION & METHODS * APython list isa mutable sequence of data values called items or elements. An item can be of any type. List is one of the most frequently used and very versatile datatype used in Python Creating Elements ina Li ‘+ In Python programming, a list is created by placing all the items (elements) inside a ‘square bracket [ ], separated by commas. + Itcan have any number of items and they may be of different types (integer, float, string etc). Fes Syntax: <1ist_nane>=[valuel, value?, value3, ... ,valuen] Empty List: Listt = [] + The empty Python list is written as two square brackets containing nothing. Examples of different lists: list1 = ['C', ‘java", 2016, 2018] # the items in a list need not be of the same type. list2 = [1, 2, 3, 4,5] "tet, "d"] Python [BBA (CA - Ser. V) 1a. Introduction te Python Example: Listi = [“apple", “benana”, “cherry ] print (Lista) Output: ['apple", "banana", “cherey"] Accessing List + There are various ways in which we can access the elements of a list List Index: * We can use the index operator[ ] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4. ‘+ Trying to access an element other that this will raise an IndexEtror. The index must be an integer. We can't use float or other types, this will result into TypeError. Negative Indexing: + Python allows negative indexing for its sequences. The index of -1 refers to the last. item, -2 to the second last item and soon. Slicing List: + We can access a range of items in a list by using the slicing operator: (colon). ‘* Slicing can be best visualized by considering the index to be between the elements. So if we want to access a range, we need two index that will slice that portion from the list, + Basic Syntax to Access Python List is: « [index] Examples: list4=[1,2,3,4] List2=['a','b',"e'] print(List1[6]) print(1ist1[@:2]) print(List2[-3:-1]) print(list1[@:]) print(1ist2[:2]) Output: 1 1, 2] bY 4, 2, 3, 4] tat, ‘b'] Python [BBA (CA - Ser. V) az Introduction te Python List Operation ‘+ Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result isa new list, not a string. ‘* In fact, lists respond to all of the general sequence operations we used on strings in the previous section. Python Expression Results Description len((4, 5, 6, 7)) 4 Length (1, 2,3]+ 14,5, 6] 11,2,3,4,5, 6] Concatenation (Hit) *3 (Hil, "Hil Hil] Repetition 3in(1,2,3] True Membership for iin[1, 2,3]: printi, 123 Iteration Working with Lists Updating List + The single or multiple elements of lists can be updated by giving the slice on the left- hand side of the assignment operator. i.e. We can use assignment operator (-) to change an item ora range of items. ‘* We can add one item to a list using append() method or add several items using extend() method, ‘+ We can also use + operator to combine two lists. This is also called concatenation. + The* operator repeats a list for the given number of times. Example: list = ['c', ‘java’, 2016, 2618]; print("Value available at index print(List1[2]) list1[2]= 200 print(List1) Output: Value available at index 2: 2016 ('C', "java", 200, 2018] Example: List2 - ["apple", “banana”, “cherry"]5 List2.append( "orange"; print(1ist2) Output: ("apple", "banana", "cherry", “orange”] Python [BBA (CA - Ser. V) 143 Introduction te Python EEPI vetete ist ‘We can delete one or more items from a list using the keyword del. It can even delete the list entirely. We can use del statement{ if you know exactly which elements you are deleting). We can use remove() method to remove the given item or pop) method to remove an item at the given index. The remove() method is used to delete the elements from allist if we do not know which element we are deleting, ‘The pop() method removes and returns the last item if index is not provided. This helps us implement lists as stacks (first in, last out data structure). We can also use the clear() method to empty alist. Example: list = ['c', "java', 2616, 2618]; print list del list [2]; print “After deleting:", list List. remove (“Java’); print list Output: ['c', ‘java', 2816, 2018) After deleting: ['¢', ‘java’, 2018] "ch, 2618] E21 Functions and Methods Python includes the following list Functions: + all: Return True if all elements of the listare true (or if the list is empty). * any(): Return True if any element of the list is true, If the list is empty, return False. + enumerate): Return an enumerate object. It contains the index and value of all theitems of list as a tuple * len(: Return the length (the number of items) in the list. * _ list(: Convert an iterable (tuple, string, set, dictionary) to alist. + max(): Return the largest item in thelist. + min(): Return the smallest item in the list. + sorted(): Return a new sorted list (does not sort thellist itself). + sum(); Return the sum of allelements in the list Python includes following list methods: * list.append(obj + list.count(obj ppends object obj to list. turns count of how many times obj occurs in list. Python [BBA (CA - Ser. V) aa Introduction te Python + list.extend(seq): Appends the contents of seq tollist. + list.index(obj): Returns the lowest index in list that obj appears. + list.insert(index, obj): Inserts object obj into list at offset index. + list.pop(obj-list[-1]): Removes and returns last object or obj from list. + list.remove(obj): Removes object obj from list. + list.reverse(: Reverses objects of list in place + listsort({func)): Sorts objects of list, use compare func if given. + clear: Removes all items from the list. + copy): Returns a shallow copy of the list Program 1.28: For list methods. Ast = [123, ‘xyz", ‘par’, ‘abe’, "xyz"]5 Ist.reverse(); print("List: ", Ist) print("Count for 123: “, Ist. count(123)) print(“count for xyz: “, Ist.count( xyz") Ist renove(‘xyz") print("List: ",Ist) Ist.renove(*abe") print("List: ", 1st) Ist.pop() print (Ist) Output: List: [aye", "abe", “par, ‘xyz, 123) Court for 123: 4 Count for xyz: 2 List: ["abc", ‘par’, ‘xyz', 123] List: ['par*, ‘xyz’, 123] Cpar's xyz") TUPLE-INTRODUCTION, ACCESSING TUPLES, OPERATIONS WORKING, FUNCTION AND METHODS, EXAMPLES + A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets. This Python Data Structure is like a list in Python, is a heterogeneous container for objects. ‘+ The differences between tuples and lists are, we cannot change the elements of a tuple once it is assigned whereas in a list, elements can be changed. This means that while you can reassign or delete an entire tuple, you cannot do the same to a single item ora slice. Tuples use parentheses, whereas lists use square brackets. Python [BBA (CA - Ser. V) 14s Introduction te Python Advantages of Tuple: 1, Processing of Tuples are faster than Lists. 2. It makes the data safe because tuples are immutable and hence cannot be changed. 3. Generally tuples are used for heterogeneous (different) datatypes and list for homogeneous (similar) datatypes. 4, Tuples are used for String formatting. Difference between Tuples and 1. The syntax of tuples is shown by parenthesis) whereas the syntax of lists is shown by square brackets[ J. List has variable length, tuple has fixed length. List has mustable nature, tuple has immutable nature. List has more functionality than the tuple. ‘Typles are heterogeneous while lists are homogeneous. One has to deal individually with the items 6. Tuples showr structure whereas lists show order. Creating Tuple: ‘+ Atuple is created by placing all the items (elements) inside a parentheses ), separated by comma. The parentheses are optional but is a good practice to write it. A tuple can have any number of items and they may be of different types (integer, float, list, string etc). + For example waAwN tupl = ("apple", "orange", 2018); tup2 = (1, 2, 3, 4, 5): tup3 = "a", i ‘+ Theempty tuple iswritten as two parentheses containing nothing, tupl = 03 + To write a tuple containing a single value you have to include a comma, even though there is only onevalue: tupl = (58,); ‘+ Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and soon. Program 1.29: Python program for creating Tuples # enpty tuple my_tuple = () print (ny_tuple) # tuple having integers my tuple = (1, 2, 3) print (my_tuple) Python [BBA (CA - Ser. V) 146 Introduction te Python # tuple with nixed datatypes my_tuple = (1, "Hello", 3.4) print (my_tuple) # nested tuple my_tuple = (“Hello”, [8, 4, 6], (2, 2, 3)) print (my tuple) # tuple can be created without parentheses also called tuple packing my_tuple = 3, 4.6, “tybca” print (my_tuple) # tuple unpacking is also possible a, by ¢ = my_tuple print (a) print (b) print(e) output: G, 2. 3) (1, "Helle", 3.4) (CHello', [8, 4, 6], (1, 2, 3)) G, 4.6, ‘tybea") tybea EET Accessing Tuples To access values in tuple, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example: tupl = ("appli tup2 = (1, 2, 3, 4, 5, 6,7) print “tupi[e]: ", tupi[e] print “tup2[1:6]: ", tup2[a:6] » Torange", 2018); When the above code is executed, it produces the following result: ‘tupi[@]: apple ‘tup2[1:6 Python [BBA (CA - Ser. V) 147 Introduction te Python + Python Tuple Packing Python Tuple packing is the term for packing a sequence of values into a tuple without using parentheses. >>> mytuple=1,2,3 #0r it could have been nytuple= >>> mytuple + Python Tuple Unpacking 22,3 ‘The opposite of tuple packing, unpacking allots the values from a tuple into a sequence of variables. >>> a,b,c = nytuple >>> print (a,b,c) 123 222] Tuple Operations Tuples respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new tuple, not a string. The various operations that we can perform on tuples are very similar to lists. 1. Concatenation: + Using the addition operator +, with two or more tuples, adds up all the elements into a new tuple. Example: (1,2, 3) + (4.5.6) Output: (1,2,3,4,5, 6) 2. Repetition: ‘* Multiplying a tuple by any integer, x will simply create another tuple with all the elements from the first tuple being repeated x number of times. For example, t'3 means, elements of tuple t will be repeated 3 times. Example: ('Hi!",) * 4 Output: (HIE, CHEE, CHAE, “HAI*) 3. Tuple Membership Test using in keyword: + In keyword, can not only be used with tuples, but also with strings and lists too. It is used to check, if any element is present in the sequence or not. It returns True if the element is found, otherwise False. Example: #in operation tup = (‘a","p',"p", "1", "e',) print(‘a’ in tup) # Output: True print("b' in tup) # Output: False # Not in operation print(‘g' not in tup) # Output: True Python [BBA (CA - Ser. V) 14s Introduction te Python 4, Iterating Through a Tuple: Using a for loop we can iterate though each item ina tuple. Example: for name in (‘mom', "dad" ): print ("Hel 0" ,nane) output: # Hello mon # Hello dad Python Expression Results | DescriptionLength | (4.2.3) + (4,5, 6) (.2.3,4,5, 6) Concatenation (Hil) "4 (Hi!, "Hi 'Hi!’) | Repetition 3in (1,2,3) True Membership forx in (1, 2, 3): print x, 123 Tteration Updating Tuple Tuples are immutable which means you cannot update or change the values of tuple elements. You are able to take portions of existing tuples to create new tuples as the following example demonstrates: tupl = (1, 32.76) tup2 = (‘abe", ‘xy2") # tupl[e] - 100 4s not valid # So create a new tuple as follows tup3 = tupl + tup2 print tup3 When the above code is executed, it produces the following result: (1@, 22.76, ‘abe", ‘xy2") + Wecan use + operator to combine two tuples, This is also called concatenation, * We can also repeat the elements in a tuple for a given number of times using the * operator, >> (L) 85 (1,1, 1, 1, 1) «Both +and * operations result into a new tuple. Deleting Tuples Deleting Tuple: * Removing individual tuple elements is not possible. There is, of course, nothing wrong with putting together another tuple with the undesired elements discarded. Python [BBA (CA - Ser. V) 149 Introduction te Python + Toexplicitly remove an entire tuple, just use the del statement. ‘Example: tup = ("apple”, “orange”, 2018); print tup del tup print “After deleting tup: print tup Output: (apple’, ‘orange’, 2018); after deleting twp: Traceback (most recent call last): File "test.py", Line 5, in T2, then cmp(T1, T2) returns 1 + if T1= 12, then cmp(T4, 72) returns 0 + if T1>12,thencmp(?4, 12) returns -1 2. len(tuple): © This function is used to get the number of elements inside any tuple. Example: len((1, 2, 3)) output: 3 3. max(tuple): Returns item from the tuple with max value. 4, min(tuple): Returns item from the tuple with min value, 5. tuple(seq): This method converts a list of items into tuples. Program 1.31; Python program for built in Tuple function, alist atuple print( ‘# use of max() method: (Coxyz'y “par’, ‘abe")5 tuple(aList) uple elements: ", aTuple) print ("Max value element: ", max(aTuple)) # use of min() method: print("Max value elenent: “ # use of len() metho tuplel, tuple2 = ('xvz", 'par','spq'), (45@, ‘abe") » min(aTuple)) print("Finst tuple length: ", len(tuplet)) print("Second tuple length: ", len(tuple2)) Output: Tuple elements: (‘xy2", ‘par’, ‘abc') Max value elenent: xyz Max value elenent: abe First tuple length: 3 Second tuple length: 2 Python [BBA (CA - Ser. V) 1s. Introduction te Python Methods: Python Tuple Methods: + Amethod is a sequence of instructions to perform on something. Unlike a function, it does modify the construct on which it is called. You call a method using the dot operator in python. Python has two built-in methods that you can use on tuples. 1. index(x): Return index of first item that is equal to x. Example: >>> a=(1,2,3,2,4,5,2) >>> avindex(2) Output: 1 As youcan see, we have 2sat indices 1, 3, and 6. But it returns only the first index. 2. Count(x): Return the number of items is equal tox. Example: >>> a=(1,2,3,2,4,5,2) >>> a. count (2) Output: 3 Program 1.32: Write a Python program to create a list of tuples with the first element as the number and second element as the square of the number. L_range=int(input(“Enter the lower range:")) u_range=int(input ("Enter the upper range:")) a=[(x,x**2) for x in range(1_range,u_range#1)] print (a) Output: Enter the lower range:1 Enter the upper range:4 [(4, 1), (2 4), G, 9), , 16)1 Examples: Program 1.33: Write a Python program to add an item in atuple. Hereate a tuple tuplex = (4, 6, 2. 8. 3, 1) print(tuplex) Htuples are inmutable, so you can not add new elements fusing merge of tuples with the + operator you can add an element and it will create a new tuple tuplex = tuplex + (9,) print(tuplex) Hadding itens in a specific index Python [BBA (CA - Ser. V) 12 Introduction te Python tuplex = tuplex[:5] + (15, 20, 25) + tuplex[:5] print (tuplex) converting the tuple to list listx = list(tuplex) Wuse different ways to add itens in list Listx.append (36) tuplex = tuple(listx) print (tuplex) Output: (6 2,8 3D G, 6, 2, 8 3, 1, 9) Gy 6 2, 8, 3, 15, 28, 25, 4, 6, 2, 8 3) (4, 6, 2, 8 3, 15, 2, 25, 4 6 2, 8, 3, 38) Program 1.34: Write a Python program to convert a tuple to a string. tup = (let, fet, fet, tet, tet fet, tet, ts") str = '".jobn(tup) print(str) Output: Program 1.35: Write a Python program to get the 4 element from front and 4* element from last of a tuple wet an iten of the tuple tuplex = ("p", "y", print(tuplex) Get iten (4'" element)of the tuple by index iten = tuplex(3] print (item) Get iten (4' element from last)by index negative item1 = tuplex[-4] print (item) Output: Cis ys TE, TN, Or, Tm, “DY, “Or, TO", KD h b Python [BBA (CA - Ser. V) 153 Introduction te Python Program 1.36; Write a Python program to find the repeated items of a tuple. create a tuple tuplex = 2, 4, 5, 6, 2,3, 4, 4,7 print (tuplex) fiveturn the number of times it appears in the tuple count = tuplex.count(4) print (count) Output: (2, 4, 5, 6 2, 3, 4, 4 7) 3 Program 1,37: Write Python program to check whether an element exists within a tuple. tuplex 3, 7r print("r" in tuplex) print(S in tuplex) output: True False DICTIONARIES-INTRODUCTION, ACCESSING VALUES IN DICTIONARIES, WORKING WITH DICTIONARIES, PROPERTIES, FUNCTION, EXAMPLES * A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. + Dictionariesare optimized to retrieve values when the key is known. + Dictionaries are Python's implementation of a data structure that is more generally known asan associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the key to its associated value, Creation of Dictionary: + Creating a dictionary is as simple as placing items inside curly braces {} separated by ‘comma, An item has a key and the corresponding value expressed as a pair, key: value. + Each key is separated from its value by a colon (}, the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: (} * Keys are unique within a dictionary while values may not be. The values of a dictionary can be of any type, but the keys must be of an immutable data type such as strings, numbers, or tuples. Python [BBA (CA - Ser. V) 154 Introduction te Python Syntax: dictionary_name = { : , : , ckey>: } dictionary_name = dict([ (ckey>, ), (, , (key] Example: dict = (Name's ‘abet, ‘Age’: 20, ‘Class: ‘tybea'} print “dict['Nane"]: ", dict{'Nane") print “dict[‘Age"]: ", dict[ Age" ] Output: dict["Nome"]: abe dict["Age']: 20 If we attempt to access a data item with a key, which is not part of the dictionary, we get an error. dict = (*Name': ‘abc', ‘Age’: 28, ‘Class': ‘tybea'} print “dict['xyz"]: ", dict[yz"] Output: dict[*xyz"]: Traceback (most recent call last) File “test.py", line 2, in print “dict['xyz']: " KeyError: "xyz" EEEy Working with Dictionaries dict['xyz"]5 | updating Dictionary A dictionary can be updated by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below: Program 1,38: dict = ('Name': ‘abe', ‘Age: 20, 'Class': ‘tybca'} dict[‘Age"] = 22 5 # update existing entry dict[ ‘College’ ] = "College"; # Add new entry print( et['Age’]: ", dict[*Age"]) print("dict["College"]: ", dict[ ‘College’ ]) Output: dict["Age"]: 22 dict['College']: college Python [BBA (CA - Ser. V) 156 Introduction te Python Example: Python program for updating Dictionary. dicti = {'name*:"Onkar*, ‘age": 20} # update value dictt[‘age'] = 25 Houtput: {'age': 25, ‘name’: ‘Omkar'} print (dict1) # add item dicti[‘address'] = ‘pune’ # Output: {'address': ‘pune’, ‘age': 25, ‘name’: ‘Omkar*} print (dict2) Program 1,39: Print all key names in the dictionary, one by one. dict = {‘name':'Onker', ‘address': ‘pune’, ‘phone' :9897965867) for x in dictt: print(x) Output: phone name address Program 1.40; Program to print all values of dictionary. dict1 = {‘name':'Onkar', ‘address’: ‘pune’, ‘phone' :9897965867} for x in dict1.values(): print(x) Output: Onkar 9897965867 pune Program 1,41: Program to print all keys and values of dictionary. dict {'name":"Onkar", ‘address': ‘pune’, ‘phone’ :9897965867} for x, y in dict. items(): print(x, y) Output: address pune phone 9897965867 name _Onkar Python [BBA (CA - Ser. V) 157 Introduction te Python Delete Dictionary Elements + Adictionary element can be removed one at a time or can clear the entire contents of a dictionary, To explicitly remove an entire dictionary, the del statement is used. The del keyword removes the item with the specified key name: 1. Example using del: dicta = (‘Nane": ‘abe', "Age": 2, "Class*: ‘tybca") del dict1["Name']; # remove entry with key ‘Name’ dict1.clear(); # remove all entries in dict dol dict1 ; # delete entire dictionary print “oicta["Aage']: ", dicta[‘age"] This produces the following result. Note that an exception is raised because after del dict dictionary does not exist any more. dict ['Age"}: Traceback (most recent call lest): File “test.py", line 5, in 2", dict['Age"]3 Typetnron: ‘type’ object is unsubseriptable 2. Theclear() method empties the dictiona: Example using clear() dict = {‘nane':'Onkar', ‘address’: ‘pune’, ‘phone’ :9897965867} print “dict[ ‘Age’ dict1.clear() print(dict1) # Output: {} 3. The pop() method removes the item with the specified key name: Example using pop(): dicti = (‘nane*:‘omkar', ‘address": ‘pune*, ‘phone’ 9897965867} dict1.pop(‘address") print(dict1) # Output: (‘name':‘Onkar', ‘phone’ :9897965867} 4, The popitem() method removes the last inserted item. Example using popitem(): dict1 = {‘nane':"omkar', ‘address’: ‘pune’, ‘phone’ :9897965867} dictt.popiten( ) print(dict1) # Output: (‘name':‘Onkar*, ‘address*: ‘pune'} Python [BBA (CA - Ser. V) 158 Introduction te Python Program 1.42: To delete and remove elements from dictionary: squares = {1:1, 2:4, 3:9, 4:16, 5:25} # remove a particular iten print (squares.pop(4)) print (squares) # remove an arbitrary iten print (squares. popitem()) print (squares) # delete a particular iten del squares[3) print (squares) # remove all items squares. clear() print (squares) # delete the dictionary itself del squares print (squares) Output: 16 {lr 1, 2: 4 3: 9, 5: 25} ap {2: 4, 3: 9, 5: 25) (2: 4, 5: 25) tt NameError: nane ‘squares’ is not defined Properties * Dictionary values have no restrictions. They can be any arbitrary Python object, either standard objects or user-defined objects. However, same is not true for the keys. ‘+ There are two important points to remember about dictionary keys: (@) More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins. (&) Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like [‘key'] is not allowed. * ma dictionary, we can add any number of values for one key. Python object, either standard objects or user-defined objects. Python [BBA (CA - Ser. V) 159 Introduction te Python Example: >>> >>> {0: >>> True ‘+ More than one entry per key not allowed. Which means no duplicate key is allowed. When duplicate keys encountered during assignment, the last assignment wins, means the second occurrence will override the first. Example: dict ~ (‘Name': ‘Omkar', ‘Age's 20, ‘Mane': 'Mani*) dict ['Nane"] print “dict [’Name']: " output: dict[‘Name" ]: Mani + Keys must be immutable. Which means you can use strings, numbers or tuples as dictionary keys but something like ['key'] is not allowed. Example: dict = {['Nane']: ‘Onkar', ‘Age’: 20) print “dict['Nane'"]: ", dict[‘Nane"] # Output: error Program having a tuple asa dictionary key, because tuples are immutable yoo d = (CL, 22 ’a"y (Ly 2)s "DY, (2, ads "er, (2 272°C >> dL] >> df(2,0)] c Function and Methods Python includes the following dictionary functions: 1. emp(dictt, dict2): Compares elements of both dict. 2, len(dict): Gives the total length of the dictionary. This would be equal to the number of items in the dictionary. 3, str(dict): Produces a printable string representation of a dictionary, 4, type(variable): Returns the type of the passed variable. If passed variable is dictionary, then it would return a dictionary type. Example: dict = {'Name': ‘abc', ‘Age’ :20}; fusage of len() method print “Length: %d" % len (dict) #0utout:Length: 2 # usage of type() method Python [BBA (CA - Ser. V) 1.60 Introduction te Python print "Variable Type: %s" % type(dict) #Output :Variable Type: fusage of str() method print “Equivalent String: %s" % str (dict) #Output: Equivalent String: {"Age’: 28, ‘Name’: ‘abc"} Python includes following dictionary methods: 1. dict.clear(): Removes all elements of dictionary dict. 2. dict.copy(): Returnsa shallow copy of dictionary dict. 3. dict. fromkeys(): Create 2 new dictionary with keys from seq and values set to value. dict.get(key, default=None): For key key, returns value or default if key not in dictionary. dict.has_key(key): Returns true if key in dictionary dict, false otherwise. dict-items(): Returns a list of dict’s (key, value) tuple pairs dict keys(): Retumns list of dictionary dict's keys. dict.setdefault(key, default=None): Similar to get(), but will set dict[key|=default if key is not already in dict. 9. dict-update(dict2): Adds dictionary dict2's key-values pairs to dict. 10. dict.values(): Returns list of dictionary dict's values. p eiaw Program 1.43: To show usage of all methods of dictionary. dict = {’Name’: ‘abc’, ‘Age’: 20} # usage of items() method. print("Value: Xs" % dict.itens()) # usage of update() method. dict = {'Nane': ‘abe’, ‘Age’: 20} dict = {"Sex': ‘female’ ) dict.update(dict1) print("Value: Xs" % dict) # usage of keys() method. peint("Value: %s" % dict.keys()) # usage of values() method. print ("Value: %s" % dict.values()) # usage of copy() method. dict2 = dict.copy() print ("New Dictionary: Xs" % str(dict2)) # clear() mothod. print ("Start Le! Kd" % Len(dict)) dict.clear() print ("End Lenz %d" % len(dict)) Python [BBA (CA - Ser. V) 161 Introduction te Python Output: Value: dict_items([("Nane*, ‘abc"), (“Age’, 20)]) Value: {‘Nane': ‘abc’, "Age": 20, ‘Sex': ‘female’} Value: dict_keys(['Name", ‘Age’, 'Sex']) Value: dict_values(['abc', 28, ‘female"]) {'Wane': ‘abc', ‘Age’: 20, ‘Sex New Dictionary start Len: 3 End Len: @ "female') Examples Program 1.44: Write a Python script to sort (ascending and descending) a dictionary by value. import operator d= {Ar 2, 3: 4, 4: 3, 2: 1, @: Op print(‘Original dictionary : ',d) sorted d ~ dict(sorted(d.itens(), key-operator. itengetter(2))) print(*Dictionary in ascending order by value : ',sorted_d) sorted_d - dict(sorted(d.itens(), key-operator.itengetter(1), reverse-True)) print (‘Dictionary in descending order by value : ',sorted_d) Output: Original dictionary : (1: 2, 3: 4, 4:3, 2: 1, @: 9} Dictionary in ascending orde= by value : {@: 8 2: 1, Dictionary in descending order by value : (3: 4, 4: 3, Program 1.45: Write a Python script to add a key to adictionary. Sample Dictionary : (0: 10, 1: 20) Expected Result : (0: 10, 1: 20, 2: 30). d= (0:10, 1:20) print (a) d.update({2:30}) print(a) Write a Python script to concatenate following dictionaries to create a new one. Sample Dictionary: 2, 4:3, 3: 4} 2, 2: 4, 0: 0} 28, 2:20) 30, 4:40) 50,6:60} Expected Result: (1: 18, 2: 28, 3: 38, 4: 40, 5: 58, 6: 60} 10, 2:20) dic2={3:38, 4:40} dic3=(5:50,6:60} aica = for d in (dicl, dic2, dics): dica.update(a) print(dica) Python [BBA (CA - Ser. V) 162 Introduction te Python Program 1.46: Write a Python script to check ifa given key already exists in a dictionary. d= (1: 10, 2: 20, 3: 38, 4: 40, 5: 50, 6: 60} def is_key_present(x): if x ind? print('Key is present in the dictionary") else: print(‘Key is not present in the dictionary") is_key_present(s) is_key_present(9) Output: Key is present in the dictionary Key is not present in the dictionary Program 1.47: Write a Python program to iterate ever dictionaries using for loops. d= ('xt: 40, ‘y's 26, 'z: 30) for dict_key, dict value in d.items(): print(dict_key,'->',dict_value) output: y ~> 20 z-> 30 x 10 Program 1.48: Write a Python script to generate and print a dictionary that contains a number (between 1 and n) in the form (x, x*x). Sample Dictionary (n =5) : Expected Output 2:4, 3:9, 4: 16, 5: 25} n=int(input("Input a nunber ")) d = dict() for x in range(1,n+1): a[x]=xtx print (a) Output: 10 {41 1, 2: 4, 3:9, 4: 16, S: 25, 6: 36, 7 49, 8: 64, 9: 81, 10: 100) Program 1.49: Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the values are square of keys. d=dict() for x in range(1,16): a[x]=x2, print(d) Output: {i 1, 2: 4 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: G4, 9: B1, 1e: 100, 11: 1144, 13: 169, 14: 196, 15: 225) Python [BBA (CA - Ser. V) 1.63 Introduction te Python Program 1.50; Write a Python program to combine two dictionary adding values for common keys. dis (la a= {la 1@0, 'b 300, ‘b) 202, 'c':300) 208, 'd' :400) Sample output: Counter({‘a': 400, * 400, 420, 300)) fron collections inport Counter di = {'a': 100, "b's 200, ‘c':300) d2 = {'a': 300, ‘b': 208, 'd':400} d= Counter(d1) + Counter(d2) print(d) Program 1,51: Write a Python program to create and display all combinations of letters, selecting each letter from a different key in a dictionary. Sample data : {V-['a',b'], 2''c'/d']} Expected Output: ac ad be ba inport itertools d faftat, bY], 25 Le "a ]} for combo in itertools.product(*[d[k] for k in sorted(d.keys())]): print(* join(combo)) Program 1.52: Write a Python program to create a dictionary from two lists without losing duplicate values. Sample lists: [‘Class-V', 'Class-VI", ‘Class-VIT", ‘Class-VEII'], (1, 2,2, 3] Expected Output: defaultdict(, (‘Class-VIE': {2}, 'Class-VI": {2}, ‘Class-vinI': (3), “Class-v': {4}}) fron collections inport defaultdict class_list = [‘Class-V', ‘Class-VI', ‘Class-VII', 'Class-VIII"] id_list = (1, 2, 2, 3] temp = defaultdict(set) for c, i in zip(class list, id list): tenp[c].add(i) print (tenp) Python [BBA (CA - Ser. V) 164 Introduction te Python Program 1.53: Write a Python program to match key values in two dictionaries, Sample dictionary: (‘key1!: 1, 'key2!: 3, 'key3': 2}, ("key1!: 1, 'key2': 2) Expected output: key1: 1 is present in both xand y. x= {*keyl': 1, *key2": 3, *key3": 2} y= {('key2': 1, "key2": 2) for (key, value) in sot(x.items()) & set(y-items()): print('ss: %s 4s present in both x and y" % (key, velue)) FUNCTIONS-DEFINING A FUNCTION, CALLING A FUNCTION, he@U) TYPES OF FUNCTION, FUNCTION ARGUMENTS, ANONYMOUS FUNCTION, GLOBAL AND LOCAL VARIABLE, EXAMPLES ‘+ A function is defined as a block of organized, reusable code used to perform a single, related action, + Toprovide a high degree of modularity Functions are used. There are two types of Functions: (a) Built-in Functions: Functions that are predefined and organized into a library. We have used many predefined functions in Python. (®) User-Defined: Functions that are created by the programmer to mest the requirements. Advantages of Functions: 1. Tomakes the code easier to manage, debug, and scale, functions are used. 2. Every time you need to execute a sequence of statements, all we need to do is to call the function, so that we can reuse the code, 3. Functions allow us to change functionality easily, and different programmers can work on different functions. Defining a Function © Following are the rules to define a function in Python: o Function blocks begin with the keyword def followed by the function name and parentheses () © The input parameters or arguments should be placed within these parentheses o The first statement of a function can be an optional statement - the documentation string of the function or docstring or documentation string. It is used to explain in brief, what a function does. © The code block within every function starts with a colon (:) and is indented. o The return statement is used to exit a function. A return statement with no arguments is the same as return None. syntax: def function_name( param1, param2,.. ): ‘function docstring’ Function body return [expression] Python [BBA (CA - Ser. V) 165 Introduction te Python + By default, parameters have a positional behavior and you need to inform them in the same order that they were defined. Every function must be defined before it is called + How function works in Python: def functionName(): functionName() Fig. 1.23, Example: # function without parameters def my_function(): print # A string as input parameter and prints it on standard screen. def fun( str ): jello fron a function") his prints a passed string into this function’ print str retuen Calling a Function + Defining a function only gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code, + Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. + To calla function means that you are telling the program to execute the function. If ‘there is a return value defined, the function would return the value, else the function would return None, + Tocalla function, use the function name followed by parenthesis, if you need to pass parameters/arguments to the function, you write them inside the parentheses. Syntax: function_nane(argi, arg2) Example: 1. Calla function that performs a task and has no return value. def my_function() print("Hello from a function”) ny_function() Output: "Hello from a function" Python [BBA (CA - Ser. V) 166 Introduction te Python 2, Calla function with a return value. def my_function(name) : print(" ello" + name) ny_function("On") ny_function(*shanti") ny_function("Ran”) Output: Hello On Hello Shanti Hello Ram 3, To call a function with arguments. def avg_nunber(x, y): print("Average of ",x,” and is ",(x4y)/2) ave_number(3, 4) Output: Average of 3 and 4 is 3.5 Kinds of Functions: Looking from a particular point of view, we can discern three kinds of functions - functions that are always available for usage, functions that are contained within external modules, which must be imported and functions defined by a programmer with def Keyword, For example: (2) >>>From math import sqrt >>> print sqrt(81) 9.€ ‘The sqrt() function is imported from the math module, (b) >>> def cube(x); return x * x * x >>> print cube(9) 728 The cube() function is a custom defined function. (©) >>> print abs(- 1) 1 The abs() function is a built-in function readily accessible. It is part of the core of the language. Python [BBA (CA - Ser. V) 167 Introduction te Python Program 1.54; Python Program to Find HCF or GCD. # define a function def calhef(x, y): # choose the smaller nunber ifx>y: smaller = y else: smaller = x for i in range(1, smaller+t): iF((x %i == 0) and (y %i hef = 4 return hef @)): num = 54 num2 = 24 # take input from the user # num = int(input("Enter first number: ")) # num2 = int(input(“Enter second nunber: ")) print ("The H.C.F. of", nunt,"and", nun2,"is", calhef(nunt, num2)) Output: The H.C.F. of 54 and 24 is 6 Program 1.55; To Find the Largest Among Three Numbers. x=2 y= z ‘# uncomment following lines to take three numbers from user ‘#x = float(input("Enter first number: “)) ty = Float Cinput("Enter second number: ")) iz ~ float(input("Enter third number: ")) AF (>= y) and (x >= z) largest = x elif (y >= x) and (y >= 2): largest = y else: largest = z print ("The largest number between",x,",",y,"and", 2, "is", largest output: The largest number between 12, 17 and 9 is 17 Python [BBA (CA - Ser. V) 168 Introduction te Python Types of Function * There are three types of functions in Python: © Built-in functions, such as min() and max to get the minimum and maximum values, print() to print an object to the terminal. o User-Defined Functions (UDFs), which are functions that users will write their own. o Anonymous functions, which are also called lambda functions because they are not declared with the standard def keyword. FETE] Function Arguments + Function arguments are the real values passed to (and received by) the function. + The arguments in the function definition bind the arguments passed at function invocation (ie. when the function is called), which are called actual parameters, tothe names given when the function is defined, which are called formal parameters. * Actual arguments, or simply “arguments,” are the values passed to functions to be operated on. Formal parameters, or simply “parameters,” are the “placeholder” names for the arguments passed. 1. Formal Arguments: + Afunction can be called by using the following types of formal arguments: © Keyword arguments © Default arguments © Required arguments/ Positional argument © Variable-length arguments ‘+ Let us see details of each argument. 2. Keyword Arguments: + Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name, The Python interpreter is able to use the keywords provided to match the values with parameters. + The order of parameters does not matter. Example: # Function definition is here def func( str ): "This prints a string passed into this function" print str return; # calling func function func( ste = "TYBBA") Output: TyBBA Python [BBA (CA - Ser. V) 169 Introduction te Python Example: # Function definition is here def mydata( name, age ): “This prints a passed info into this function” print “Name print “Age: return; # calling the function mydata( age=50, nane="manisha" ) Output: Name: manisha Age: 58 3. Default arguments: + A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. Example: # Function definition is here def mydata( name, age = 4 ): “This prints a passed info into this function" print “Name: ", name print “age: ", age return; # calling mydata function mydata( age=50, nane="manisha" ) mydata( name="manisha" ) Output: Name: manisha age: 50 Name: manisha Age: 40 Example: # function to calculate the square of the sum of two nunbers def nsquare(x, y = 2): return (xx + 2hxty + y#y) print("The square of the sum of 2 and 2 is: ", nsquare(2)) print ("The square of the sum of 2 and 3 is: ", nsquare(2,4)) Output: The square of the sum of 2 and 2 is: 16 The square of the sum of 2 and 4 is: 36 Python [BBA (CA - Ser. V) 170 Introduction te Python Required Arguments; ‘+ Required arguments are the arguments passed to a function in correct positional order. + The number of arguments in the function call should match exactly with the function definition. # Function definition is here def printme( str ): "This prints a passed string into this function" print str return; # calling function printme() Output: Traceback (most recent call last): File “test.py", line 11, in printme() 5 TypeError: printme() takes exactly 1 argument (@ given) Variable-length Arguments: + The function can have more arguments than the arguments defining the function, * These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments. syntax: def functionname( [formal_args,] *var_args_tuple ): "Function_docstring” function_suite return [expression] * An asterisk (*) is placed before the variable name that holds the values of all non- keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call, Example: # Function definition is here def printinfo( argi, *vartuple ): “This prints a variable passed arguments” print “output is: " print argt for var in vartuple: print var return; Python [BBA (CA - Ser. V) um. Introduction te Python # call printinfo function printinfo( 18 ) printinfo( 78, 60, 58) Output: Output is: 20 output is 70 60 50 return Statement: * The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None. + def function_name(argumentt, argument2,..) statement_1 statement_2 return expression function_name(argt, rg?) Example: The following function returns the square of the sum of two numbers. def nsquare(x, y): veturn (xtx + 2hty + yy) print("The square of the sum of 2 and 3 is: ", nsquare(2, 3)) Output: The square of the sum of 2 and 3 is: 25 Anonymous Function + Anonymous Functions are the functions that are not bond to name. It means anonymous function does not have a name + While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambde functions. * A lambda function can take any number of arguments, but can only have one expression. Lambda is created without using the def keyword. Syntax of a lambda expression in Python: lanbda [argt,arg2,..]: [expression] Where you place lambda expression in Python, it returns the value of the expression. Python [BBA (CA - Ser. V) im Introduction te Python Example: ‘Function Definition square=Lambda x1: x1*x1 #Calling square as a function print "Square of number is",square(10) Output: >» Square of number is 160 >> Example: Program To Display Powers of 2 Using Anonymous Function. terms = int(input (“How nany terms? *)) # use anonymous function result = list(map(lanbda x: 2 ** x, range(terms))) # display the result print ("The total terms is:", terms) for i in range(terns): print("2 raised to power”,i,"is",result[i]) Output: The total terns is: 10 2 raised to power 0 is 1 2 raised to power 1 is 2 2 raised to power 2 is 4 2 raised to power 3 is 8 2 raised to power 4 is 16 2 raised to power 5 is 32 2 raised to power 6 is 64 2 raised to power 7 is 128 2 raised to power 8 is 256 2 raised to power 9 is 512 Global and Local Variable, Examples + Avariable’s scope tells us where in the program it is visible. A variable may have local or global scope. A variable that's declared inside a function has a local scope. When you declare a variable outside python functions, or anything else, it has global scope. + A variable’s lifetime is the period of time for which it resides in the memory. A variable that's declared inside python functions is destroyed after the function stops executing, So the next time the function is called, it does not remember the previous value of that variable. Python [BBA (CA - Ser. V) 173 Introduction te Python + Allvariables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. ‘+ There are two basic scopes of variables in Python: © Local variables: Variables declared inside a function body is known as Local Variable. © Global variables: Variable defined outside the function is called Global Variable. Global Vs. Local Variables: + Variables that are defined inside a function body have a local scope, and those defined outside havea global scope. + The local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. + When you call function, the variables declared inside it are brought into scope. Program 1.56: sum = 9; # This is global variable. # Function definition def sunfunc( argt, are2 ): # add both the parameters and return then sum = argl + arg2; # Here sum is local variable. print "Inside the function local sun: ", sum return sum # calling sumfunc function sumfunc( 108, 200 }5 print “Outside the function global sum: Output: Inside the function local sum: 300 sun Outside the function global sun: @ ‘Nonlocal Variables: + Nonlocal variable are used in nested function whose local scope is not defined. This means, the variable can be neither in the local nor the global scope. + Inthe following code, we use nonlocal keyword to create nonlocal variable. def outer() x = “local” def inner() nonlocal x x = “nonloca’ print inner() print(“outer:", x) outer() inner x) Python [BBA (CA) - Sem. VI 174 Introduction te Python ‘+ When we run the code, the will output be: inner: nonlocal outer: nonlocal + In the above code, there is 2 nested function inner(). We use nonlocal keyword to create nonlocal variable. The inner) function is defined in the scope of another function outer(. Program 1.57: To Check Prime Number. hum = int(input ("Enter a number: ")) # prime numbers are greater than 1 if num > 4: # check for factors for i in range(2, num): if (num % i) == @: print(num,"is not a prime number") break else: print(num,"is 2 prime nurber") # Af input ounber is less than or equal to 1, it is not prime els. print(num,"is not a prime number") Output: Enter a number: 56 56 is not a prime number Program 1.58: To Find Factors of Number. # define a function def factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x% i == 0: print(i) num = int(input ("Enter a number: ")) print_factors (num) Output: Enter a number: 5@ The factors of 50 are: 1 2 5 25 50 Python [BBA (CA - Ser. V) 175, Introduction te Python Program 1.59: To Find the Factorial of a Number. # change the value for a different result num = int(input ("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < @: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of @ is 1") else: For 4 in range(1,num + 1): Factorial = factorial*i print(“The factorial of” ,nun,“is", factorial) Output: Enter a number 5 The factorial of 5 is 120 Program 1,60: To Find the Sum of Natural Numbers. num = 10 # uncomment to take input from the user #oum = Int(input("enter a number: *)) if num < @: print("Enter a positive number”) else: sun = # use while loop to iterate un till zero while(num > 0): sum += num 1 print("The sum is*,sum) Output: The sum is 55 nun Program 1,61; Write a Python Program to Calculate the Average of Numbers in a Given List. ele-[2,4,6,7,8] def avg(ele) : return sum(ele)/len(ele) print("average : ",round(avg(ele),1)) Output: average : 5.4 Python [BBA (CA - Ser. V) 176 Introduction te Python Program 1,62: Write a recursive function which print string in reverse order. def rec(s): if (len(s) return else: return rec(s[1:])+5[0] ssinput("enter the string: if(seo™ print("string should not be null") else: reverec(s) print(rev) Output: enter the string:=Python programming gninmargorp nohtyP Program 1.63: Write an anonymous function to find area of circle. padelambda a:3.14%a*3 asint(input(“enter radius of circle to calculate area=")) print(rad(a)) Output: enter radius of cirele to calculate area-15 706.5 Program 1.64: Write a function which prints a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. af} def createdict(a): for i in range(1,21): dli}=it2 return d print (“Dictionary i: Output: Dictionary is: (1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 102, 11: 121, 12: 194, 13: 169, 14: 196, 15: 225, 16: 286, 17: 289, 18: 324, 19: 361, 26: 406} ,createdict(d)) Python [BBA (CA - Ser. V) 7 Program 1,65: Write a program to find gcd of number use recursion, def getged(a,b): if (b==0): return a else: return getgcd(b,a%b) asint(input(“enter value for 1 st number") baint (input(“enter value for 2 nd number") gcd=getgcd(a,b) print("GCD is Output: enter value for 1 st nunber35 enter value for 2 nd nunbersé cb is:= 7 eed) Introduction te Python Additional Programs Program 1,66: Program to find the square root of a number. x=int(input("Enter an integer nunber:")) ans=x*?0.5, print("Square root= ", ans) Output: Enter an integer nunber: 144 Square root= 12.0 Program 1,67; Program to find the area of Rectangle. L-Float(input("Enter length of the rectangle: ")) beFloat(input ("Enter breadth of the rectangle: *)) area-1*b print("Area of Rectangle= ",area) Output: Enter length of the rectangle: 5 Enter breadth of the rectangle: 6 Area of Rectangle= 38.0 Program 1,68: Write a program to display following pattern. Code: 1234 123 12 1 =(1,2,3,4] for i in range(4+1): for j in range(4-i): print(a[j],end=" ") print(” ") Python [BBA (CA - Ser. V) 178 Introduction te Python Program 1,69: Program to calculate surface volume and area ofa cylinder. pis22/7 height = float(input("Height of cylinder: ')) radian = float(input(*Radius of cylinder: *)) volume = pi * radian * radian * height ((2*pitradian) * height) + ((pitradian**2)*2) sur_area print("Volume is: print("Surface Area is Output: Height of cylinder: 4 Radius of cylinder: 6 Volume is: 452.57142857142856 ", volume) ", sur_area) Surface Area is: 377.1428571428571 Program 1.70: Program to swap the value of two variables. um input (“Enter first value: ") hum2=input ("Enter second value: “) print("Numbers before swapping") ‘temp=numt, numa =num2 num2=temp print("Numbers after swapping") print(“numi= “,nuni) print("num2= ",nun2) Output: Enter first value: 1¢ Enter second value: 20 Numbers before swapping numa= 18 num2= 20 Numbers after swapping numa= 20 num2= 10 Python [BBA (CA - Ser. V) 179 Introduction te Python Program 1.71; Write a program which finds sum of digits of a number. nt (input(“enter a nunber:”)) tot=@ while (n>) : digent10 totetotedig ye print("The total sum of digits i Output: Enter a number:156 The total sum of digits is: 12 Program 1,72: Write a program which prints Fibonacci series of a number. nterms = 10 # uncomment to take input from the user finterms ~ int(input("How many terms? “)) " tot) # first two terms mse mea count = @ # check if the number of terns is valid if nterms <= 0: print("Please enter a positive integer”) elif nterms == 1: print("Fibonacci sequence upto" nteras, print(nt) else print("Fibonacci sequence upto” nterms, while count < nterms: print(ni,end=" , °) nth = ni + n2 update values nd = n2 2 = ath count 42 1 Output: Fibonacci sequence upto 1¢: @,1,1,2,3,5,8, 13,21, 34, Python [BBA (CA - Ser. V) 1.30 Introduction te Python Program 1,73: Write a program which accept an integer value ‘n’ and display all prime numbers till ‘n’ # Python program to ask the user for a range and display all the prime numbers in that interval # uncomment to take input from the user # lower = int(input("Enter lower range: ")) # upper = int(input("Enter upper range: ")) lower = 10 upper = 20 for num in range(lower,upper + 1): # prime numbers are greater than 1 if num > a: for i in range(2,num): if (num % i) == 0: break else: print (num) Output: Fy 2B 7 19 Program 1.74; Write a program to display following pattern. neint(input(“Enter number of rows: “)) for i in range (n,®,-1): print((n-i) # + i # TP) Output: Enter nunber of rows: 5 Python [BBA (CA - Ser. V) 181 Introduction te Python Program 1.75; Write a program to reverse a given number. Code: int(input("enter any number")) sumo while(n!=2) = r=n%ie sum=(sum*10)+r nen//36 print(“reverse nunber :,sum) Output: enter any nunber2i reverse nunber : 12 Python is an open source, object-oriented, high-level powerful programming language. > A data type is a set of values, and a set of operators that may be applied to those values. Python supports five basic numerical types namely Numbers, String, List, Tupleand Dictionary. String in Python are surrounded by either single quotation marks, or double quotation marks such as ‘hello’ is the same as "hello". > String is 2 sequence of characters. Strings in Python are arrays of bytes representing unicode characters. > Variable is a name which is used to refer memory location. Variable also known as identifier and used to hold value. The period of time that a variable exists is called its lifetime, > Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables. A local variable is a variable that is only accessible from within a given function. Such variables are said to have local scope. In Python, any variable assigned a value in a function becomes a local variable of the function. > A global variable is a variable that is defined outside of any function defini Such variables are said to have global scope. Tuple is another data type which is a sequence of data similar to list. Python Dictionary is an unordered sequence of data of key-value pair form. Python operators can be classified into several categories such as arithmetic, logical, comparison, bitwise and assignment. v v vvy Python [BBA (CA - Ser. V) a2 Introduction te Python A control statement is a statement that determines the control flow of a set of instructions. A control structure is a set of instructions and the control statements controlling their execution. Three fundamental forms of control in programming are sequential, selection, and iterative control. > Python list is enclosed between square ([]) brackets and elements are stored in the index basis with starting index 0. > A list is a container which holds comma-separated values (items or elements) between square brackets where items or elements need not all have the same type. > A tuple in Python is an immutable linear data structure, denoted by a comma- separated list of elements within parentheses, allowing mixed-type elements > A tuple is a sequence of immutable objects, therefore tuple cannot be changed. It can be used to collect different types of object. > Dictionary is an unordered set of key and value pair. It isa container that contains data, enclosed within curly braces. The pair i.e., key and value is known as item. > Functions are a construct to structure programs. They are known in most programming languages, sometimes also called subroutines or procedures. Functions are used to utilize code in more than one place in a program. » Function in Python is defined by the “def” statement followed by the function name and parentheses ( ()) > Inside the function, the arguments are assigned to variables called parameters. 1. Which of the following is incorrect variable name in Python? (a) variable a (b) variablet (©) avariable (@) _variable 2. Which statementis correct? (a) List is immutable && Tupleis mutable (b) List is mutable && Tuple is immutable (c) Both are Mutable, (4) Both are Immutable 3. What type of data is: arr =[(1.1).(2.2).(3,3)]? (a) Array of tuples (b) Tuples of lists (c) List of tuples (4) Invalid type 4, Assignment Operators are Used to..runm (a) toassign valuesto variables _(b) to compare values (¢) tosort values (@) all of the above 5. ‘in’ operator is... (a) Identity operator (b) Membership operator (c) Arithmetic operator (@) Assignment operator Python [BBA (CA - Ser. V) 193 Introduction te Python 6. Awhile loop in Python is used for what type of iteration? {@) indefinite (©) discriminate () definite (@) indeterminate 7. Ina string range of slice shown by character @) LJ >) Ol @~ 8. Tuples are shown by ___ @) 0 ou oO (@) <> 9. dictionary consists of a collection of ~--~-- pairs (a) Key-value (b) Value-key (©) Key: Value (@) value: Key 10, Which brackets are used to access dictionary elements? @o oO 00 @o 11, Which of the following keywords marks the beginning of function block? (@) fun (0) define (©) def (@) function Answers 1 | 20) [30 | 4@ [5m | 6@ | 7) | 8 | 9 | 10) 14. (e) Eerie QU Answer the following Questions in short: 1. Which are data types in Python? 2. Whatare the types of variables? 3. Which are the different conditional statements? 4, Whatis looping? 5. Whatis operator? 6 7. 8 List out python basic operators. List out loop controlstatements. Which are special operators in Python? 9. What are the different types of function? 10. How to call function? 11, What is string slice? 12. How to select an element from List? 13. Whatis the difference between Xrange and range? Python [BBA (CA - Ser. V) 14 Introduction te Python 14. How to delete tuple? 15, Explain any two tuple operations with an example. 16, list out different dictionary function. QI Answer the following Questions: 1. Explain Loop control statements used in Python? 2. Writea python program to display fibonnacci series. 3. Write python program to check whether number is even or odd. 4, Writea python program to display Prime numbers between given range. 5. Write program to find factorial of given number. 6. Writea program which finds sum of digits of a number. 7. explain any five built-in List functions. 8, Which are special operations in string? 9, How to create and access elements in list 10. Which are basic tuple operations? Explain with example. 11, How to access values in tuples? 12, Whatis the use of + and * operators on tuples? 13. Writea Python program to add an item ina tuple. 14. Write a Python program to check whether an element exists within a tuple. 15, What are built-in dictionary functions? Explain, 16. How to access dictionary elements? 17. Explain how to delete elements in Dictionary. 18. Explain about functions with suitable examples. 19. Write about the concept of scope of a variable ina function. 20. Writein brief about anonymous functions 21, Writea program to calculate simple interest. 22, Write program to find area of circle. 23, Write program to swap numbers. 24, Write short note on identifier and keyword. 25, Explain different data types in python. 26, What are the features of Python? 27. Explain any three built-in dictionary functions. QuII Define the terms: 1. Data type 2. Tuple 3. List 4. Variable 5, Slicing Dictionaries 6. functions 7. anonymous function 8. global variable 9. local variable

You might also like