VI Sem B.Sc / BCA 1 Programming Basics

Python Programming Basics Introduction to Python: Python is an easy to learn, powerful programming language. It combines the features of and JAVA. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

Python is open source software, which means anybody can freely download it from www.python.org and use it to develop programs. Its source code can be accessed and modified as required in the projects.

Features of python: 1. Simple: Python is a simple and minimalistic language. Reading a good Python program feels almost like reading English language. It means more clarity and less stress on understanding the syntax of the language. It allows you to concentrate on the solution to the problem rather than the language itself.

2. Easy to learn: Python uses very few keywords. Python has an extraordinarily simple syntax and simple program structure.

3. Open Source: There is no need to pay for Python software. Python is FLOSS (Free/Library and Open Source Software). It can be free downloaded from www.python.org website. Its source can be read, modified and used in programs as desired by the programmers.

4. High level language: When you write programs in Python, you never need to bother about the low-level details such as managing the memory used by your program, etc. 5. Dynamically typed: Python provides IntelliSense. IntelliSense to make writing your code easier and more error-free. IntelliSense option includes statement completion, which provides quick access to valid member function or variables, including global, via the member list. Selecting from the list inserts the member into your code.

6. Portable: Due to its open-source nature, Python has been ported to (i.e. changed to make it work on) many platforms. All your Python programs can work on any of these platforms without requiring any changes at all if you are careful enough to avoid any system-dependent features.

7. Platform independent: When a Python program is compiled using a Python compiler, it generates byte code. Python’s byte code represents a fixed set of instructions that run on all operating systems and hardware. Using a Python Virtual Machine (PVM), anybody can run these byte code instructions on any computer system. Hence, Python programs are not dependent on any specific operating system.

8. Procedure and Object Oriented: Python supports procedure-oriented programming as well as object-oriented programming. In procedure-oriented languages, the program is built around procedures or functions which are nothing but reusable pieces of programs. In object- oriented languages, the program is built around objects which combine data and functionality. Python has a very powerful but simplistic way of doing OOP, especially when compared to big languages like C++ or Java.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 2 Programming Basics

9. Interpreted: Python converts the source code into an intermediate form called byte codes and then translates this into the native language of your computer using PVM(Is s interpreter) and then runs it.

10. Extensible: The programs or function written in C / C++ can be integrated into Python an executed using PVM. There is another flavor of Python where programs from other languages can be integrated into Python.

11. Embeddable: You can embed Python within your C/C++ programs to give scripting capabilities for your program’s users.

12. Extensive Libraries: The Python Standard Library is huge indeed. It can help you do various things involving regular expressions, documentation generation, unit testing, threading, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, cryptography, GUI (graphical user interfaces), and other system-dependent stuff. Remember, all this is always available wherever Python is installed. This is called the Batteries Included philosophy of Python. Some interesting batteries or packages are:  orgparse is a package that represents command-line parsing library  botois Amazon web services library  cherryPhy is an object-oriented HTTP frame work  cryptography offers cryptographic techniques for the programmers.  fiona reads and writes big data files.  numpy is package for processing arrays of single or multidimensional type.  w3lib is a library of web related functions.  mysql-connector-pythonis is a driver written in Python to connect to MySQL data base.

13. Scripting language: Python is considered as scripting language as it is interpreted and it is used on the Internet to support other software.

14. Database connectivity: Python provides interface to connect its programs to all major databases like Oracle, Sybase or MySQL.

15. Scalable: Python programs are scalable since they can run on any platform and use the features of the new platform effectively.

Comparison between C and Python C-Language Python Procedure Oriented Programming Language Object Oriented Programming Language Program execute faster Program execute slower compare to C Declaration of variable is compulsory Type declaration is NOT required. Type discipline is static and weak Type discipline is dynamic and string Pointer is available No pointer Does not have exception handling Handles exceptions It has while, for and do-while loops It has while and for loops

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 3 Programming Basics

It has switch-case statement It does not have switch-case statement The variable in for loop does not incremented The variable in the for loop incremented automatically. automatically. Memory allocation and de-allocation is not Memory allocation and de-allocation is done automatic automatically by PVM. It does not contain a garbage collection Automatic garbage collection It supports single and multi dimensional arrays It supports only single dimensional array. Implement multi dimensional array we should use third party application like numpy. The array index should be positive integer. Array index can be positive and negative integer. Negative index represents location from the end of the array. Indentation of statements in not necessary Indentation is required to represents a block of statements. A semicolon is used to terminate the New line indicates end of the statements and statements and comma is used to separate semicolon is used as an expression separator. expressions / variables. It supports in-line assignment It does not supports in-line assignment.

Comparison between Java and Python Java Python Pure Object-Oriented Programming Language Both Object-Oriented and Procedure-Oriented programming language Java programs are verbose. Python programs are concise and compact. Declaration of variable is compulsory Type declaration is NOT required. Type discipline is static and weak Type discipline is dynamic and string It has while, for and do-while loops It has while and for loops It has switch-case statement It does not have switch-case statement The variable in for loop does not incremented The variable in the for loop incremented automatically. automatically. Memory allocation and de-allocation is Memory allocation and de-allocation is done automatically by JVM automatically by PVM. It supports single and multi dimensional arrays It supports only single dimensional array. Implement multi dimensional array we should use third party application like numpy. The array index should be positive integer. Array index can be positive and negative integer. Negative index represents location from the end of the array. Indentation of statements in not necessary Indentation is required to represents a block of statements. A semicolon is used to terminate the New line indicates end of the statements and statements and comma is used to separate semicolon is used as an expression separator. expressions / variables. The collection objects like stack, linked list or The collection objects like lists and dictionaries vector but not primitive data types like int, can store objects of any type including float, char etc., numbers and lists.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 4 Programming Basics

Python Virtual Machine (PVM) or Interpreter Python converts the source code into byte code. Byte code represents the fixed set of instructions created by Python developers representing all types of operations. The size of each byte code instruction is 1 byte.

The role of PVM is to convert the byte code instructions into machine code. So that the computer can execute those machine code instruction and display the final output. The PVM is also called as interpreter.

Python Shell Python Interpreter is a program which translates your code into machine language and then executes it line by line. We can use Python Interpreter in two modes:

1. Interactive Mode. 2. Script Mode. In Interactive Mode, Python interpreter waits for you to enter command. When you type the command, Python interpreter goes ahead and executes the command, then it waits again for your next command. In Script mode, Python Interpreter runs a program from the source file.

Interactive Mode Python interpreter in interactive mode is commonly known as Python Shell. To start the Python Shell enter the following command in terminal or command prompt:

To start the Python 3 Shell enters python3 instead of just python. q@vm:~$ python3 1 Python 3.5.2 (default, Nov 17 2016, 17:05:23) 2 [GCC 5.4.0 20160609] on linux 3 Type "help", "copyright", "credits" or "license" for more 4 information. 5 >>> What you are seeing is called Python Shell. >>> is known as prompt string, it simply means that Python shell is ready to accept you commands. Python shell allows you type Python code and see the result immediately. In Python shell, enter the following calculations one by one and hit enter to get the result.

>>> >>> 88 + 4 92 >>> 45 * 4

180

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 5 Programming Basics Script Mode Python Shell is great for testing small chunks of code but there is one problem – the statements you enter in the Python shell are not saved anywhere.

In case, you want to execute same set of statements multiple times you would be better off to save the entire code in a file. Then, use the Python interpreter in script mode to execute the code from a file.

Create a new file named example.py and following code to it: print("Welcome to Python Program") print("B.Sc 6th Sem") print("SSCW Tumkur") By convention, all Python programs have .py extension. The file example.py is called source code or source file or script file or module. Execute by typing the following command an obtained out as follows, $ python example.py Welcome to Python Program B.Sc 6th Sem SSCW Tumkur

Indentation: Whitespace is important in Python. Actually, whitespace at the beginning of the line is important. This is called indentation. Leading whitespace (spaces and tabs) at the beginning of the logical line is used to determine the indentation level of the logical line, which in turn is used to determine the grouping of statements.

This means that statements which go together must have the same indentation. Each such set of statements is called a block. One thing you should remember is that wrong indentation can give rise to errors

Basic elements of Python 1. Comments : Comments are non-executable statements. It means neither compiler nor PVM will not execute them. Comments are any text to the right of the # symbol and is mainly useful as notes for the reader of the program. There are two types of comments in Python, Single line comments and Multiline comments a. Single line Comments: this comment starts with a hash symbol (#) and are useful to mention that the entire line till the end should be treated as comments. Eg. # To find the sum of two number k=5 # assign 5 to variable k. In the above example, first line starts with # and hence the total line treated as comments. In second line part of this line starting from # to the end of the line treated as comments.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 6 Programming Basics

b. Multi line Comments: The triple double quotes (“””) or triple single quotes (‘’’) are called multi line comments or block comments. They are used to enclose a block of lines as comments. Eg-1. “”” This is illustrated as multi line comments To find the sum of two number Using Triple double quotes “”” Eg-2 ‘’’ This is illustrated as multi line comments To find the sum of two number Using Triple Single quotes ‘’’ 2. Identifiers: Identifier is the name given to various program elements like variables, function, arrays, classes, strings etc.,

The Python identifiers follow the following rules:

i. The Name should begin with an alphabet. ii. Only alphabets, digits and underscores are permitted. iii. Distinguish between uppercase and lowercase alphabets. iv. Keywords should not be used as identifiers. v. No blank space between the identifiers. e.g. Valid Identifiers : Area area_tri num1 Invalid Identifiers : Reason 2sum Start with a digit area tri space in between is not allowed num$ $ is not allowed 3. Keywords: The keywords have predefined meaning assigned by the Python Complier. The keywords are also called as reserved word. All keywords are written in lower case alphabets. The Python keywords are:

and del for lambda true

as elif from not try

assert else global or while

break except if pass with

class exec import print yield

continue false in raise

def finally is return

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 7 Programming Basics

4. Variable: Is a program element, whose value changes during the execution of the program. Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it. Eg. x=5; y=”maya” Variables do not need to be declared with any particular type and can even change type after they have been set. x = 4 # x is of type int x = "sscw" # x is now of type str

5. Constants: Constant is a program element, while execution of a program the value does not change. A constant gets stored in a memory location but the address of the location is not accessible to the programmer

Assigning value to a constant in Python

In Python, constants are usually declared and assigned on a module. Here, the module means a new file containing variables, functions etc which is imported to main file. Inside the module, constants are written in all capital letters and underscores separating the words.

Eg.:

Create a constant.py PI = 3.14 GRAVITY = 9.8 Create a main.py import constant print(constant.PI) print(constant.GRAVITY)

6. Literals : Literal is a raw data given in a variable or constant. In Python, there are various types of literals they are as follows:

a. Numeric Literals : Numeric Literals are immutable (unchangeable). Numeric literals can belong to 3 different numerical types Integer, Float and Complex. E.g. a=5 # integer literal b=2.5 # float literal c=3.5j # complex literal

b. String literals : A is a sequence of characters surrounded by quotes. We can use both - single, double or triple quotes for a string. literal is a single character surrounded by single or double quotes.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 8 Programming Basics

E.g. str=”sscw” ch=’M’ sline=”””This is multi line string “””

c. Boolean literals : A Boolean literal can have any of the two values: True or False. E.g. x=true Y=false

d. Special literals: Python contains one special literal i.e. None. We use it to specify to that field that is not created.

E.g. k=none 7. Data Types: A data type represents the type of data stored into a variable or memory. There are 5 different data types are:  None type  Numeric type  Sequences  Sets  Dictionary

i. None data type : The none data type represents an object that does not contain any value. In java language it is called “NULL” object. But in Python it is called as “none”. In Python maximum of only one ‘none’ object is provided. If no value is passed to the function, then the default value will be taken as ‘none’. ii. Numeric data type: The numeric type represents numbers. There are 3 sub types:  int  float  complex int data type: The int data type represents integer number (Whole number). An integer number is number without fraction. Integers can be of any length, it is only limited by the memory available. E.g. a=10 b=-29 SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 9 Programming Basics

float data type: The float data type represents floating point number. A floating point number is a number with fraction. Floating point numbers can also be written in scientific notation using exponentiation format. A floating point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points. E.g. c=2.0 d=-29.45 x=2.5E4 complex data type: A complex number is number is written in the form of x +yj or x+yJ. Here x is the real part and y is the imaginary part. E.g. a= 5 +6j b= 2.5 + 6.2J We can use the type() function to know which class a variable or a value belongs to and the isinstance() function to check if an object belongs to a particular class. E.g. a = 5 print(a, "is of type", type(a)) b = 2.0 print(a, "is of type", type(b)) c = 1+2j print(c, "is complex number?", isinstance(c.complex)) iii. Sequences: A sequence represents a group of items or elements. There are six types of sequences in Python. Important sequences as follows,  str  list  tuple

str data type : The str represents string data type. A string is a collection of character enclosed in single or double quotes. Both are valid. E.g. str=”maya” # str is name of string variable str=’dhanya’ # str is name of string variable Triple double quote or triple single quotes are used to embed a string in a another string (Nested string). str=”””This is ‘str data type’ example””” print(str) # output is : This is ‘str data type’ example str=’’’ This is “str data type” example’’’ print(str) # output is : This is “str data type” example The [] operator used to retrieve specified character from the string. The string index starts from 0. Hence, str[0] indicates the 0th character in the string. e.g str=”sscw tumkur” print(str) # it display - sscw tumkur print(str[0]) # it display - s print(str[4]) # it display - w SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 10 Programming Basics

print(str[2:4]) # it display 2nd to 4th character – scw print(str[-1]) # it display first character from end – r

list data type: A List is a collection which is ordered and changeable. It allows duplicate members. A list is similar to array. Lists are represented by square brackets [] and the elements are separated by comma.

The main difference between a list and an array is that a list can store different data type elements, but an array can store only one type of elements. List can also grow dynamically in memory but the size of array is fixed and they cannot grow dynamically.

e.g. list=[10,3.5,-20, “maya”,’asha’] # create a list print(list) # it display all elements in the list : 10,3.5,-20,”maya”,’asha’ print(list[0]) # it display : 10 print(list[1:3]) # it display : 3.5, -20,”maya” print(list[-1]) # it display : ‘asha’ print(list * 2) # it display :(10, 3.5, -20, “maya”, ‘asha’, 10, 3.5, -20, “maya”, ‘asha’ ) list[1]=1.5 # replace 1st location element by 1.5 print(list) # it display all elements in the list : 10,1.5,-20,”maya”,’asha’

tuple data type: A tuple is similar to list. A tuple contains group of elements which can be different types. The elements in the tuple are separated by commas and enclosed in parentheses (). The only difference is that tuples are immutable. Tuples once created cannot be modified. The tuple cannot change dynamically. That means a tuple can be treated as read-only list.

e.g. tpl=(10,3.5,-20, “maya”,’asha’) # create a tuple print(tpl) # it display all elements in the tuple : 10,3.5,-20,”maya”,’asha’ print(tpl[0]) # it display : 10 print(tpl[1:3]) # it display : 3.5, -20,”maya” print(tpl[-1]) # it display : ‘asha’ tpl[1]=1.5 # replace 1st location element by 1.5 Display an error message - “tuple does not support this assignment. iv. Sets: Set is an unordered collection of unique items and un-indexed. The order of elements is not maintained in the sets. A set does not accept duplicate elements. Set is defined by values separated by comma inside braces { }. There are two sub types in sets: . Set data type

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 11 Programming Basics

. Frozen set data type Set data type: To create a set, we should enter the elements separated by comma inside a curly brace. e.g. s = {10,30,5, 30,50} print(s) # it display : {10,5,30,50} In the above example, it displays un-orderly and repeated elements only once, because set is unordered collection and unique items. We can use set() to create a set as K=set(“maya”) Print(K) # it display : “maya” The update() method used to add new elements to a set as s.update([6,15]) print(s) # it display : {10,5,30,50,6,15} The remove() method used to remove a particular element from the set as s.remove(30) print(s) # it display: {10,5,50,15,6}

Frozen set data type: Frozen set is just an immutable version of a Python set object. While elements of a set can be modified at any time, an element of frozen set remains the same after creation. Due to this, frozen sets can be used as key in Dictionary or as element of another set. v. Dictionary: A dictionary is an unordered collection, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. That means dictionary contains pair of elements such that first element represents the key and the next one becomes its value. The key and value should be separated by a colon(:) and every pair should be separated by comma. All the elements should be enclosed inside curly brackets. e.g. d={3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’} Here, d is the name of dictionary. 3 is the key and its associated value is ‘asha’. The next is 4 and its value is ‘yashu’ and so on. Print(d) # it display : {3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’} Print(d[5]) # it display : maya Print (d.keys()) # it display keys : ([3,4,5,6]) Print(d.values()) # it display values : ([:‘asha’, ’yashu’, ’maya’, ‘dhanu’]) d[2]=’sscw’ # add ‘sscw’ to key value 2 print(d) # it display : (2:’sscw’, 3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’} del d[4] # del key 4 and associated value. print(d) # it display : (2:’sscw’, 3: ‘asha’, 5:’maya’, 6: ‘dhanu’}

String operations: 1. Extract specified character from the string. Get the character at position 1 (remember that the first character has the position 0):

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 12 Programming Basics

a= "Hello,Python!" print(a[6]) # it display : P 2. Substring: Extract number of character from the specified position. Get the characters from position 2 to position 5 (not included): b= "Hello,Python!" print(b[6:8]) # it display : Ph 3. The strip() method removes any whitespace from the beginning or the end of the given string. a= " Hello,Python! " print(a.strip()) # it display : "Hello,Python!"

4. The len() method returns the length of a given string a= " Python" print(a.len()) # it display : 6

5. The lower() method returns the given string in lower case. a= " PYTHON" print(a.lower()) # it display : python

6. The upper() method returns the given string in upper case. a= " python" print(a.upper()) # it display : PYTHON

7. The replace() method replaces a given string with another string a= "FOR" print(a.replace(‘O’ , ‘A’)) # it display : FAR

8. The split() method splits the string into substrings if it finds instances of the separator a= "Hello,Python!" print(a.split(‘,’)) # it display : [ ‘Hello’ , ‘Python’}

Operator and Operand: Operators are special symbols which represents computation. They are applied on operand(s), which can be values or variables. Same operator can behave differently on different data types. Operators when applied on operands form an expression. Operators are categorized as Arithmetic, Relational, Logical and Assignment. Value and variables when used with operator are known as operands.

1. Arithmetic Operators : Symbol Description Example-1 Example-2 + Addition >>> 5 + 6 >>>’SSCW’+’BSC’ 11 SSCWBSC - Subtraction >>>10-5 >>>5 – 6 5 -1 * Multiplication >>> 5*6 >>>’SSCW’ * 2 30 SSCWSSCW

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 13 Programming Basics

/ Division >>> 10 / 5 >>>5 /2.0 2 2.5 % Remainder / Modulo >>> 5 % 2 >>>15%5 1 0 ** Exponentiation >>> 2**3 >>>2**8 8 256 // Integer Division >>> 7.0 // 2 >>>3//2 3.0 1

2. Relational Operators : Symbol Description Example-1 Example-2 < Less than >>> 7<10 >>> ‘SSCW’ <’BSC’ True False > Greater Than >>> 7 >10 >>>’SSCW’ > ‘BSC’ False True <= Less than or equal to >>> 7<=10 >>>’SSCW’ <=’BSC’ True False >= Greater than or equal to >>> 7>=10 >>>’SSCW’>=’BSC’ False True != , <> Not equal to >>> 7!=10 >>>’SSCW’!= ‘sscw’ True True == Equal to >>> 7==10 >>>’SSCW’ ==’SSCW’ False True

3. Logical Operators : Symbol Description Example-2 or If any one of the operand is true, then >>> 7<=10 or 7 ==10 condition becomes TRUE True and If both the operands are true, then the >>>7<10 and 7 >20 condition becomes TRUE False not Reverse the state of operand / condition >>> not 7<10 False

4. Assignment Operator: Symbol Description Example-1 = Assigned values from right side operands >>> x=10 to left variable. 10 Variations of Assignment Operators: Compound Assignment Operator combines the effect of arithmetic and assignment operator, The original value of x =5 Symbol Description Example-1 += added and assign back the result >>> x+=2 to left operand 7 -= subtracted and assign back the >>> x-=2 result to left operand 3 *= multiplied and assign back the >>> x*=2 result to left operand 10 /= divided and assign back the >>> x/=2 result to left operand 2 SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 14 Programming Basics

%= taken modulus using two >>> x%=2 operands and assign the result 1 to left operand **= performed exponential (power) >>> x**=2 calculation on operators and 25 assign value to the left operand //= performed floor division on >>> x//=2 operators and assign value to 2.5

the left operand

5. Bitwise Operator: a bit is the smallest unit of data storage and it can have only one of the two values, 0 and 1. Bitwise operators works on bits and perform bit-by-bit operation.

Symbol Description Example | Performs binary OR operation 5 | 3 gives 7 & Performs binary AND operation 5 & 3 gives 1 ~ Performs binary XOR operation 5 ^ 3 gives 6 ^ Performs binary one's complement operation ~5 gives -6 << Left shift operator: The left-hand side operand bit is 0010 << 2 gives 8 moved left by the number specified on the right-hand side (Multiply by 2) >> Left shift operator: The left-hand side operand bit is 0100 << 2 gives 1 moved left by the number specified on the right-hand side (Divided by 2)

6. Membership operators: Python has membership operators, which test for membership in a sequence, such as strings, lists or tuples. There are two membership operators are: Symbol Description Example in Returns True if the specified operand is found in the >>> x = [1,2,4,6,8] sequence >>> 3 in x false Not in Returns True if the specified operand is found in the >>> x = [1,2,4,6,8] sequence >>> 3 not in x true

7. Identity operator: Identity operators compare the memory locations of two objects. There are two Identity operators are: Symbol Description Example Example is Returns True if two variables point to the >>>X=10 >>> x=[1,2,3] same object and False, otherwise >>>Y=10 >>> y=[1,2,3] >>> X is Y >>> x is y true false is not Returns False if two variables point to the >>>X=10 >>> x=[1,2,3] same object and True, otherwise >>>Y=10 >>> y=[1,2,3] >>> X is not Y >>> x is not y false true

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 15 Programming Basics

Chapter-2 Creating Python Programs Input and Output:

1. input() : Syntax:

If prompt is present, it is displayed on monitor, after which the user can provide data from keyboard. Input takes whatever is typed from the keyboard and evaluates it. As the input provided is evaluated, it expects valid python expression. If the input provided is not correct then either syntax error or exception is raised by python. e.g. x= input (“Enter data:‟) Enter data: 2+1/2.0 Compiler will supply 2.5 to x

Output Statement: Output is what program produces. In algorithm, it was represented by print. For output in Python we use print.

Print Statement Syntax: print expression/constant/variable Print evaluates the expression before printing it on the monitor. Print statement outputs an entire (complete) line and then goes to next line for subsequent output (s). Print more than one items on a single line used comma (,) operator to separate items. Example >>> print “Hello” Hello >>> print 5.5 5.5 >>> print 4+6 10 >>>print “This”, “is” + “Python”, “Notes” This isPython Book Print function The print a line of text, and then the cursor moves down to the next line so any future printing appears on the next line. print('enter an integer value:') The print statement accepts an additional argument that allows the cursor to remain on the same line as the printed text: print('enter an integer value:', end=' ')

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 16 Programming Basics

The expression end=' ' is the keyword that cause the cursor to remain on the same line as the printed text. Without this keyword argument, the cursor moves down to the next line after printing the text. The statement print('enter an integer value:', end='\n') that is, the default ending for a line of printed text is the string '\n', the newline control code. Similarly, the statement print() is a shorter way to express print(end='\n') By default, the print function places a single space in between the items it prints. Print uses keyword arguments named sep to specify the string to use insert between items. The name sep stands for separator. The default value of sep is the string ' ', containing single space. The program sep.py shows the sep keyword customizes print’s behavior.

Program to illustrate sep: printsep.py The output of printsep.py is w, x, y, z = 10, 15, 20, 25 10 15 20 25 print(w, x, y, z) 10,15,20,25 10 15 20 25 print(w, x, y, z, sep=' , ') 10:15:20:25 print(w, x, y, z, sep=' ') 10-----15-----20-----25 print(w, x, y, z, sep=' : ') print(w, x, y, z, sep='-----')

Formatting Numbers and Strings Format function is used to return a formatted string for displaying numbers in a certain desirable format. e.g.: Following code computes interest, given the amount and the annual interest rate. >>>amount = 12618.98 >>>interestRate = 0.0013 >>>interest = amount * interestRate >>>print("Interest is",format(interest, ".2f ")) Interest is 16.40 >>> The syntax to invoke this function is format(item, format-specifier) Where item is a number or a string and format-specifier is a string that specifies how the item is formatted. The function returns a string.

Frequently Used Specifiers Specifier Format

"10.2f" Format the float item with width 10 and precision 2.

"10.2e" Format the float item in scientific notation with width 10 and precision 2.

"5d" Format the integer item in decimal with width 5.

"5x" Format the integer item in hexadecimal with width 5.

"5o" Format the integer item in octal with width 5.

"5b" Format the integer item in binary with width 5.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 17 Programming Basics

"10.2%" Format the number in decimal.

"50s" Format the string item with width 50.

"<10.2f” Left-justify the formatted item.

">10.2f" Right-justify the formatted item.

Control Statements: Control statements define the direction or flow in which execution of a program should take place. Python supports four types of control statements. 1. Sequence. 3. Looping or iteration. 2. Selection or branching. 4. Jumping.

1. Sequence: It is the order in which the statements are executed one after the other from top to bottom direction or left to right direction. By default all programming logics are sequence.

Write a python program to print the right most digit of a given integer. Output: n=int(input("Enter any integer") ) r=n % 10 Enter any integer 234 print("Right most digit = ",r ) Right most digit = 4

2. Conditional Branching / Selection: It permits selective execution of statements depending on truth value of the conditional statement. Pyhton provides two types of selective statements and one operator. The statements are: a) if statements . b) Conditional operator. i. if statement: The if statement is the simplest form of selection statement. It is very frequently used in decision making and altering the flow of execution of the program. The if structure has four different forms;

i. Simple if:

Syntax: if (condition) : Condition Statement-1

The condition / expression must be enclosed within parentheses. The expression / condition is Statement-1 evaluated true, to perform the statement-1, otherwise skip the statement-1 and perform next statement followed by if structure. Next Statement e.g-1: if (x==y): SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 18 Programming Basics

print ” a and b values are equal”

If the values of the variables x and y are same then only the print statement gets executed. Otherwise, it is skipped.

ii. If-else statement: [two-way branching statement] Syntax: if (condition) : Statement-block-1 else : Statement-block-2 The condition within the parenthesis is evaluated to true then statement-block-1 is executed otherwise statement-block-2 is executed. The condition may be simple, compound or complex. Blocks can have multiple lines. As long as they are all indented with the same amount of spaces, they constitute one block. e.g-1: If the value of the if(x>y): variable x is greater than print( ” x is big”) y then display “x is big” else : otherwise display “y is print(“ y is big”) big”.

False True Condition

Statement-2 Statement-1

Next Statement

Write a python program to check the number is divisible by 5 or not. Output -1: n=int(input("Enter any integer") ) Enter any integer 56 r=n % 5 NOT Divisible by 5 if(r==0): Output -2: print("Divisible by 5") Enter any integer 70 else: Divisible by 5 print("NOT Divisible by 5") SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 19 Programming Basics iii. Nested-if statement: Within one if construct we can introduce another if structure such a construct is called nested if. Python allows to constructing two ways of nested if,

 if-ladder  else-if ladder.

a) if ladder [nested-if in true direction] In this construct introduce new condition only if the pervious condition is Syntax: true. The second if is nested in the first if if (condition-1) : condition. When the first condition is if(condition-2): true, then second if condition is tested. if(condition-3): C++ allows maximum of 16 nesting in a statement-1 construct. else : statement-2

else : statement-3 True False else : statement-4 Cond-1

False True Statement-4 Cond-2

False True Statement-3 Cond-3

Statement-1 Statement-2

Statement-5

Write a python program to accept student percentage and print the appropriate result. Output-1: per=int(input("Enter percentage") ) Enter percentage 55 if (per>35): Second Class if(per>50): Output-2: if(per>60): Enter percentage 30 print("First class") Fail else :

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 20 Programming Basics

print("Second Class") else: print("Pass") else: print("Fail") b. The elif-ladder(Nested if with false direction):

In case, we introduce new condition only if the previous condition is false. The second if is nested in the first if condition. When the first condition is false, and then second if condition is tested, otherwise executes statement-1. If the condition- 2 is evaluated to true execute statement-2 otherwise check the next condition, and so on. Most of the programmers recommended this construct for multiple branches.

Syntax: if (condition-1) : False True Statement-1 Cond-1 elif(condition-2):

Statement-2 True False Statement-1 Cond-2 elif(condition-3): Statement-3 True False Statement-2 else: Cond-3

Statement-4 Statement-4 Statement-3

Next statement

e.g-1: if ( (a>b) and (a>c) ): print ” a is larger” elif ( (b>c) and (b>a) ): print “ b is larger” else: print “ c is larger”

Ternary Operator: Ternary operator is also called as conditional operator. It operates on 3 data elements. It was added to Python in version 2.5. It simply allows testing a condition in a single line replacing the multiline if-else making the code compact.

Syntax : SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 21 Programming Basics

[Resultant_var=] [on_true] if (condition) else [on_false]

Here Resultant variable part is optional. First check the condition, if it is true to perform [on_true] statement, otherwise to perform [on_false] statement. e.g-1: min=x if (x

Initialization;

while (condition) : Statement-1; True Cond-1 :

: Statement-1 Statement-n; False : Statement-n Update-st;

Next Statement

First initialize loop control variable then condition is evaluated. If condition is evaluates to true then the statements in the body of the loop get executed. The update-statement in the body of the loop updates the looping variable. Control goes back to the beginning of the loop. The condition again evaluated, it evaluates true, once again is executed the body of the loops. This is repeated as long as the condition remains true. Once the condition evaluates to false, the loop gets terminated and control goes to next statement followed by while loop. Example:

m=1 while( m <= 5): print ”maya” m=m+1 for loop: A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string) or specified number of times. for in [] :

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 22 Programming Basics

The start and end of the body is indicated by its indentation under the loop heading. The variable after the keyword for is called the loop index. It takes on each successive value in the sequence and the statements in the body are executed once for each value.

Usually, the sequence portion is a list of values. Build a simple list by placing a sequence of expressions in square brackets. e.g. Output: 1 for x in [1,2,3,4]: 2 print x 3 4

The range() function: The range() function is a built-in function in python that helps us to iterate over a sequence of numbers. It produces an iterator that follows arithmetic progression.

range(start, end, step) e.g >>> range(5) It generates a sequence is [0,1, 2, 3, 4 ] >>> range(2,9) It generates a sequence is [ 2, 3, 4, 5, 6, 7, 8] >>> range(2,10,2) It generates a sequence is [ 2, 4, 6, 8] Output: Write a program to print even number from 0 to 10 0 2 for x in range(0, 10, 2): 4 print (x) 6 8 Nested Loop: Within one loop we can introduce another looping construct is called nested looping. Maximum of 16 loops can be introduced in one nested looping construct. In other words Enclosing one loop within another loop is called nested loop. The enclosing loop is called outer- loop and the enclosed loop is called inner-loop. The main usage of nested loop is to print the data in tabular format, accessing the matrix element or representation of 2D or 3D graph, etc. Maximum of 16 loops can be inserted per nested loop. In nested loops, the inner loop is completely repeated for each repetition of the outer loop. Out put: n=int(input("Enter n value")) for i in range(1,n+1): Enter n value 4 for j in range(1,i+1): * print "*", ** print *** ****

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 23 Programming Basics

Jump Statements: The statements which are unconditionally transferring the program control within a program are called jump statement. The jump statements are

 break  continue  pass

The break statement: The break statement is used to terminate loops. When a break statement is encountered inside a loop, the loop is immediately terminated and next statement immediately following the loop is executed. When the loops are nested, the break statement only exits from the loop containing it. That means the break will exit only single loop. Syntax: break e.g: i=1 while(i<=10): Output: 1 print i 2 if(i==4): 3 break 4 i=i+1 Out of loop print “Out of loop”

The continue statement: The name implies that loop to be continued with next iteration. The continue statement tells the python interpreter to skip the following statements and continue with next iteration i.e. control automatically passes to the beginning of the loop. In while loop, continue causes control to transfer directly to the conditional part and continue the iteration. In case of for loop, update section of the loop will execute before test condition is evaluated.

Syntax: continue e.g: i=0 while(i<=9): i=i+1 if(i==4): continue print i print “Out of loop”

The pass statement: The pass statement does not do anything. It is used with “if statement” or inside a loop to represent no operation. We use pass statement when we need a statement syntactically but we do not want to do any operation.

Syntax: pass

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 24 Programming Basics

i=0 Output: 1 while(i<=5): 2 i=i+1 3 4 if(i==4): 5 pass 6 print i Out of loop print "Out of loop"

Difference between break, continue and pass:

Break Continue pass Terminates the loop Continue statement skip all The pass statement in statement and transfers the remaining statements in Python is used when a execution to the the loop and move controls statement is required statement immediately back to the top of the loop syntactically but you do following the loop. not want any command or code to execute.

Keyword : break Keyword : continue Keyword : pass

Array: Array is a collection of homogeneous elements or array is a collection of similar data elements under single name.

In python array can increase or decrease their size dynamically. It means, we need not declare the size of the array. When the elements are added, it will increase its size and when the elements are removed, it will automatically decrease its size in memory.

In python, there is a standard module by the name ‘array’ the helps to create and process the arrays. The array module is import to python program by using import statement.

Creating an Array: arrayName = array(typecode, [elements])

‘array’ is the standard module in python, which helps to create and process the arrays. The array module is import to python program by using import statement.

import array where typecode represents the type of array. In other words type of data stored in an array. The typecode should be enclosed in single quote(‘ ‘).

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 25 Programming Basics

TypeCode Type Description Minimum size in bytes b Signed integer 1 B Unsigned integer 1 i Signed integer 2 I Unsigned integer 2 l Signed integer 4 L Unsigned integer 4 f Floating point 4 d Double precession floating point 8 u Unicode character 2 e.g. X=array(‘i’ ,[4, 6, 3, 8])

This is creating an integer array with the name X and store whole number each taking 2 bytes memory.

Y=array(‘f’ , [1.4, 5.6, 7.8, 3.6])

This is creating a floating point array with the name Y and store fraction elements each taking 4 bytes memory.

Importing the array Module: There are three ways to import the array module into our program.

a. The first method is to import the entire array module using import statement.

import array X= array.array(‘i’, [10,20,30]) Here, the first ‘array’ represents the module name and the next ‘array’ represents the class name for which the object is created. This means creating our array as an object of array class. b. The second method of importing the array module is to give is an alias name. import array as maya X= maya.array(‘i’,[10,20,30]) Here, the array is imported with an alternate name ‘maya’. Hence we can refer to the array class of ‘maya’ module. c. The third method of importing the array module is to import all from array class from array import * X=array(‘i’, [10,20,30]) SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 26 Programming Basics

Here, * symbol represents all. That means import all(classes, objects, variables etc) from the array module into our program. So, there is no need to mention the module name before our array name while creating it. The name array represents the class name that is available from the ‘array’ module.

Built-in array methods: 1. Append any value to the array using append() method my_array = array('i', [1,2,3,4,5]) my_array.append(6) # array('i', [1, 2, 3, 4, 5, 6]) Note that the value 6 was appended to the existing array values.

2. Insert value in an array using insert() method my_array = array('i', [1,2,3,4,5]) my_array.insert(0,0) #array('i', [0, 1, 2, 3, 4, 5]) In the above example, the value 0 was inserted at index 0. Note that the first argument is the index while second argument is the value.

3. Extend python array using extend() method my_array = array('i', [1,2,3,4,5]) my_extnd_array = array('i', [7,8,9,10]) my_array.extend(my_extnd_array)

# array('i', [1, 2, 3, 4, 5, 7, 8, 9, 10]) We see that the array my_array was extended with values from my_extnd_array.

4. Remove any array element using remove() my_array = array('i', [1,2,3,4,5]) my_array.remove(4)

# array('i', [1, 2, 3, 5])

We see that the element 4 was removed from the array.

5. Remove last array element using pop() method pop removes the last element from the array. my_array = array('i', [1,2,3,4,5]) my_array.pop()

# array('i', [1, 2, 3, 4]) So we see that the last element (5) was popped out of array.

6. Fetch any element through its index using index() index() returns first index of the matching value. Remember that arrays are zero-indexed. my_array = array('i', [1,2,3,4,5]) SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 27 Programming Basics

print(my_array.index(5)) #output: 5 my_array = array('i', [1,2,3,3,5]) print(my_array.index(3)) #output: 3 Note in that second example that only one index was returned, even though the value exists twice in the array

7. Reverse a python array using reverse() method The reverse() method reverses the array. my_array = array('i', [1,2,3,4,5]) my_array.reverse() # array('i', [5, 4, 3, 2, 1])

8. Sort a python array using sort() method from array import * my_array = [1,20,13,4,5] my_array.sort() print(my_array) #output:1,4,5,13,20

Multi-Dimensional Array An array containing more than one row and column is called multidimensional array. It is also called combination of several 1D arrays.2D array is also considered as matrix.

A=array([1,2,3,4])# create 1D array with 1 row B=array([1,2,3,4],[5,6,7,8]) create 2D array with 2 row

Matrix in Numpy In python we can show matrices as 2D array. In numpy, a matrix is considered as specialized 2D array. It has lot of built in operators on 2D matrices. In numpy,matrix is created using the following syntax. Matrix_name=matrix(2D array or string) Eg.a=matrix('12 3;4 5 6;7 8 8')

Matrix addition and multiplication. We can use arithmetic operators like +, -,* ,/ toperform different operations on matrices. Example: Matrix_Operation.py From numpy import* a=matrix('4 4 4;4 4 4;4 4 4') b=matrix('2 2 2;2 2 2;2 2 2') print("Printing A matrix") print(a) print("Printing B matrix") print(b) print("Printing Addition of two matrix") c=a+b #matrix addition print(c) SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 28 Programming Basics

print("Printing Multplication of two matrix") c=a*b #matrix Multiplication print(c)

Function: Function is a group of statements and perform a specific task. A function can be written individually in a python program. A function is called using its name (function name). When a function is written inside a class, it becomes a method. A method can be called using object / class name

Types of function: Functions are three types. There are: a. Module b. Built-in function c. User-defined function. a. Module: A module is a file that contains a collection of related functions and other definitions. Modules are the key to Python’s portability and power. Modules are extensions that can be imported into Python ti extend its capabilities. Python itself is made up of modules. For example, Python has a math module that includes a number of specialized mathematical tools. To include math module into your program by importing it.

WAP to illustrate math module import math print "Absolute value of -34.45 is ",math.fabs(-34.45) print "Absolute value of 56.34 is ",math.fabs(56.34) print "ceil of 100.12 is ",math.ceil(100.12) print "ceil of 100.67 is ",math.ceil(100.67) print "floor of 50.34 is ",math.floor(50.34) print "floor of 50.89 is ",math.floor(50.89) print "E rise to 2 is ",math.exp(1) print "squre root of 25 is ",math.sqrt(25)

Create your own Module / Construct the user defined module 1. First create module description and saved as module1.py 2. Create new python file as Test-module.py 3. Call module methods using module-name.method-name() Example: module1.py def sum1(a,b): c = a+b return c def mul1(a,b): c = a*b return c

Filename: Test_module1.py import module1 #import module_name x = 12 y = 34 print("Sum is ", module1.sum1(x,y)) SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 29 Programming Basics

print("Multiple is ", module1.mul1(x,y)) b. Built-in Functions: Built-in functions are the functions that are built into Python and can be accessed by programmer any time without importing any module. These functions are also called as standard functions. These functions are available in all versions of Python. Example, X= abs(-34) Y=min(5,2,7,19) Z=max(2,20,4,33,21) Pirnt(range(1,5)) c. User-Defined Functions: A user defined function represents a function which is named and provided by user to produce the desired and certain output. Simple rules to defined user defined function are: 1. A function blocks begins with the keyword def followed by function name followed by parenthesized parameter list and the colon 2. Any input parameters or arguments should be placed within these parentheses. 3. The first line in the function can be optional statement- the documentation string of the function or docstring. 4. The body of the function followed by colon and is indented. 5. The return statement exits a function. The return statement contain zero or with an argument. 6. Calling / invoking a function by its function-name.

Syntax : def function-Name(argument-list) : Function Header St-1 St-2 : Function Body St-n return() Example: def printname(str): print str This is user defined function return printname("Python-2.7")

This is invoking a function

Types of Parameters or Formal Arguments: The user defined functions can be call by using the following types of formal arguments. 1. Required arguments 2. Keyword arguments 3. Default arguments 4. Variable –length arguments SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 30 Programming Basics

1. Required Arguments: Required arguments are the arguments passed to a function in correct positional order. Here the number of arguments in the function call should match exactly with the function definition. Example: def printinfo(name,sem) print name print sem return printinfo(“maya”,6)

In the above example, we have passed two arguments. The function definition contains two arguments to receive those values. 2. Keyword Arguments: :Keyword arguments are the arguments with assigned values passed in the function call statement, i.e., when you use keyword argument 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. Example: def printinfo(name,sem) print name print sem return printinfo(sem=6,name=“maya”) In the above example, we passed arguments with different order and then the caller identifies the arguments by the parameter name.

3. Default Arguments: A default argument is an argument that assumes a default values if a value is not provided in the function call for that argument. A parameter having default value in the function header is known as a default parameter. I case the user does not want to provide values at the time of calling, we can provide default values.

Example: def printinfo(name=”Dhanu”,,sem=6) print name print sem return printinfo() printinfo(sem=5) printinfo(name=“maya”,sem=3) In the above example, first call, we missing both the arguments and then function take default values. In second time call, we missing one argument and then take name values as the default value. In third time call, we r not missing any arguments and then function takes both the arguments provided by the user.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 31 Programming Basics

4. Variable-length arguments: To process a function for more arguments than you specified while defining the function. These arguments are called variable length arguments and are not named in the function definition, unlike required and default arguments. A asterisk (*) is placed before the variable name that will hold the values of all non-keyword variable arguments. This tuple remains empty if not additional arguments are specified during the function call.

Example: def printinfo(arg1, *vartuple) print arg1 for k in vartuple : print k return printinfo(10) printinfo(1,2,3,4,5) RECURSION A recursive function is one that invokes itself. Or A recursive function is a function that calls itself in its definition.

Any recursive function can be divided into two parts. First, there must be one or more base cases, to solve the simplest case, which is referred to as the base case or the stopping condition Next, recursive cases, here function is called with different arguments, which are referred to as a recursive call. These are values that are handled by “reducing” the problem to a“simpler” problem of the same form. Example: Fact_recursion.py # Return the factorial for the specified number def factorial(n): if n == 0: # Base case return( 1) else: return (n*factorial(n-1)) # Recursive call

n=int(input("Enter a nonnegative integer: ")) print("Factorial of", n, "is", factorial(n)) List Data Type:

A List is a collection which is ordered and changeable / mutable. It allows duplicate members. A list is similar to array. Lists are represented by square brackets [] and the elements are separated by comma.

The main difference between a list and an array is that a list can store different data type elements, but an array can store only one type of elements. List can grow dynamically in memory but the size of array is fixed and they cannot grow dynamically.

The following are the characteristics of a Python list: SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 32 Programming Basics

 Values are ordered  Mutable  A list can hold any number of values  A list can add, remove, and modify the values Syntax: List-var =[ele1,ele2, …,elen] Example, k=[1,2,3,4,5,”dhanu”] List Operations: Let us consider the list k=[1,2,3,4,5,”dhanu”] 1. Indexing: For accessing an element of the list, indexing is used. List index starts from 0 in left to right method. Working from right to left, the first element has the index -1, the next one -2 and so on, but left most element is still 0. print k[2] # output is 3 2. Slicing: A slice of a list is sub-list. Slicing using to access range of elements. This operation using two indices, separated by colon(:). First index is the starting point to extraction starts and second index is the last point to be stop.

Print k[2:5] # output is 3,4,5

3. Joining two list: Concatenate two lists together. The plus(+) operator used to concatenate two list >> a= [1,2,3] >> b=[4,5] >>c=a+b >> print c # it produce [1,2,3,4,5]

4. Repeating list: Multiplying a list by an integer n creates a new list that repeats the original list n times. The operator * is used to repeating the list by n times. >> a=[1,2,3] >>print (a*3) # It produce [1,2,3,1,2,3,1,2,3]

List functions and methods:

1. len(): It is used to get the length of a list. 2. append(): To add an item to the end of a list. 3. count(value): To find the number of times a value occurs in a list. 4. extend(): To add the items in one list to an existing another list. 5. insert(): To insert a new element at the specified location. 6. pop(): To returns and remove the rightmost element from the list. 7. remove(value): To remove the first occurrence of the specified element from the list. 8. sort(): This function used to sort/arrange the list item. 9. reverse(): This function reverse the list elements.

Dictionary: A dictionary is an unordered collection, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. That means dictionary contains pair of elements such that first element represents the key and the next one becomes its value. The key and value should be separated by a colon(:) and every pair should be separated by comma. All the elements should be enclosed inside curly brackets.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 33 Programming Basics

Characteristics of a Dictionary: 1. A dictionary is an unordered collection of objects. 2. Values are accessed using a key 3. A dictionary can shrink or grow as needed 4. The contents of dictionaries can be modified. 5. Dictionaries can be nested. 6. Sequence operations, such as slice cannot be used with dictionary e.g. d={3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’}

Here, d is the name of dictionary. 3 is the key and its associated value is ‘asha’. The next is 4 and its value is ‘yashu’ and so on. Print(d) # it display : {3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’} Print(d[5]) # it display : maya Print (d.keys()) # it display keys : ([3,4,5,6]) Print(d.values()) # it display values : ([:‘asha’, ’yashu’, ’maya’, ‘dhanu’]) d[2]=”Tumkur” # add ‘’Tumkur” to key value 2 print(d) # it display : {2:’Tumkur’, 3: ‘asha’, 4:’yashu’, 5:’maya’, 6: ‘dhanu’} del d[4] # del key 4 and associated value. print(d) # it display :{2:’sscw’, 3: ‘asha’, 5:’maya’, 6: ‘dhanu’}

Dictionary functions and methods: 1. len():It returns the number of items in a dictionary. 2. clear(): It removes all the items from the dictionary. 3. get(): It returns the value from a dictionary associated with the name. 4. popitem(): It remove the last item in the dictionary. 5. keys(): It returns list of all the keys used in the dictionary, in arbitrary order. 6. values():It returns list of all values used in the dictionary. 7. items(): It returns list of tuple(key : value) used in the dictionary.

Tuple: A tuple is similar to list. A tuple contains group of elements which can be different types. The elements in the tuple are separated by commas and enclosed in parentheses (). The only difference is that tuple are immutable. Tuples once created cannot be modified. The tuple cannot change dynamically. That means a tuple can be treated as read-only list.

Difference between list and tuple

LIST TUPLE List are enclosed in square brackets [] Tuple are enclosed in parentheses () Element and size can be changed Can’t be changed. Is a mutable object Is a Immutable object It can grow and shrink as needed It is read only list

e.g. tpl=(10,3.5,-20, “maya”,’asha’) # create a tuple print(tpl) # it display all elements in the tuple : 10,3.5,-20,”maya”,’asha’ print(tpl[0]) # it display : 10 SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 34 Programming Basics

print(tpl[1:3]) # it display : 3.5, -20,”maya” print(tpl[-1]) # it display : ‘asha’ tpl[1]=1.5 # replace 1st location element by 1.5 Display an error message - “tuple does not support this assignment”.

Tuple functions and methods:

1. len(): It returns number of elements in a tuple. 2. max(): It returns a largest element in the tuple. 3. min(): It returns a smallest element in the tuple. 4. cmp(t1,t2): It compares two tuples. It checks whether the given tuples are same or not. If both are same, it returns 0, otherwise return 1 or -1. If the first tuple is big, then it will return 1 otherwise return -1. 5. tuple(): It creates empty tuple.

Set: Sets are like lists in that you use them for storing a collection of elements. Unlike lists, the elements in a set are non-duplicates and are not placed in any particular order.

Creating Sets Python provides a data structure that represents a mathematical set. As with mathematical sets, elements of Set are enclosed inside a pair of curly braces ({}).The elements are non- duplicate, separated by commas. You can create an empty set, or you can create a setfrom a list or a tuple, as shown in the following examples: s1 = set () # Create an empty set s2 = {1, 3, 5} # Create a set with three elements s3 = set ([1, 3, 5]) # Create a set from a tuple

Set Operations Python provides the methods for performing set union, intersection, difference, and symmetric difference operations.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 35 Programming Basics

Example: Setop.py s1 = {1, 4, 5, 6} s2 = {1, 3, 6, 7} print(s1.union(s2)) print(s1 | s2) print(s1.intersection(s2)) print(s1 & s2) print(s1.difference(s2)) print(s1 - s2) print(s1.symmetric_difference(s2)) print(s1 ^ s2)

FILES

Files are used to store data permanently. Data used in a program is temporary; unless the data is specifically saved, it is lost when the program terminates. To permanently store the data created in a program, you need to save it in a file on a disk or some other permanent storage device. The file can be transported and can be read later by other programs. Python’s standard library has a file class that makes it easy for programmers to make objects that can store data to the disk and retrieves data from the disk

In order to read and write into a file, we will use the open() as built-in function to open the file in specified mode of operations. The open() function creates an file_object object. The Syntax is: file_object = open(file_name ,access_mode) The first argument file_name is specifies the name of the filename that is to be opened. The second argument access_mode is determines in which mode the file has to be opened, that is, read, write and append.

The File open modes are:

Mode Description "r" Opens a file for reading.

"w" Opens a new file for writing. If the file already exists, itsold contents are destroyed "a" Opens a file for appending data from the end of the file. "rb" Opens a file for reading binary data. "wb" Opens a file for writing binary data. "r+" Opens a file for reading and writing. Opens a file for reading and writing. If the file doesn't exist, then a new file is "w+" created. Examples: f = open (‘student.txt', 'r') This statement creates a file object as f, it opens the student.txt file as read only purpose if the file is exists. SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 36 Programming Basics

f = open ('student.txt', 'w') This statement creates a file object as f, it creates new file student.txt for write purpose if the file is does not exists. If the file is exists overwrite the file. f = open ('student.txt', 'a') This statement creates a file object as f, it opens file student.txt for append mode if the file is exists. That means add new content to the end of existing file.

Writing text to a file The 'w' mode creates a new file. If the file already exists, then the file would be overwritten. We will use the write() function.

f = open("student.txt",'a') f.write("100, maya,6 sem") f.close()

Reading Data After a file is opened for reading data, you can use the read() method to read a specified number of characters or all characters from the file and return them as a string, the readline() method to read the next line, and the readlines() method to read all the lines into a list of strings.

EXCEPTION HANDLING:

An Exception is a condition that is caused by a run-time error in the program. When the Python interpreter encounters an error such as dividing an integer by zero, it creates an Exception object and throws it [i.e., informs us that, an error has occurred].

If the Exception object is not caught and handled property, the interpreter will display an error message and will terminate the program. If we want the program to continue with the execution of the remaining code, then we should try to catch the Exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling.

The purpose of Exception handling mechanism is to provide a means to detect and report an “Exceptional circumstance”, So that appropriate action can be taken, the mechanism performs the following task:

1. Find the error/ detect the error [hit the Exception]. 2. Inform that an error has occurred [throw the Exception]. 3. Receive the error information [catch the Exception]. 4. Take corrective actions / appropriate actions [handle the Exception].

The error handling code basically consists of two segments,

1. To detect the errors and throw Exception. 2. To catch Exception and perform appropriate action. 3. SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 37 Programming Basics

Syntax: try: except :

Here, contains the code that may raise an exception. When an exception occurs, the rest of the code in is skipped. If the exception matches an exception type, the corresponding handler is executed. is the code that processes the exception. Exception handling keywords are try, except and finally.

Try and except:

The try block can have one or more statements that could generate an exception. If anyone statement generates an exception the remaining statements in the block are skipped and exception jumps to the except block that is placed next to the try block.

The except block can have one or more statements that are necessary to process the exception. Every try statement should be followed by at least one except statement, otherwise compilation error will occur.

The except statement works like method definition. The except blocks receive a single parameter, which is reference to the exception object thrown by the try block. If the except parameter matches with the type of exception object, then the exception is caught and statements in the except block will be executed. Otherwise, the exception is not caught and the default exception handler will cause the exception to terminate.

Example: Exception1.py def divide(a,b): try: c = a/b return c except: print ("Error in divide by zero function") print(divide(10,0)) #function call

Common standard exception classes

Class Meaning

AttributeError Object does not contain the specified instance variable or method

ImportError When import statement fails to find a specified module or name

IndexError A sequence (list, string, tuple) index is out of range

KeyError Specified key does not appear in a dictionary

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 38 Programming Basics

NameError Specified local or global name does not exist

TypeError Operation or function applied to an inappropriate type

ValueError Operation or function applied to correct type but inappropriate value

ZeroDivisionError Second operand of divison or modulus operation is zero

A try with multiple except clause and finally block:

In some cases, more than one exception should be raised by a single piece of code. To handle this type of situation, you specify two or more except clauses, each catching different types of exception. When an exception is thrown, each except statement is inspected in order, and the first one whose type matches that of the exception is executed. After one except statement executes, the others are bypassed, and execution continues after the try / except block. finally block:

This can be used to handle an exception that is not caught by any of the previous except statements. Finally block can be used to handle any exception generated within a try block. It may be added immediately after the try block or after the last except block.

When a finally block is defined, this is guaranteed to execute, regardless of whether or not an exception is thrown. As a result, we can use it to perform certain housekeeping operations such as closing files and releasing system resources.

try: except : except : : except :

finally :

Multi Threading:

The modern operating systems such as Windows-95 may recognize that they can execute several programs simultaneously. This ability is known as ‘Multitasking’. In system terminology, it is called ‘Multithreading’.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 39 Programming Basics

Multithreading is a conceptual programming paradigm where a program (process) is divided into two or more subprograms (process), which can be implemented at the same time in parallel.

A Thread is similar to a program that has a single flow of control. It has beginning, a body and an end, and executes command sequentially. Every java program will have at least one thread called main thread.

Threads exist within a process, Every process has at least one thread, threads share the process’s resources, including memory and open files. Therefore threads are sometimes called as ‘lightweight processes’.

Life Cycle of thread:

States of Thread To understand the functionality of threads in depth, we need to learn about the lifecycle of the threads or the different thread states. Typically, a thread can exist in five distinct states. The different states are shown below: New Thread A new thread begins its life cycle in the new state. But, at this stage, it has not yet started and it has not been allocated any resources. We can say that it is just an instance of an object. Runnable As the newly born thread is started, the thread becomes runnable i.e. waiting to run. In this state, it has all the resources but still task scheduler have not scheduled it to run. Running In this state, the thread makes progress and executes the task, which has been chosen by task scheduler to run. Now, the thread can go to either the dead state or the non-runnable/ waiting state. Non-running/waiting In this state, the thread is paused because it is either waiting for the response of some I/O request or waiting for the completion of the execution of other thread. Dead A runnable thread enters the terminated state when it completes its task or otherwise terminates.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 40 Programming Basics

Creating threads in python Python provides “Thread” class of threading module to create threads. We can create threads in the following different ways. 1. Creating threads without using a class 2. Creating a thread by creating sub class to thread class 3. Creating a thread without creating sub class to Thread class

1. Creating threads without using a class In this method, a function is created and its name is passed as target for the thread as t=Thread(target=function_name,[args=(arg1,arg2,..) Here t is the object of thread class; the target represents the function on which the thread will act. The args represents a tuple of arguments which are passed to the function. the tread is started by calling the start() method as t.start(). The thread t will execute the function.

2. Creating a thread by creating sub class to thread class By using Thread class from threading module, we can create our own class as sub class to Thread class, so that we can inherit the functionality of Thread class. By inheriting Thread class we can make use all methods of Thread class into sub class. The Thread class has run() method which is also available to sub class. Every thread will run this method when it is started. By overriding this run we can make threads run our own run() method.

3. Creating a thread without creating sub class to Thread class We can create an independent class say MyThread that does not inherit from Thread class. Then create object of MyThread .Next step is to create a thread by creating object to Thread class and specifying the method of the MyThread class as its target as,

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 41 Programming Basics

T1=Thread(target=obj.Sleep,args( ))

Thread synchronization It is defined as a mechanism which ensures that two or more concurrent threads do not simultaneously execute some particular program segment known as critical section.

PROFILING Profiling means having the application run while keeping track of several different parameters, like the number of times a function is called, the amount of time spent inside it, and so on. Profiling can help us find the bottlenecks in our application, so that we can improve only what is really slowing us down. Python includes a profiler called cProfile. It breaks down your entire script and for each method in your script it tells you: ncalls: The number of times a method was called tottime: Total time spent in the given function (excluding time made in calls to sub- functions) percall: Time spent per call. Or the quotient of tottime divided by ncalls cumtime: The cumulative time spent in this and all subfunctions (from invocation till exit). This figure isaccurate even for recursive functions. percall: is the quotient of cumtime divided by primitive calls filename: lineno(function): provides the respective data of each function

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 42 Programming Basics

Chapter-3: Object Oriented Programming

“Object Oriented Programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of same class”.

Salient features of OOPs: 1. Class and Object: A Class represents a set of objects that shares common characteristics and behavior or A Class is an overall organization of data and operational method. An object is a real world entity / real world identifiable entity which represent characteristics, state and behavior. In other words, Object is a variable of type class or object is an instance, which represents the characteristics of a class. e.g. Vehicle is a class, Car is an object. Furniture is a class, table is an object. Flower (lily, lotus, rose) flower: class Lilly, lotus, rose: objects of class flower

2. Data abstraction: Abstraction refers to the act of representing essential features without including the background details / explanation. Abstraction is the concept of simplifying a real world concept into its essential elements. e.g. To define an abstract STACK class using abstract representation: Class : STACK Data : St [20], top Methods : 1. Pre-Condition: isEmpty (), isFull () 2. Functions: PUSH (), POP () Abstract class represents only the external structure of the class but not the internal structure.

3. Data Encapsulation and hiding: The wrapping up of data and method into a single unit is known as Encapsulation. The data is not accessible to the outside world and only those methods, which are wrapped in the class, can access it. These methods provide the interface between the object data and the program. This insulation of the data from direct access by the program is called Data hiding. Encapsulation is a way to implement data abstraction. Encapsulation hides the details of the implementation of an object.

4. Polymorphism: Polymorphism means the ability to take more than one form. An operation may exhibit different behavior in different instance. The behavior depends upon the type of data used in the operation. A function name can be used to handle different types of arguments. This is similar to a particular word having different meanings depending on the context. Polymorphism is extensively used in implementing inheritance.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 43 Programming Basics

E.g. consider the operation of addition for 2 numbers the operation will generate sum and if the operands are strings, then the operation would produce a third string by concatenation.

5. Inheritance: Inheritance is the process by which objects of one class acquire the properties of object of another class. In OOP, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class form the existing one. The new class will have the combined features of both the classes. It represents parent–child relationship or hierarchical model.

6. Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in response to the call. The dynamic binding means, the code associated with a given procedure call is not known until the time of call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a polymorphic reference depends on the dynamic type of that reference.

7. Bottom-up approach: OOPs follows the bottom-up approach for coding and top-down approach for design. It reduces the compilation time and debugging time. Bottom-up approach follows the user to develop a unit module first, and then integrates all unit module into a single main module. Example for OOPs languages are Python, C++, JAVA, Visual C++ etc.,

Advantages of Object Oriented Programming

. Simplicity: Software models are real object models in the application domain. The complexity of the program is reduced and the program structure becomes clear and simple. . Modularity: Each object forms a separate entity with internal workings that are decoupled from other parts of the system. . Modifiability: It is easy to make minor changes in the data representation. Changes within an object do not affect any other part of the program provided that the external behaviour of the object is preserved. . Extensibility: Adding new features to the existing object. . Flexibility: It is very flexible in accommodating different situations because the interaction patterns among the objects can be changed without modifying the objects. . Maintainability: Objects can be maintained separately, locating and fixing problems easy. . Code Reusability: This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class form the existing one. The new class will have the combined features of both the classes. Disadvantages

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 44 Programming Basics

. It does not have functional abstraction. . There is still a lot of discussion about which features are really essential to Object-Orientedness. . Lack of solid formal foundations.

Class and Object: A Class represents a set of objects that shares common characteristics and behavior or “A Class is an overall organization of data and operational method”.

“An object is a real world entity / real world identifiable entity which represent characteristics, state and behavior”. In other words, Object is a variable of type class or object is an instance, which represents the characteristics of a class.

E.g. Vehicle is a class, Car is an object. Data member: Any variable defined inside the class is called data member Instance variable: The variable defined inside a method and belongs to current instance of a class. Instance: The individual object of certain class. Instantiation: It is process of creating an object / instance of a class.

Creating a class Creating a class in Python with the following syntax: class(): #statements must be indented Methods The class functions are known by common name, methods. In Python, methods are defined as part of the class definition and are invoked only by an instance. To call a method we have to : (1) define the class (and the methods), (2) create an instance, and finally, (3) invoke the method from that instance. Here is an example class with a method: class MyMethod: #define the class def display(self): # define the method print ('Welcome! to class My Method') obj=MyMethod() obj.display() The self is a parameter that references the object itself. Using self, you can access object’s members in a class definition.

To invoke the method we have to instantiate the class and call the method as follows. >>> myObj = MyMethod() # create the instance >>> myObj.display() # now invoke the method

W.A.P to illustrate class and object class xyz (object):

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 45 Programming Basics

def putdata(self): Print (“Welcome to Class and object”) Return P=xyz() P.putdata() Constructor: [ __init__() ]method: A Constructor is a special method, which is executed automatically when an object is created. Constructor is used to initialize the instance variable of a class. In constructor, we create the instance variable and initialize them with some starting values. The first parameter of the constructor will be ‘self’ variable that contains the memory address of the instance. The python provides a special method, __init__ is a constructor. This method, known as an initializer, is invoked to initialize a new object’s state when it is created. An initializer can perform any action, but initializers are designed to perform initializing actions, such as creating an object’s data fields with initial values. class student(object): def __init__(self): # constructor self.rno=100 self.name=”maya” return def putdata(self): print"Student rno=",self.rno print "Student name=",self.name return p=student () # Constructor call p.putdata() # call putdata() method

Destructor [__del__() ]Method : A destructor is a special method, which is executed automatically when an object scope is ended. Like constructor, there is an equivalent destructor special method called __del__(). However, due to the way Python manages garbage collection of objects, this function is not executed until all references to an instance object have been removed. Destructors in Python are methods which provide special processing before instances are de-allocated and are not commonly implemented since instances are rarely de-allocated explicitly. class xyz(object): def __init__(self): # Constructor print (“Object is created and Initialize”) def __del__(self): # Destructor print(“xyz object is deleted / Destructor is executed”) K=xyz() # Constructor call del K # Destructor call

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 46 Programming Basics

Built-In-Class -Attributes Every Python class keeps following built-in attributes and they can be accessed using dot operator like any other attribute −  __dict__ : Dictionary containing the class's namespace.  __doc__ : Class documentation string or none, if undefined.  __name__ : Class name.  __module__ : Module name in which the class is defined. This attribute is "__main__" in interactive mode.  __bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.

class student: 'Student details' def getdata(self,r,st): self.rno=r self.name=st return def putdata(self): print"Student rno=",self.rno print "Student name=",self.name return p=student () print "Studen Doc=",p.__doc__ print "Class Name=",p.__class__ print "Module=",p.__module__ print "Dictionary=",p.__dict__

Inheritance: “Inheritance is a process of creating new class from an existing class is called inheritance”. Or “Inheritance is the process by which objects of one class acquire the properties of objects of another class”. The new class is called the derived class or subclass or child class. The existing class is called the base class or super class or parent class. OR Inheritance enables you to define a general class (a superclass) and later extend it to more specialized classes (subclasses).

 The derived class inherits all the properties of the base class and it can add new features of its own.  The derived class members automatically inherit the features of the base class.  The derived class may also posses additional features, apart from those inherited from the base class.  A class could be derived from different base classes.

Code Reusability The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 47 Programming Basics

An advantage of reusability is that a class created by a person and added to the class libraries, can be used by another programmer. Without modifying the existing class the programmer can create derived classes from it with additional features, to suit the situation.

Syntax: class BaseClass(object): . .

class DerivedClass(BaseClass): . .

The BaseClass is the already existing (parent) class, and the DerivedClass is the new (child) class that inherits (or subclasses) attributes from BaseClass.

Types if inheritance A Base class There are different types of inheritance, they are

1. Single inheritance: - B It contains only one base class and only one derived class. Derived class

A Base class

2. Multi-level inheritance: - Derived / Base

B class If a class is derived from another derived class, It is called multilevel inheritance.

Pure Derived

B class

Multiple inheritances: - Base class B C If a class is derived from more than one base class, it is called multiple inheritances. Derived class

A

Base class 3. Hierarchical inheritance: - A

The process of inheriting the properties of one base class by more than one derived class is called hierarchical inheritance. B C

Derived class SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 48 Programming Basics

4. Hybrid inheritance: -It is a combination of single, hierarchical, multiple and multi-level inheritance. Here A is the base class, B and C are the derived classes of A. B and C are the base class of D. D is the base class of E.

A

B C

D

E

1. Single / Simple Inheritance: It contains only one base class and one derived class. That means, a class can be inherited by single base class. Syntax:

class BaseClassName(object): : class DerivedClassName (BaseClassName): : WAP to illustrate Single Inheritance (In the college notes) 2. Multi-level inheritance: -

A class is derived from another derived class is called multilevel inheritance. class BaseClassName(object): : class DerivedClassName-1 (BaseClassName): : class DerivedClassName-2 (DerivedClassName-1): : class DerivedClassName-3 (DerivedClassName-2): : SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 49 Programming Basics

WAP to illustrate Multi-level Inheritance (In the college notes) 3. Multiple inheritances: -

A class is derived from more than one base class, it is called multiple inheritances.

class BaseClassName-1(object): : class BaseClassName-2 (object): : class DerivedClassName-1 (BaseClassName-1, BaseClassName-2): : WAP to illustrate Multiple Inheritance (In the college notes)

4. Hierarchical inheritance: The process of inheriting the properties of one base class by more than one derived class is called hierarchical inheritance.

class BaseClassName(object): : class DerivedClassName-1 (BaseClassName): : class DerivedClassName-2 (BaseClassName): : WAP to illustrate Hierarchical Inheritance (In the college notes) Overriding methods Overriding methods allows a user to override the parent class method. That is use the same method both in base and child class. The name of the method must be the same in the parent class and the child class with different implementations.

The Python package

Python modules are a single file, whereas a Python package is a collection of modules. A package is a directory that contains Python modules. A package isa module that contains other modules. Some or all of the modules in a package may be sub packages, resulting in a hierarchical tree-like structure.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 50 Programming Basics

CHAPTER-4 Python MySQL Database 4.1 Introduction Few of the commonly used data base servers are supported by Python database API are MySQL, Oracle, Sybase, Informix, etc. MySQL is an open source relational database. In this chapter we will cover Python database API with MySQL database server which includes the following: - import MySQLdb - database connection - create database and tables - insertion, deletion, update, read SQL statements - Disconnecting database Python Database API supports a wide range of database servers such as −

 GadFly  mSQL  MySQL  PostgreSQL  Microsoft SQL Server 2000  Informix  Interbase  Oracle  Sybase

4.2 Structured Query Language(SQL) SQL is the database language used to create a database and perform various tasks like insert, delete, update etc. The SQL commands are mainly categorized into five categories as:

(i) DDL – Data Definition Language used to define the table structure. The following are DDL commands  CREATE – is used to create the database tables  DROP – is used to delete rows from the database.  ALTER-is used to alter the structure of the database.  RENAME –is used to rename an object existing in the database. (ii) DQL – Data Query Language is used to retrieve the data based (may certain condition) using SELECT command

(iii) DML – Data Manipulation Language is used to manipulate the data in the database The following are the DML commands  INSERT – is used to insert data into a table.  UPDATE – is used to update existing data within a table.  DELETE – is used to delete records from a database table. SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 51 Programming Basics

(iv) DCL – Data CONTROL Language mainly deals with rights, permissions and other controls of the database system.  GRANT-gives user’s access privileges to database.  REVOKE-withdraws user’s access privileges given by using the GRANT command. (v) TCL(transaction Control Language) : TCL commands deals with the transaction within the database. The commonly used TCL command are  COMMIT– commits a Transaction.  ROLLBACK– rollbacks a transaction in case of any error occurs.

4.3.1 Steps involved in connecting Database (MySQL) to Python

1. Install mysql.connector driver Install MySQL Connector Python using pip.

2. Import connector to python program Import mysql.connector

This line imports the MySQL Connector Python module in to program and we can use this module’s API to connect MySQL.

3. Create connection string by using connect() method The connect() function establishes a connection to the MySQL database from python application and returns a MySQLConnection object. This process automates logging into the database and selecting a database to be used. Then we can use MySQLConnection object to perform various operation on the MySQL Database.

Conn= mysql.connector.connect(host=’localhost’, database =’test’, user=’root’, password =’ ‘ )

4. Create cursor object Cursor object allows interacting with the database. The MySQLCursor class instantiates objects that can execute operations such as SQL statements.

Cur= conn.cursor()

5. Execute the sql-query After creating cursor object, execute SQL statements by following syntax.

Cur.execute(sql-query)

6. Save transaction After execute all your queries then save the transaction by using following statement.

Conn.commit()

7. Close connection object and cursor object. After your all transaction / activities are completes, close both connection and cursor which are opened. Conn.close() Cur.close()

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 52 Programming Basics

4.3.2 The Important Python Database functions

Closes the connection to the database (represented by the dbobject db.close() which is obtained by calling a connect() function)

db.commit() Commits any pending transaction to the database

db.cursor() Returns a database cursor object through which queries can be executed

Rolls back any pending transaction to the state that existed before the db.rollback() transaction began

The (readable/writable) number of rows that fetchmany() will return if no db.arraysize size is specified

Closes the cursor, this is done automatically when the cursor goes out of db.clone() scope

A read-only sequence of 7-tuples (name, type_code, display_size, db.description() internal_size, precision, scale, null_ok), describing each successive column of cursor c

Executes the SQL query in string sql, replacing each placeholder with the db.execute(sql) corresponding parameters given

Returns a sequence of all the rows that have not yet been fetched (which db.fetchall() could be all of them)

db.fetchmany(size) Returns a sequence of number of rows

db.fetchone() Returns the next row of the query result set as a sequence

db.rowcount() The read-only row count for the last execute method

4.4 Create database in MySQL with Python

To create a database in MySQL, use the "CREATE DATABASE" statement. The following python snapshot illustrate how to create database with name EMPdb importMySQLdb importmysql.connector db = mysql.connector.connect SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 53 Programming Basics

( host="localhost", user="root", passwd="root", ) mycursor =db.cursor() mycursor.execute("CREATE DATABASE EmpDB") db.close() 4.5Data Definition Language (DDL) 4.5.1 Create Table in MySQL with Python

To create a table in MySQL, use the "CREATE TABLE" statement. We need to define the name of the database while creating connection followed by creating table.

# Create Employee table sql = """CREATE TABLE EMPLOYEE ( EmpId INT AUTO_INCREMENT PRIMARY KEY, EmpName VARCHAR(20) NOT NULL, DeptNameCHAR(10), ExperienceYears INT, Salary FLOAT )""" mycursor.execute(sql)

# disconnect from server db.close()

4.5.2 Dropping table in MySQL with Python using DROP DROP command is used to delete a table from database.

Syntax DROP TABLE TableName sql = """DROP TABLE Employee"""

4.5.3 Change name of database table using RENAME RENAME command is used to change the name of existing database table.

Syntax RENAME TABLE currentTableName TO newTablename

sql = " " "RENAME TABLE Employee TO EMP " " " mycursor.execute(sql)

4.5.3 ALTER table in MySQL with Python Alter command is used for changing Table structure in SQL. Changing table structure includes change data type, change constraints, rename column name, adding new data field or removing data field.

(i) Modify data type using MODIFY Syntax : ALTER TABLE MODIFY column name

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 54 Programming Basics

The following code snippet illustrate how to alter the EmpId of Employee Table from INT to char(10) and remove the auto increment

sql = """ALTER TABLE Employee MODIFY EmpIdCHAR(6) PRIMARY KEY """ mycursor.execute(sql)

(ii) Adding new column to table using ADD Syntax : ALTER TABLE Tablename ADD columnname The following code snippet illustrate how to add new field Designation of Char data type to Employee table.

sql = """ ALTER TABLE Employee ADD DesignationCHAR(15) """ mycursor.execute(sql) (iii)Remove column from table using DROP Syntax : ALTER TABLE Tablename DROP columnname

The following code snippet illustrate how to remove Designation field from Employee table.

sql = """ ALTER TABLE Employee DROP Designation """ mycursor.execute(sql)

(iv) Changing column name using CHANGE Syntax : ALTER Table Tablenameoldnamenewname

The following code snippet illustrates how to rename column Salary to Income using CHANGE in Employee table.

sql = """ ALTER TABLE Employee CHANGE Salary Income """ mycursor.execute(sql)

5.6 Data Query Language (DQL)

Read data from table using SELECT SELECT command is used to fetch the data from the table. If no condition is specified in SELECT command then it fetches all contents of the table.

(i) Select all rows and all columns of a table Example 1: To illustrate use of SELECT command to fetch all the contents of Employee table and display the same.

sql = “”” SELECT * from Employee””” mycursor.execute(sql)

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 55 Programming Basics

(ii) Fetch selected columns from table Example 1.to illustrate use of SELECT command to fetch selected columns say EmpID and Salary from Employee table and display the same.

sql = “”” SELECT EmpId, Salary from Employee ””” mycursor.execute(sql)

(iii) Fetch selected rows from table using condition Example 1.to illustrate use of SELECT command to fetch selected rows columns say Employee details with salary > 60000 from Employee table and display the same.

sql = “”” SELECT * from Employee where Salary > 60000””” mycursor.execute(sql)

Example 2.llustrate use of SELECT command to fetch selected rows say Employee working for ‘Research’ department from Employee table and display the same.

sql = “”” SELECT * from Employee where DeptName= ‘ Research’ ””” mycursor.execute(sql)

(iv) Fetch selected rows and selected columns from table using condition Example 1.llustrate use of SELECT command to fetch selected rows and columns say Employee Id and Employee name working for ‘Research’ department from Employee table and display the same.

sql = “”” SELECT EmpId, EmpName from Employee where DeptName= ‘ Research’ ””” mycursor.execute(sql)

(v) Fetch selected rows from table using wildcard characters  Wildcard Percentage (% ) The % (percentage symbol) character is used to specify a pattern of zero (0) or more.

Example 1. Suppose we need to fetch the records with Employee name ending with ‘gowda’ as part of the name then this can be achieved using wildcard specified as ‘%gowda’ in Select command.

sql = """SELECT * FROM Employee WHERE EmpName LIKE '%Gowda' """ mycursor.execute(sql)

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 56 Programming Basics

Example 2. Suppose we need to fetch the records with Employee name ‘Kumar’ as part of the name (at the start, or end or in between), then this can be achieved using wildcard specified as ‘% Kumar%’ in Select command.

sql = "SELECT * FROM Employee WHERE EmpName LIKE '%Kumar%'" mycursor.execute(sql)

 Wildcard Underscore (_) To search patterns with only single character matching we can make use of wildcard single underscore(_). More than one ( _ ) underscore characters can be used to match a pattern of multiple characters.

Example1. To find employees whose qualification starts with ‘M’ and ends with ‘A’ with any one single character between M and A ( eg: MBA, MCA, etc) can be obtained as follows.

sql = “”"SELECT * FROM Employee WHERE Qualification LIKE 'M_A' "””

4.7 Data Manipulation Language (DML) 4.7.1 Insert records into Table using INSERT Assuming that Employee table has EmpId (char), EMPName(VARCHAR), DName(char) and Salary(INT) as attributes, the following code snippet illustrate the use of INSERT command to insert record into Employee table. We can insert one record or multiple records at the same time using INSERT command.

(i) Inserting one Employee record at a time into Employee using INSERT mycursor = db.cursor()

sql = " "" INSERT INTO Employee (EmpId, EMPName, DName, Salary) VALUES (‘E101’, 'AshaGowda', ‘Research’,50000)""" mycursor.execute(sql)

(ii) Inserting multiple Employee records at a time into Employee using INSERT

sql = "" " INSERT INTO Employee (EmpId, EMPName, DName, Salary) VALUES (%s, %s, %s,%d)" ”” val = [ (‘E101', 'AshaGowda', ‘Production’, 50000), (‘E102', 'Abhishek ', ‘ Architecture’, 60000), (‘E103', 'Mahesh ', ‘ Marketing’, 55000), (‘E104', 'Mukundappa ', ‘ Finance’, 75000), ] mycursor.executemany(sql, val)

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 57 Programming Basics

4.7.2Delete records using DELETE The DELETE command can delete more than one row from a table in a single query.Once a row has been deleted, it cannot be recovered. Syntax: DELETE FROM `table_name` [WHERE condition]; If where clause is not used all the records of the table are deleted. If where condition is used then records which satisfy the condition are deleted.

Example 1. Delete records with employee name as ‘AshaGowda’ sql = “”” DELETE FROM Employee WHERE EmpName = ‘AshaGowda’ “”” mycursor.execute(sql)

Example 2. Delete records with employee salary less than 5000 DELETE FROM Employee WHERE Salary < 5000 mycursor.execute(sql)

Example 3. Delete all employee records with employee name beginning with ‘A’ DELETE FROM Employee WHERE EmpName LIKE ‘A%’ mycursor.execute(sql)

Example 4. Delete all employee records with employee name containing ‘Kumar’ DELETE FROM Employee WHERE EmpName LIKE ‘%Kumar%’ mycursor.execute(sql)

4.7.3 Update records using UPDATE UPDATE statement is used to update existing records in a table. Syntax :

UPDATE Tablename SETColumnname =newvalueWHERE Columnname = oldvalue

Example 1.Update salary of employee with EmpId as E105 to 80000

sql = “”” UPDATE EmployeeSET Salary = 80000 WHERE EmpId = ‘E105’ “”” mycursor.execute(sql)

Example 2. Update salary of all employeesworking for ‘Research’ department with 80000

sql = “”” UPDATE Employee SET Salary = 80000 WHERE DeptName = ‘Research’ “”” mycursor.execute(sql)

Example 3. Update multiple fields : update salary to 50000 and DeptName as ‘Production’ for employee with employee id as E189. sql = “”” UPDATE Employee SET Salary = 50000, DeptName = ‘Production’ WHERE EmpId = ‘E189’ “”” mycursor.execute(sql)

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 58 Programming Basics

Example: importmysql.connector conn=mysql.connector.connect(host='localhost',database='test',user='root',password='') cur=conn.cursor() str1='''CREATE TABLE emp(eno int(4) ,name char(20),sal float)''' cur.execute(str1) str2='INSERT INTO emp(eno,name,sal) VALUES (101,’maya’,34000.90)' cur.execute(str2) str3='INSERT INTO emp(eno,name,sal) VALUES (102,’asha’,23000.90)' cur.execute(str3) conn.commit() cur.execute("Select * from emp") row=cur.fetchall() print("total row=",cur.rowcount) for r in row: print(r) cur.close() conn.close()

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 59 Programming Basics

Chapter-5

Graphical User Interface

The user can interact with an application through graphics or an image is called GUI [Graphical User Interface]. Here the user need not remember any commands. User can perform task just by clicking on relevant images.

Advantages:

1. It is user friendly.

2. It adds attraction and beauty to any application by adding pictures, colors, menus, animation.

3. It is possible to simulate the real life objects using GUI.

4. GUI helps to create graphical components like push button, radio button, check box, text box, menus etc.,

GUI in Python:

Python offers tkinter module to create graphical programs. The tkinter represents ‘toolkit interface’ for GUI. This is a interface for Python programmers that enable them to the classes of TK module of TCL/TK [Tool Command Language]. TCL language use TK[Tool Kit] language to generate graphics.

General steps involved in basic GUI programs:

1. Create a root Window: The root window is the top level window that provides rectangular space on the screen where we can display text, color, images, etc.,  First import tkinter module from tkinter import *  root=Tk() # create root window object. 2. Create a Canvas / Frame : Canvas and frame are child windows in the root window. C=Canvas(root, bg=‘blue’, height=500,width=400,cursor=‘pencil’) Cursors are – circle, hand1, hand2, heart, pencil, plus, mouse, star, watch etc… 3. Create Widgets – Components : For Canvas – create line, circle, rectangle, any geometric objects For Frame – buttons, text box, list , check box etc… 4. Create a Event Handler Write the function for corresponding event.

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 60 Programming Basics

WAP to draw line, oval, polygon, rectangle and text from tkinter import * root=Tk() root.title ("My Window") #root.geometry ("400x300") c=Canvas(root,bg="blue",height=700,width=1200,cursor='pencil') id=c.create_line(50,50,200,50,200,150,width=4,fill="white") id=c.create_oval(100,100,400,300,width=2,fill="yellow" , activefill="blue") id=c.create_polygon(10,10,200,200,300,200,width=3,fill="green",outline="red",activefill="Pink") id=c.create_rectangle(500,200,700,600,width=2,fill="gray",outline="yellow",activefill="green") fnt=('Times',40,'bold italic underline') id=c.create_text(500,100,text="Python Graphics", font=fnt, fill="White", activefill="red") c.pack() root.mainloop()

Frame: A frame is similar to canvas, but it can hold components of forms. To create a frame, we can create an object of Frame class as : F= Frame(root, height=400,width=500,bg=“yellow”,cursor=“cross” Here, ‘F’ is an object of class Frame, the options height and width reprsents the area of frame in pixels, ‘bg’ represents the back ground color to be displayed and ‘cursor’ indicates the type of the cursor to be displayed in the frame. Once the frame is created, it should be added to the root window using the pack() method.

Widgets/ form elements: Widgets is a GUI component that is displayed on the screen and can perform a task as designed by the user. The widgets are:

1. Button 2. Label 3. Text box 4. Message 5. Checkbox 6. List box 7. Option button 8. Scroll bars 9. Menus

Steps to create a Widgets

1. Create a widget object B=button(f, text=“Submit”) 2. Define the event performed by the widget def buttonClick(self) : print(“You have clicked submit button”) 3. Clicking event should be linked with the callback handler B.bind(‘’, buttonClick) 4. Call event loop root.mainloop()

1. Button: A push button is a component that performs some action when clicked. These buttons are created as objects of Button class as,

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 61 Programming Basics

b=Button(f, text="Ok", width=15,height=3, bg="yellow", fg="blue")

Here, ‘b’ is the object of Button class, ‘f’ represents the frame for which the button is created as a child. The ‘text’ option represents the text to be display on the button, width and height represents the size of the button, ‘bg’ represents the background color and ‘fg’ represents the fore ground color of the button,

b.bind("", buttonClick) We link the mouse left button with the buttonClick( )method using bind()method.

2. Text: A text widget is same as label. But text widget has several options and can display multiple lines of text in different colors and fonts. It is possible to insert text into a text widget, modify it or delete it. We can also display images in the text widget. A text is created as an object of Text class as, t=Text(f,width=20, height=3, font=('Times',20,'italic'), fg='blue', bg="yellow", wrap=WORD) Here, ‘t’ is the object of Text class, ‘f’ represents the frame for which the text is created as a child. The width and height represents the size of the text box, ‘bg’ represents the background color and ‘fg’ represents the fore ground color of the text, ‘font ‘ represents a tuple that contains font name, size and style. The ‘wrap’ represents the text information can be align with in the text box.

3. Label: A label represents the constant text that is displayed in the frame or container. A label can display one or more lines of text that cannot be modified. A label is created as an object of Label class as,

l=Label(f, text=" Label Demo",width=25,height=3, font=('Times',14,'bold'), fg='blue',bg='yellow')

Here, ‘l’ is the object of Label class, ‘f’ represents the frame for which the button is created as a child. The ‘text’ option represents the text to be display on the Label box, width and height represents the size of the label, ‘bg’ represents the background color and ‘fg’ represents the fore ground color of the label, ‘font ‘ represents a tuple that contains font name, size and style.

4. Check button: Check buttons are also known as check boxes are useful for the user to select one or more options from available group of options. Check buttons are displayed in the form of square shaped boxes. When check box is selected, a tick mark is displayed on the check box. Check box is created as an object of Checkbutton class as,

c1=Checkbutton(f, text="Python", bg='yellow', fg='red', font=('Times',20,'italic'))

Here, ‘c1’ is the object of Checkbutton class, ‘f’ represents the frame for which the check button is created as a child. The ‘text’ option represents the text to be display on the check box, ‘bg’ represents the background color and ‘fg’ represents the fore ground color of the check box, ‘font ‘ represents a tuple that contains font name, size and style. SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 62 Programming Basics

5. Radio button: A radio button is similar to a check box, but it is used to select only one option from a group of available options. A radio button is displayed in the form of round shaped button. The user cannot select more than one option. When a radio button is selected, there appears a dot in the radio button. We can create a radio button as an object of the Radiobutton class as,

r1=Radiobutton(f, text="male", bg='green', fg='red', font=('Times',20,'italic'), value=0)

Here, ‘r1’ is the object of Radiobutton class, ‘f’ represents the frame for which the radio button is created as a child. The ‘text’ option represents the text to be display on the radio button, ‘bg’ represents the background color and ‘fg’ represents the fore ground color of the radio button, ‘font ‘ represents a tuple that contains font name, size and style, ‘value’ represents a value that is set to this object when the radio button is clicked..

WAP to illustrate button, label, text, checkbox and radio button from tkinter import * def buttonClick(self): print ("You have cliked Ok button") root=Tk() root.title ("Button Example") f=Frame(root,bg="blue",height=700,width=1200,cursor='cross') f.propagate(0) f.pack() b=Button(f, text="Ok", width=15,height=3, bg="yellow", fg="blue") b.pack() b.bind("", buttonClick) l=Label(f, text=" Label Demo",width=25,height=3, font=('Times',14,'bold'), fg='blue',bg='yellow') l.pack() t=Text(f,width=20, height=3,font=('Times',20,'italic'),fg='blue',bg="yellow",wrap=WORD) t.insert(END," Text Demo") t.pack(side=LEFT) c1=Checkbutton(f, text="Python",bg='yellow',fg='red', font=('Times',20,'italic')) c1.pack(side=LEFT) c2=Checkbutton(f, text="Networking",bg='yellow',fg='red', font=('Times',20,'italic')) c2.pack(side=LEFT) c3=Checkbutton(f, text="Java",bg='yellow',fg='red', font=('Times',20,'italic')) c3.pack(side=LEFT)

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 63 Programming Basics

r1=Radiobutton(f, text="male", bg='green',fg='red', font=('Times',20,'italic'),value=0) r1.pack(side=LEFT) r2=Radiobutton(f, text="female", bg='green',fg='red', font=('Times',20,'italic'),value=1) r2.pack(side=LEFT) root.mainloop()

5.10 Visualization/Graphic using Python In this section we will learn how to plot pie chart, bar chart, histogram, line chart and scatter plot using matplotlib. Matplotlibis package for creating2D plots and graphs. This package is not part of python pakage and hence need to installed. In anaconda the matplotlib is readily available. The following programs on graphics are executed on jupitor anaconda.

Program 5.10.1 : Python program to plot Pie chart # plot Pie chart based on % jobs based on computer subjects importmatplotlib.pyplot as plot # Data to plot Subjects = 'Python', 'C++', 'WebTechnology', 'Java', 'DataMining' JobCount = [200, 250, 75, 200, 150] colors = ['red', 'orange', 'blue', 'black','green'] # Plot Pie chart plot.pie(JobCount,labels=Subjects,colors=colors,autopct='%1.2f' ) # title for pie chart plot.title("Piechart for of % of Jobs based on Computer subjects", bbox={}) # display pie chart plot.show()

Figure 5.10.1 Pie chart usingmatplotlib.pyplot

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 64 Programming Basics

Program 5.10.2 : Python program to plot Histogram

importmatplotlib.pyplot as plot Age = [ 20, 30, 10, 10, 30, 30, 10, 10, 10, 40,40, 50,50,50] # Plot histogram for Age plot.hist(x1, facecolor='red', edgecolor='yellow') plot.title("Histogram for Age") # display histogram plot.show()

Figure 5.10.3 Histogram plot using matplotlib.pyplot

Program 5.10.3: Python program to Line chart importmatplotlib.pyplot as plt X = [ 3,5,7,8,15,18] Y = [ 10,15, 18, 22, 24, 25] plt.title("Line chart ") plt.plot(X,Y) plt.show()

Figure 5.10.4 Line chart(bold) using matplotlib.pyplot

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 65 Programming Basics

Program 5.10.4 : Python program to plot two line chart importmatplotlib.pyplot as plt X = [ 3,5,7,8,15,18] Y = [ 10,15, 20, 22, 24, 22] X1 = [ 5,8, 9, 15, 20] Y1 = [ 5,8,10, 15,20] # Plot two lines together, X and Y line in ‘g- -‘ plot dashed line in green color # X1 and Y1 as red color line plt.plot(X,Y,'g--', X1,Y1, 'r') #plt.plot(X1,Y1,'g') #plt.ylabel('some numbers','bs') plt.show()

Figure 5.10.6 Bold and Dashed Line chart using matplotlib.pyplot

Program 5.10.5 : Python program to plot Barchart

importmatplotlib.pyplot as plt Course = ('BCA', 'BCOM', 'BA', 'BSC-CS', 'BSC-Agri') NumOfStudents = [40, 15, 30, 20, 10] plt.bar(Course, NumOfStudents) plt.ylabel('Numbber of Students') plt.title('Bar chart indicating Students admission for various courses') plt.show()

SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 66 Programming Basics

Figure 5.10.7 Bar chart usingmatplotlib.pyplot

Label, Text, Command Button, Check box and Radio buttons: from tkinter import * def buttonClick(self): print ("You have cliked Ok button")

root=Tk() root.title ("All Form Elements Example") f=Frame(root,bg="blue",height=700,width=1200,cursor='cross') f.propagate(0) f.pack()

b=Button(f, text="Ok", width=15,height=3, bg="yellow", fg="blue") b.pack() b.bind("", buttonClick)

l=Label(f, text=" Label Demo",width=25,height=3, font=('Times',14,'bold'), fg='blue',bg='yellow') l.pack()

t=Text(f,width=20, height=3,font=('Times',20,'italic'),fg='blue',bg="yellow",wrap=WORD) t.insert(END," Text Demo") t.pack(side=LEFT)

c1=Checkbutton(f, text="Python",bg='yellow',fg='red', font=('Times',20,'italic')) c1.pack(side=LEFT) c2=Checkbutton(f, text="Networking",bg='yellow',fg='red', font=('Times',20,'italic')) c2.pack(side=LEFT) c3=Checkbutton(f, text="Java",bg='yellow',fg='red', font=('Times',20,'italic')) c3.pack(side=LEFT) SSCW, Tumkur Mahesha S , Cell : 9886044689

VI Sem B.Sc / BCA 67 Programming Basics

r1=Radiobutton(f, text="male", bg='green',fg='red', font=('Times',20,'italic'),value=0) r1.pack(side=LEFT) r2=Radiobutton(f, text="female", bg='green',fg='red', font=('Times',20,'italic'),value=1) r2.pack(side=LEFT)

root.mainloop()

SSCW, Tumkur Mahesha S , Cell : 9886044689