Python 3 For beginners

Page 1


AI HUB’S

ULTIMATE GUIDE TO PYTHON BASICS

DIWAS PANDEY SUNIL GHIMIRE 2020


"To our family, relatives, friends and all belovedâ€?Â


TABLE OF CONTENTS INTRODUCTION​…………………………….………….……………....……….……....1 PYTHON IN AI​……………………….……………………………………...……...2 INSTALLING PYTHON​…………………….……………………….…………….….….3 INSTALLING ON WINDOWS​………….. …………………….………………...…..3 INSTALLING ON LINUX​………………..…………………….………………….....4 HELLO WORLD!​ ………………………………………….………………………...…...5 WHAT IS PYTHON INTERPRETER?​ …………………….…..…...…...………….....6 INDENTATION​……………………………………………….….………………………..7 VARIABLE​……………………………………………………….………………………..8 USER INPUT​…………………………………………………………...….……………..12 DATA TYPES​…………………………………………………………….…………….....16 NONE……………………………………………………………………………………....17 NUMBERS………………………………………………………………………………....17 STRINGS……………………………………………………………………………….….20 LIST​…………………………………………………………….……………...…...30 TUPLE​…………………………………………………………….………………..35 SET​…………………………………………………………….…………………...38 DICTIONARY​……………………………………………………….……………...43 BOOLEAN​…………………………………………………………….…………....49

OPERATORS IN PYTHON​………………………………………………………...........51 ARITHMETIC OPERATOR​……………………………………………………....…52 ASSIGNMENT OPERATOR​………………………………………………………...53 LOGICAL OPERATOR​……………………………………………………………..56 BITWISE OPERATOR​……………………………………………………………...56 RELATIONAL OPERATOR​………………………………………………………...58 IDENTITY OPERATOR​………………………………………………………….....60 MEMBERSHIP OPERATOR​………………………………………………………..61 OPERATOR PRECEDENCE​………………………………………………………..62 CONDITIONAL & LOOP​……………………………………………………………....63 IF ELSE STATEMENT​………………………………………………………….......64 FOR LOOP​…………………………………………………………………….…...71 WHILE LOOP​……………………………………………………………….……..76 BREAK & CONTINUE​……………………………………………………..………80 PASS​…………………………………………………………………….…………83 PROGRAMMING EXAMPLES​………………………………………….…………….84


FUNCTION IN PYTHON​……………………………………………..………………93 DEFINITION​…………………………………………………………..…………94 DEFAULT ARGUMENTS…………………………………………….………………..95 ARBITRARY ARGUMENTS…………………………….…………………………….96 LAMBDA FUNCTION………………………………….……………………………...97 FUNCTION OVERLOADING​……………………..…………………………….100

PROGRAMMING EXAMPLES​……………………..……………………………....101 RECURSION​…………………………………….…………………………………....104 PYTHON AS OOP​………………………….…………..…………………………….107 CLASS & OBJECT​……………………..…………………………………………….110 CLASS​………………………..………………………………………………....110 OBJECT​…………………..……………………………………………………..111 CONSTRUCTOR​…….………………………………………………………….113 DESTRUCTOR​….………………………………………………………………115 INHERITANCE​………………………………………………………....…….....116 POLYMORPHISM​……………………………………………………….……...117 ARRAY​…………………………………………………………………….…………..119 LIST INTO ARRAY​…………………………………………….…………….…126 FILE HANDLING​……………………………………………….…………………...128 MISCELLANEOUS​………………………………………….……………………....132


1 INTRODUCTION

Python is the most popular general-purpose, high-level programming language which was created in 1991 by ​Guido van Rossum and developed by Python Software Foundation with the goal of concentrating on the readability of code with its extensive use of white space. The Python development team was inspired by the British comedy group Monty Python to make a programming language that was fun to use. Python was named after the BBC show “​Monty Python’s Flying Circus​” as he was a big fan of the TV show. Used in various purposes such as developing, scripting, generation, and software testing, this language is mostly used in the field of Artificial intelligence as it is open-source, free, dynamic, portable, easy to code and integrated language (python can be integrated with other languages like c, c++, etc.) Python, being a cross-platform language, can run on various platforms like Linux, Windows, Mac, Raspberry pi, etc. Python is much more efficient as developers are allowed to write programs with fewer lines of code than other programming languages. Python code is executed line by line at a time so it is also known as an interpreted language. Python relies on indentation, using white space, to define scope, whereas Other programming languages often use curly-brackets for this purpose. We can split the program in various modules which can later be used in other programs.

1


WHY PYTHON IN AI ??? We use Python because Python Programming language can be close to pseudo-code which is extremely versatile and popular among developers. Python is called General Purpose language (GPL) because it is used in Machine Learning, GUI development, software development, Data Science, and many more. Python is a very human-readable programming language for those with an understanding of English which allows for easy comprehension because Python supports various types of object-oriented programming and objects. Python is considered as a multi-paradigm language that allows programmers to use the most acceptable style to complete a project. Python provides a great deal of promise to those who want to start coding while also being a decent option for those who want to pick up an additional programming language. Learning Python’s core concepts and computer programming can offer you both as a user and as a developer to understand how programs function works while also conveying simple reasoning that can support you in other fields. Python is widely considered as the preferred language for Artificial Intelligence. Python helps developers be productive and confident about the software they’re building from development to deployment and maintenance. Simplicity and consistency, access to great libraries and frameworks for AI and machine learning (ML), flexibility, platform independence, and a wide community are the main reasons for python being used in the field of Artificial Intelligence. The Python AI Community has grown gradually across the globe. Scientific Python packages such as Numpy, Scipy, and Matplotlib can be installed in a program running on Python. Apart from Python, Matlab, & R are also used.

2


2 INSTALLING PYTHON

Because of its simplicity in syntax, python is a great choice for beginners to experienced developers. This tutorial teaches you how to install python on windows as well as various Linux distributions. Most of the devices come with previously installed python. To see the version of python installed open command prompt/terminal and run the following code. >>> python3 --version

INSTALLING ON WINDOWS: PREREQUISITES ● A system running Windows 10 with admin Privileges ● Command Prompt (comes with windows by default) ● A Remote Desktop connection app(use if you are installing Python to a remote Windows server)

STEPS ● ● ● ● ● ●

Download Python Executable Installer (​click here​ ) Run Executable Installer Verify Python was installed on windows Verify Pip was installed Add Python Path to environment Variables (optional) Install virtual environment (optional)

3


“ Add Python 3.x to PATH to ensure that the interpreter will be placed in your execution path. “

INSTALLING ON LINUX: If you are using Ubuntu and derived OS then you can install python using following command : $ sudo apt-get install software-properties-common $ sudo add-apt-repository ppa:deadsnakes/ppa $ sudo apt-get update $ sudo apt-get install python<version> # like python3.8.1 If you are using Arch Linux or Manjaro, you can run the following code: $ sudo pacman -S python If you are on Red Hat/RHEL/CentOS, you can install python using following command : $ sudo yum install python Hurray! You have installed python on your device. Now you are one step closer to developing your first python project. If you have any questions or feedback, feel free to contact us on ​aihubprojects.com​.

4


3 HELLO WORLD!

Python interpreter is usually installed at /usr/local/bin/python3.# on Linux and in C:\Program Files\Python37\ on windows devices. We can write the program using a text editor like gedit, vim, Jython, IronPython, IDLE, ActivePython, Wing IDE, pydev, etc. The interpreter is said to be in interactive mode when interpreter displays its copyright message and presents the user with the >>> prompt. For continuation lines it prompts with the (…) secondary prompt. $ python Python 3.8.1 (default, Jan 8 2021, 22:29:32) Type "help", "copyright", "credits" or "license" for more information. >>> In the interactive shell, we can execute the valid statement or sequence of statements and can instantly execute and view the output. >>> 5 + 7 12 Python source files are ordinary text files and normally have a .py suffix. Python source files are treated as encoded in UTF-8. For debugging, it is better to run the program within a Python development tool such as IDLE. To execute the .py file, you can enter the command on interpreter/terminal as follows: $ python <filename>.py

# example: python firstprogram.py

5


Let’s try some simple Python commands. Start the interpreter and wait for the primary prompt,>>>. “Hello World” is the first program that a programmer runs after setting up their environment for the first time to verify that the environment is set up and working. >>> print (" Hello World ") Output: Hello World Let’s break our above code. ​print ( ) function is the built-in function in Python 3 that is used to print the specified message and other standard output whatever we put inside the parentheses ( ) to the screen. This function is always available for us to use in programs that we created which tells the computer to perform certain tasks. Within, the ​print ( ) function’s parentheses are a sequence of characters “​Hello World​” which is enclosed inside the quotation marks. Thus, we can say that any character that is enclosed inside the quotation marks is called a s​ tring​.

WHAT IS PYTHON INTERPRETER? This is the program that knows how to translate or interpret our Python code into instructions that a computer can understand. First it executes line 1, then moves on line 2 and so on. So this is how python programs get executed. >>> print (5+6) 11 >>> 7+8 15 >>> 9*6 54

6


4 INDENTATION

Spaces or tabs used in the beginning of the code is known as indentation. Indentation is used to python to indicate which block of code a statement belongs to. You must indent each line of the block by the same amount of spaces or tabs. >>> if 5 > 2: print("Five is greater than two!") print(" You must indent each line by the same amount") Output: Five is greater than two! You must indent each line by the same amount Python will give you an error if you skip the indentation. The number of spaces is up to you as a programmer, but it has to be at least one. Four spaces are typical indent used in python. >>>if 5 > 2: print("Five is greater than two!") Output: Indentation error!

#without indentation

7


5 VARIABLES

Variable is defined as the reserved memory location to store the value. Various data types like Numbers, List, Tuple, Strings, Dictionary, etc are used in python and hence these values are stored in the variables. We start with an identifier which is the name of our variable then equal sign and finally a value. >>> a = 5 # a is variable >>> print(a) Output: 5 We can re-declare the variable even though it is declared above. It stores the newly assigned value replacing the old value assigned to it. >>> a = 10 >>> a =56 # reassigning the value to variable >>> print( a ) Output: 56 Let’s try something different: >>> a = 6 >>> del a >>> print (a) 8


Output: Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'a' is not defined Here, we delete variables using the command del. In the above example, we deleted variable a, and when we proceeded to print it, we got the error “name ‘a’ is not defined” which means you have deleted the variable.

RULES OF DECLARING VARIABLES : 1. A variable name must start with a letter or the underscore character 2. A variable name cannot start with a number 3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) 4. Variable names are case-sensitive (age, Age and AGE are three different variables)

PROBLEM 01: ADD TWO NUMBERS

>>> a = 3 >>> b = 5 >>> c = a+b >>> print ( "sum of " , a , " & " , b , " is " , c) Output: Sum of 3 & 5 is 8

9


PROBLEM 02: AREA OF RECTANGLE

>>> l = 5 >>> b = 4 >>> area = l*b >>> print ( "Area of rectangle is ",area) Output: Area of rectangle is 20

PROBLEM 03: SWAP TWO NUMBERS

>>> a = 6 >>> b = 9 # swapping variable by introducing new variable >>> c = b >>> b = a >>> a = c >>> print ("a = ",a) >>> print ("b = ",b) >>> a = 6 >>> b = 9 # swapping without new variable using addition & Subtraction >>> a = a+b >>> b = a-b >>> a = a-b >>> print ("a = ",a) >>> print ("b = ",b) 10


>>> a = 6 >>> b = 9 # swapping without new variable using multiplication & division >>> a = a*b >>> b = a/b >>> a= a/b >>> print ("a = ",a) >>> print ("b = ",b) >>> a = 6 >>> b = 9 # using swap construct >>> a,b = b,a >>> print ("a = ",a) >>> print ("b = ",b) All these four programs can be used to swap numbers in python. In the above program we finally obtain the output as a = 9 and b = 6. Let’s wrap up variables topic with another example : >>> var_1 = " Diwas " >>> x, y, z = "Orange", "Banana", "Cherry" >>> a = b = 34 >>> print("I am " + var_1) I am Diwas >>>print (x) Orange >>> print (a) 34 >>> print( a+b) 68

11


6 USER INPUT

In our previous tutorial, we learned how to print messages as output and indentation rules. In this tutorial, we will learn how to receive input from the user. To obtain data or to send any results, developers must communicate with the user. For this reason, Python provides two built-in functions to get/read the user data which is slightly different from other programming languages because most programming languages use a dialog box as a way to ask the user to provide some sort of feedback. >>> x = input ( " enter anything " ) Input ( ) function takes user input and then evaluates the expression which means Python determines automatically if the user has entered a string or a number or a list. By default, data from the user is stored as a string. Let’s take an example : >>> a = input (" enter a value : ") >>> print (type(a)) Output: enter a value : 8 <class 'str'>

“ We assign data types to the user input variable introducing int, float, str, and so on. S ​ ee more ​>> “ 12


PROBLEM 04: ASK NAME & GREET USER! Both these input ( ) and print ( ) are the built-in functions in Python. For the above-mentioned question, we are going to call the input function and in between parentheses we are going to add a command which gets printed on the terminal and gives instruction to the user. So, these text inside parentheses print messages on the terminal and it will wait for the user to enter a value. Whatever the user enters in this input function, is temporarily stored in the memory using a variable, for our case name is the variable​. >>> name = input('What is your name? : ') >>> print('Hi', name, ‘! Welcome to Python Tutorial !! ’) OUTPUT: What is your name? : John Hi John! Welcome to Python Tutorial !! Let’s extend the above program and ask two questions. First, the person's name, and secondly their favorite programming language. And then print a message in the pattern like ABC likes Python. >>> name = input('What is your name? : ') >>> fav_language = input('Which is your favorite programming language? : ') >>> print(name , 'likes ', fav_language) OUTPUT: What is your name? : ABC Which is your favorite programming language? : Python ABC likes Python

13


PROBLEM 05: ADD TWO NUMBER

>>> a = int(input ("enter first number: ")) >>> b = int(input ("enter second number: ")) >>> c = a+b >>> print ( "sum of ",a," & ",b," is ",c) Output: enter first number: 4 enter second number: 67 sum of 4 & 67 is 71

PROBLEM 06: FIND SIMPLE INTEREST

>>> p = int(input ("enter principal amount : ")) >>> t = int(input ("enter time period : ")) >>> r = int(input ("enter interest rate : ")) >>> si = (p*t*r)/100 >>> print("simple interest is : Rs", si) Output: enter principal amount : 100 enter time period : 1 enter interest rate : 10 simple interest is : Rs 10.0

14


PROBLEM 07: CONVERT METER TO KILOMETER >>> m = float(input ("enter length in meter : ")) >>> km = m/1000 >>> print (m," meter is equivalent to ",km,"kilometer") Output: enter length in meter : 450 450.0 meter is equivalent to 0.45 kilometer

PROBLEM 08: CONVERT CELSIUS TO FAHRENHEIT

>>> c = float(input("enter temperature in celsius : ")) >>> f = c *1.8+32 >>> print (c,"celsius is equivalent to ", f ,"Fahrenheit") Output: enter temperature in celsius : 37 37.0 celsius is equivalent to 98.60 Fahrenheit

PROBLEM 09: FIND AREA OF RECTANGLE

>>> l = int(input ("enter length : ")) >>> b = int(input ("enter breadth : ")) >>> area = l*b >>> print ( "area of rectangle is ",area) Output: enter length : 4 enter breadth : 5 area of rectangle is 20 15


7 DATA TYPES

The variable data type is automatically determined by Python. Variables can store data of different types. Python has the following data types built-in by default, in these categories: 1. None 2. Numeric 3. String 4. List 5. Tuple 6. Set 7. Dictionary (Map) To find the data type we use built-in function type( ). Within the brackets, we must place the name of the variable or type of value which we want to verify. So, for the following example we are placing different types of value to know its data-type. After executing the code, the result we obtain is “int”, “float”, or data-type which indicates the value may be “int”, “float” or other. >>> a = 3 >>> b = 3.33 >>> c = 3j >>> d = "diwas" >>> print (type(a)) >>> print (type(b)) >>> print (type(c)) >>> print (type(d))

# integer # float # complex #string

16


Output : <class 'int'> <class 'float'> <class 'complex'> <class 'string'>

7.1 NONE If you have a variable and if this variable is not allocated with any value, we usually use a keyword as null in other languages, but we use ​None in Python. >>> b = None >>> print (type(b)) Output: <class 'NoneType'>

7.2 NUMBERS Python numbers include integer (int), floating numbers (float), and complex numbers (complex). You can get the data type of any object by using the type() function.

7.2.1 INTEGERS

Integers are the positive or negative numbers without decimal values. There is no limit for integer precision but they are limited by available memory size. 17


>>> print (type(3)) >>> print (type(333333)) >>> print (type(-3)) Output: <class 'int'> <class 'int'> <class 'int'>

7.2.2 FLOATING NUMBER Floating Numbers are the positive or negative numbers including decimal values. A floating-point number is accurate up to 15 decimal places. Floats can also be scientific numbers with an “e” to indicate the power of 10. Division (/) always returns a float. >>> print (type(3.0)) >>> print (type(3.376375738)) >>> print (type(-4.755797)) >>> print (type(3.4e4)) >>> print (type(1.1e-1)) OUTPUT: <class 'float'> <class 'float'> <class 'float'> <class 'float'> <class 'float'>

18


7.2.3 COMPLEX NUMBER Complex Numbers are the combination of real part ‘x’ and imaginary part ‘y’ written in the form of x+yj. >>> a= 4+5j >>> print (type(a)) Output: <class 'complex'>

“​Python adopted the convention used by electrical engineers. In that field, i is used to represent current and use j as the square root of -1​ “

TYPECASTING Typecasting is used in python to convert one data type to another. In this tutorial we will learn to convert Integer into different bases like hex, oct, binary, and also to float numbers.

SYNTAX FUNCTION

EXAMPLE OUTPUT

int ( )

converts​ a​ ny data type to integer

int(3.4)

3

float ( )

converts any data type to float

int (3)

3.000

hex ( )

convert integer to hexadecimal string

hex(115)

‘0x73’

oct ( )

convert integer to octal string

oct(32)

‘0o40′

19


So far, we have covered all about ​introduction to python, we have written the first ​python program “HELLO WORLD ! “, we have learned about indentation​, ​variables​, and user inputs​. In our last tutorial we learned about data types and ​Numeric data types like integer, float, and complex numbers. Now, it's time to check your knowledge. Participate in a python quiz and test how far you have learned. Check our python Quiz now !! ● Python Quiz – 01 In this tutorial we are going to learn more about Python strings. We’ll learn how to create, edit, and remove lines, also learn about associate operations and string functions. Now let's start from the beginning, what are strings?

7.3 STRINGS Strings are one of the most popular aspects of python which can be created by adding single or double quotes around characters. Strings in python are created using single (‘ ‘), double (” “) or triple (”’/ “””) quotes terminated by corresponding quotes. Triple-quoted strings are useful when the contents of a string literal span multiple lines of text. >>> corona = 'stay home ! stay safe ' In the example above, we have declared a variable corona and defined it as string value ‘stay home ! stay safe ‘ using a single quote. Similarly, we can use double quotes as well. >>> corona = "I will stay home " Imagine, if you want to change ​I will stay at home to I'll stay at home​. Now you will run into problems because the string ‘I’ starts and ends here. And 20


all the characters after the second apostrophe python interpreter do not know what they are. >>> corona = 'I'll stay home' Output : SyntaxError: invalid syntax So to solve this problem, we are going to use double quotes to define our string and we have a single quote in the middle of our string. Example is shown below: >>> corona = "I'll stay home" >>> print (corona) Output: "I'll stay home" What will you do to print `I stay at “home” ’? For this kind of problem, we are going to use a single quote to define our string and use double quotes in the middle of the string. Let’s see the example below: >>> quarantine = 'I stay at "home"' >>> print(quarantine) Output : 'I stay at "home" ' So far we only deal with single and double quotes, what if you wanted to define multiple line strings. For example, what if you want to define a string for the message that we send in an email. In that case we are going to use triple quotes to define our string. 21


Let see the example below: >>> quarantine = ''' ... Hi Bae, ... Here is my first email to you ... Please stay at home ... Thank you, ... Your Sunil ... ''' >>> print (quarantine) Output: Hi Bae, Here is my first email to you Please stay at home Thank you, Your Sunil

SLICING Slicing operator [ ] can be used with string. Strings are stored as sequences of characters indexed by integers, starting at zero. To extract a single character, use the indexing operator s[i] like this: >>> s="sawid" >>> print (s[1]) Output: a Here output is ‘a’ since s[0]=’s’, s[1]=’a’, and similarly s[4]=’d’. As square brackets can be used to access elements of the string, we can access the range of characters using slicing. To obtain certain parts of characters we specify the starting and ending index separated by a colon ‘:’. 22


+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1 >>> a = 'Python' >>> c = a[2:4] >>> print (c) Output: th Here, we have assigned the starting index 2 i.e ‘t’ and ending index 4 i.e 0. But the character of index 4 is ignored and only 2nd and 3rd indexed characters are shown. This extracts all characters from s[i:j] whose index is in the range i<=k<j. If either index is omitted, the beginning or end of the string is assumed, respectively: Similarly, we can use negative slicing as follows: >>> c = a[-4:-2] >>> print( c ) Output: h In negative slicing, starting and ending indexes are reversed and a negative sign(-) is introduced before them.

“​In slicing, the start is always included, and the end always excluded​ “ 23


quarantine = 'I will stay at home' print('String -->',quarantine) print('To get first character of string -->',quarantine[0]) print('To get last character of string -->', quarantine[-1]) print('To get second last character of string -->', quarantine[-2]) print('Character start ta 1st and end at 3rd of string -->', quarantine[0:3]) Output: String --> I will stay at home To get first character of string --> I To get last character of string --> e To get second last character of string --> m Character start ta 1st and end at 3rd of string --> I w

CONCATENATION OF STRING >>> a = " I " >>> b = " Love " >>> print ( a + b + " Python") Output : I Love Python Strings in Python can be concatenated (glued together) using plus (+) operator as shown in the example above. Strings aren’t interpreted as numeric data. These numeric data acts as a string and can be concatenated. >>> a = "32" >>> print (" Output is " + a) Output is 32

24


To perform numerical operation, string data types must be converted into Numbers using int() or float ( ) function. Similarly, non-strings data can be converted into strings using the str( ) function. Let’s take an example >>> a = "24" >>> c = int(a) >>> print ( 26+ c) Output: 50

# converting string to integer

Here string a is converted into an integer using int() function and value is stored in variable c. Hence on addition operation on a, an output is obtained as 50. Two or more string literals (i.e. the ones enclosed between quotes) next to each other are automatically concatenated. This feature is particularly useful when you want to break long strings. This only works with two literals though, not with variables or expressions. >>> a = ‘All is ‘ ‘ well’ >>> print (a) Output : ‘All is well’

TYPECASTING IN STRING >>> a = 32 >>> c = str(a) >>> print (type(c)) Output: <class 'str'> 25


In the above example, the integer is changed into string using str() function. str()and repr() both are used to create strings. >>> a = 5.225 >>> print(" Using str( ) : ", str(a)) >>> print(" using repr( ) : ", repr(a)) Output: Using str( ) : 5.225 using repr( ) : 5.225

FORMATTED STRINGS Formatted string in python which is used to generate dynamic text from the variables. The curly bracket in formatted string defines place holders and when we run code, these place holders get filled with values of previously defined variables. Here, we define formatted string with ‘f’ and curly bracket : >>> first_name = "Diwas" >>> last_name = "Pandey" >>> msg = f ' {first_name} {last_name} is an AI expert' >>> print(msg) Output: Diwas Pandey is an AI expert

26


STRING METHODS METHODS FUNCTION

EXAMPLE

capitalize( )

Converts the first character to uppercase a.capitalize( )

casefold( )

Converts string into lower case

a.casefold( )

count( )

Returns the number of times a specified value occurs in a string

a.count(‘r’)

endswith( )

Returns true if the string ends with the specified value

a.endswith(‘n’)

find( )

Searches the string for a specified value and returns the position of where it was found

a.find(‘o’)

index( )

Searches the string for a specified value and returns the position of where it was found

a.index(‘o’)

isalnum( )

Returns True if all characters in the string are alphanumeric

a.isalnum( )

isalpha( )

Returns True if all characters in the string are in the alphabet

a.isalpha( )

isdecimal( )

Returns True if all characters in the string are decimals

a.isdecimal( )

isdigit( )

Returns True if all characters in the string are digits

a.isdigit( )

islower( )

Returns True if all characters in the string are lower case

a.islower( )

isnumeric( ) Returns True if all characters in the string are numeric

a.isnumeric( )

isspace( )

a.isspace( )

Returns True if all characters in the string are whitespaces

27


isupper( )

Returns True if all characters in the string are upper case

a.isupper()

lower( )

Converts a string into lower case

a.lower( )

len( )

Returns length of string

len(a)

replace( )

Returns a string where a specified value is replaced with a specified value

a.replace(‘pytho n’,’ai’)

startswith( ) Returns true if the string starts with the specified value

a.startswith(‘I’)

strip( )

Returns a trimmed version of the string

a.strip(“a”)

swapcase( )

Swaps cases, lower case becomes upper case and vice versa

a.swapcase( )

title( )

Converts the first character of each word a.title( ) to uppercase

upper( )

Converts a string into upper case

a.upper( )

“ find() method returns -1 if the value is not found. Index( ) generates error substring not found.​“ If we need to insert characters that are illegal as strings, we use ‘\’ followed by the character ( example: \@ ). Other escape characters used in python are: SPECIAL CHARACTER

FUNCTION

\’

Single Quote

\\

BackSlash \

\n

New Line

\r

Carriage Return

\b

Backspace 28


\ooo

Octal value

\xhh

Hex value

PROBLEM 10 : >>> print("i love \' programming \'") Output: i love ' programming '

>>> print("I love programming \n I love python") Output: I love programming I love python

PROBLEM 11: REVERSE A STRING >>> a = str(input("enter a string : ")) >>> print(a[::-1]) Output: enter a string : Diwas sawiD 29


7.4 LIST In python, the most basic data structure is a sequence where a number is assigned by its position or index to each part of a sequence. The first index is zero, the second index is, and so on. Python has six built-in types of sequences, but in this tutorial, we walked with a concept called a list which is defined as a changeable or mutable data-structure in Python. Lists are defined as the sequence of arbitrary objects enclosed by square brackets. Lists are ordered and changeable, separated by commas, and often consisting of a number of compound data types. lists are a mutable type, i.e. it is possible to change their content. >>> a = [1, 2.2, 'python'] >>> print (a) >>> print (a[1]) Output: [1, 2.2, 'python'] 2.2

Imagine, you have different values and say you have numbers, and likewise you have strings. If you want to group them together, Lists are used and this is similar if you have worked on arrays in any other programming languages (C, C++, Java). A Python list is an example of a heterogeneous ordered set, which is: 1. Dynamically sized​: You don’t need to specify a size when you first create your list, and it can expand to fit as much data as you need depending upon the limits set by the O/S.

30


2. Heterogeneous​: List in python can contain any other data element and may contain any mixture of data types in any given list. Python lists are so versatile that they are also containable. 3. Ordered​: They maintain their contents in the order dictated by the application and we are able to access their elements in one order after another >>> nums = [5,6,8,-10,36] >>> print('The first value of list is -->', nums[0]) >>> print('The last value of list is -->', nums[4]) Output: The first value of list is --> 5 The last value of list is --> 36

SLICING

The slicing operator [ ] can be used with a list. List stores sequences indexed by integers, starting at zero. To extract a single item, use the indexing operator s[i] like this: Similar to string, square brackets can be used to access elements of the list, we can access the range of items using slicing. To obtain certain parts of items we specify starting and ending indexes separated by colon ‘:’. >>> a = [ 's', 'a', 1,2,3,'w'] >>> print (a[2:4]) Output: [1,2] Here, we have assigned the starting index 2 i.e ‘1’ and ending index 4 i.e 3. But item of index 4 is ignored and only 2nd and 3rd indexed items are shown. This extracts all items from s[i:j] whose index is in the range i<=k<j.

31


If either index is omitted, the beginning or end of the list is assumed, respectively: Similarly, we can use negative slicing as follows: >>> c = a[-4:-2] >>> print (c) Output : [1,2] In negative slicing, starting and ending indexes are reversed and a negative sign(-) is introduced before them.

DIFFERENT DATA TYPES IN LIST?

There are no inherent problems in having multiple data types in a list compared to the array of the other programming languages that only stored one type of data. Since lists can also store other compound data structures and other lists along with other object references, processing or iterating through the list may become a bit more complex due to possible multiple layers, than just going through an array in a simple single-level iteration. This is called Shallow and deep copying​. >>> names = ['Diwas', 'Sush', 'Sunil', 'Nana'] Imagine, if we made a mistake for the last item of names i.e. Nana should be spelled as Bae. What will you do for this? >>> print('Original list -->', names) >>> names[-1] = 'Bae' >>> print('New list for names --->', names) 32


Output: Original list --> ['Diwas', 'Sush', 'Sunil', 'Nana'] New list for names ---> ['Diwas', 'Sush', 'Sunil', 'Bae'] METHOD FUNCTION

EXAMPLE

append( )

adds element to the end of the list and nums.append(-6) the length of the list itself will increase by one

insert( )

append adds elements at the end whereas insert adds at a given index . syntax: listname.insert(index,item)

nums.insert(3, 5.5)

extend( )

extends a list by appending elements from an iterable

nums.extend(names)

remove( )

removes the element which you want to

nums.remove(3)

clear( )

removes all the element from the list & nums.clear( ) returns empty

sort( )

sort the element of the given list in a nums.sort() specific order that maybe ascending or nums.sort( descending reverse=True) ​# descending

33


2D LIST 2D list refers to a rectangular data table which is generally defined as matrices or two dimensional arrays. We use ‘,’ between two lists to make an array. >>> a = [1,2,3] >>> b = [4,4,5] >>> c = [6,7,8] >>> matrix = [a,b,c] >>> matrix = [ [1,2,3], [4,4,5], [6,7,8] ] >>> print('Accessing first row:',matrix[0]) >>> print('Accessing second element of first row:',matrix[0][1]) output: Accessing first row: [1, 2, 3] Accessing second element of first row: 2

34


7.5 TUPLE Similar to Lists, Tuple is an ordered sequence of items but is immutable i.e items of a tuple can not be changed. The tuple which is pronounced either like too-pul or tup-el is, used as a way of defining a combination of one or more similar values in mathematics. Tuples are used for those data which are write-protected and can not be changed later. Tuples are written within parentheses ( ) and separated by commas. Python recognizes it as tuple even if the parentheses are missing.

>>> tuple_1 = (2,"sawid",4) >>> print (type(tuple_1)) >>> a = 2, 'sunil','bae' #missing parentheses >>> print(type(a)) Output: <class 'tuple'> <class 'tuple'>

● immutable – can’t be changed once created (separates from the list) ● ordered – The elements in a tuple are in a specific order, and remain in that order ● Sequence – The objects in the tuple are accessible in sequence-i.e. first, second, third, etc.

Although tuples support most of the same operations as lists (such as indexing, slicing, and concatenation), the contents of a tuple cannot be modified after creation (that is, you cannot replace, delete, or append new elements to an existing tuple). We can access the elements of the tuple using indexing by providing the index value inside the square bracket. Indexing starts from 0 like in other data types. We can use the slicing operator [] to extract items but we cannot change its value. 35


“​Since we can’t change values in tuples, so iteration in tuples is faster than list & the speed of execution is faster in tuples.​ “ COUNT ( ) count ( ) is a method that is used to count the total number of occurrences of data items in the tuple.

>>> a = ( 3, 5, 7, 3, 5, 3, 3) >>> b = a.count(3) >>> print (b) Output: 4

INDEX ( ) The index () method in the tuple searches an element and returns its index. Simply, the index() method checks the given element in a tuple and returns its location. However, the first / smallest position is returned if the same element is present more than once.

>>> a = ( 5, 7, 3, 5, 3, 3) >>> print (a.index(3)) output: 2

SLICING The slicing operator [ ] can be used with tuples. Tuple stores sequences indexed by integers, starting at zero. To extract a single item, use the indexing operator s[i] like this: Similar to List, square brackets can be used to access elements of the tuple, we can access the range of items using slicing. To obtain certain parts of items we specify starting and ending indexes separated by colon ‘:’. 36


>>> a = ('Sunil', 'python', 'sawid',3) >>> print (a[2]) >>> print(a [1:3]) Output : sawid ('python', 'sawid')

BUT !! DO YOU KNOW ?? Tuples are immutable: Once a tuple is created, its value can not be changed. But there is a way, we can convert a tuple into a list, change the list elements, and convert the list back into a tuple. Let's give it a try by changing “python” into sush. >>> a = ('Diwas', 'python', 'sawid','Pari') >>> print (type(a)) # output 1 >>> list_1 = list(a) >>> print (type(list_1)) # output 2 >>> list_1[1] = 'sush' >>> a = tuple(list_1) >>> print (type(a)) # output 3 >>> print (a) # output 4 OUTPUT: class 'tuple'> class 'list'> class 'tuple'> ('Diwas', 'Sush', 'sawid','Pari') 37


7.6 SET Now, it’s time to look at a new data type which is known as a set. So, what is ​Set​? If you remember the mathematical definition of a set, simply it is a collection of unique elements. Set in Python is the data structure similar to lists or dictionaries that has a mathematical definition of set. Set is the collection of unordered and un-indexed objects. Also, the set is defined by values separated by comma inside braces { }. Sets support a standard collection of operations, including union, intersection, difference, and symmetric. Unlike tuple and list data type, a set of items is an unordered sequence i.e. The order in which the set objects are listed in a set is not the order in which they are stored because the objects are stored on the basis of their internal hash value.

>>> a = {1,3,4,5} >>> print(a) >>> print (type(a)) Output: {1,3,4,5} <class 'set'>

WHAT ARE THE IMPORTANT PROPERTIES OF SET? ● A collection can be modified even though we can insert a new item and remove an existing item. ● We can’t save duplicate values into a set. ● As the order in which items of a set are stored is arbitrary, and there is no definition of using an index location to access an item of a set.

38


Square bracket is used to define lists, small brackets are used to define tuples and lastly we have got one bracket left i.e. curly { } bracket, which is used to define sets in python. >>> s = {35, 60 , 40 ,41, 30 , 60, 35} >>> print (s) Output : {30,35,40,41,60} Surprised with the output ?? Unlike other data types, set in python removes duplicate elements. Let's take another example to be more clear : >>> a = {1,1,1,1,1,1,1,1} >>> print(a) Expected output : {1,1,1,1,1,1,1,1} Output obtained : {1} Since Set is an un-indexed and unordered collection of objects, indexing is not possible. Let’s go through some set operations in python.

UNION The union of two sets A and B is the set of elements which are in A, in B, or in both A and B. >>> a = {2 ,3,4,5} >>> b = {5,6,7} >>> c = a | b >>> print ('union of a and b is :',c) output: union of a and b is : {2, 3, 4, 5, 6, 7} 39


INTERSECTION Intersection of two given sets is the largest set which contains all the elements that are common to both the sets. To find the intersection of two given sets A and B is a set which consists of all the elements which are common to both A and B.

>>> a = {2 ,3,4,5} >>> b = {5,6,7} >>> d = a & b >>> print ('intersection of a and b is : ',d) Output: intersection of a and b is : {5}

DIFFERENCE The difference of set B from set A, denoted by A-B, is the set of all the elements of set A that are not in set B. In mathematical term, A-B = { x: x∈A and x∉B} If (A∩B) is the intersection between two sets A and B then, A-B = A – (A∩B)

>>> a = {2 ,3,4,5} >>> b = {5,6,7} >>> e = a - b >>> print ('difference of a and b is : ',e) Output: difference of a and b is : {2, 3, 4} The symmetric difference, also known as the disjunctive union of two sets, is the set of elements that are in either of the sets and not in their intersection. 40


>>> a = {2 ,3,4,5} >>> b = {5,6,7} >>> f = a ^ b >>> print ('symmetric difference of a and b is : ',f) Output: symmetric difference of a and b is : {2, 3, 4, 6, 7}

METHOD

FUNCTION

EXAMPLE

add ( )

adds new items to set

name.add(‘sawid’)

update ( )

adds multiple items to set

name.update({‘a’,4,5,’b’})

remove ( )

removes item from list

name.remove(4)

clear( )

empties the set

name.clear( )

pop ( )

removes last item from set

name.pop( )

discard ( )

removes items from list

name.discard(4)

len ( )

returns numbers of items in set len(name)

del ( )

deletes the set completely

del(name)

PROBLEM 13 : ADD ITEMS TO LIST >>> a = {"diwas", 4,55,66,23," sunita",4,5,7} >>> a.add("sawid") >>> print(a) Output : {66, 4, 5, 7, 'sawid', 'diwas', 55, 23, ' sunita'} 41


PROBLEM 14 : ADD MULTIPLE ITEMS # add multiple items to set >>> a = {1,11,111} >>> a.update({2,3,4}) >>> print (a) Output: {1, 2, 3, 4, 11, 111}

PROBLEM 15 : REMOVE ITEMS IN SET >>> a ={2,3,4} >>> a.remove(2) >>> print(a) Output : {3, 4}

42


7.7 DICTIONARY Dictionary, a pair of values, one being the Key and the other corresponding pair element being its Key: value, is a collection of unordered, indexed, and mutable data values. It is generally used when we have a huge amount of data. Python dictionaries are written with curly brackets { } with each item being a pair in the form key: value. A dictionary in python is also defined as an associative array or hash table that contains objects indexed by keys.

>>> a = { 'name' : 'Diwas', 'age' : 13} >>> print(type(a)) Output : <class 'dict'>

We can access the data items of the dictionary in python by referring to its key name, inside square brackets. get() method can also be used to access the item.

>>> b = { 'name' : 'sunil', 'age' : 23, 'height': 5.4 } >>> print (b['age']) >>> print (b.get('age')) Output : 23 23 43


WHEN WE USE GET ( ) : When we try to access a key that is not present in the dictionary using a square bracket, it throws an error. To avoid this problem we use the get ( ) method. Get simply returns the non value which means the object that represents the absence of a value. Also, we can pass the default value instead of getting none as result :

>>> age = { 'a' : 1, 'b' : 2 } >>> print (age.get('c')) >>> print ('after passing default key-value ',age.get('c', 3) Output: None after passing default key-value 3

Although strings are the most common type of key, you can use many other Python objects, including numbers and tuples. Some objects, including lists and dictionaries, can’t be used as keys because their contents can change.

SET VS DICTIONARY IN PYTHON While both data types use the same bracket to define each other, the main difference is that a set is a collection of unique keys (does not actually contain values), which is useful for doing set operations. Reference object in a dictionary is called key while data is the value. The key can be string or number but the value can be number, string, a boolean, a list anything. 44


>>> student = { "name":"Diwas Pandey", "College ID": 1929635, "Phone number" : 9898989898, "Email ID" : "diwaspandey@gmail.com", "Address": "Kathmandu" }

What if we add another key-value pair with the same key ?? Any attempt to use the same key again will simply delete the previously stored value which means each key in a dictionary should be unique. If a key needs to store multiple values, then the value associated with the key should be a list or another dictionary.

DICTIONARY IS MUTABLE Dictionaries are mutable. Once a dictionary is created, its value can be changed by referring to its key name. Let's take an example: There is a student named Sushmita in a college from CSIT faculty. She lives in the USA. & her age is 21 years. Let’s define a dictionary with this information.

>>> student = { 'name':'sushmita', 'faculty':'CSIT', 'age':22, 'location':'USA'} >>> print (student) output: {'name': 'sushmita', 'faculty': 'CSIT', 'age': 22, 'location': 'USA'}

Oh sorry ! We entered wrong information on age. What should we do now?? There is a way : 45


>>> student['age']=21 >>> print (student) output: {'name': 'Sushmita', 'faculty': 'CSIT', 'age': 21, 'location': 'USA'}

The above dictionary consists of information of a student like name, faculty, age, and location. Now we need to add gender as well. To add a new item to the dictionary, we need to assign a new index key and value to it:

>>> student['gender']= 'female' >>> print (student) Output: {'name': 'sushmita', 'faculty': 'CSIT', 'age': 21, 'location': 'USA', 'gender': 'female'}

Girls usually don’t share their age with others. Let’s remove her age from the dictionary. pop() method can be used to remove the item with the specified key name. The del keyword removes the item with the specified key name whereas clear() method empties the dictionary in python.

>>> student.pop('age') #removes age >>> print (student) >>> del student['faculty'] #removes faculty >>> print (student) >>> student.clear() # empties all dictionary >>> print (student) OUTPUT: {'name': 'sushmita', 'faculty': 'CSIT', 'location': 'USA', 'gender': 'female'} {'name': 'sushmita', 'location': 'USA', 'gender': 'female'} { } 46


An empty dictionary in python is created in one of two ways:

>>> d = { } >>> e = dict()

NESTED DICTIONARY IN PYTHON Let’s create a nested dictionary named student which contains information of all the students in a class.

>>> college = { "std1" : { "name" : "A", "year" : 2002 }, "std2" : { "name" : "B", "year" : 2009 }, "std3" : { "name" : "C", "year" : 2018 } }

We have another way to create nested dictionaries in python. First we can create three different dictionaries, then we can create a single dictionary including all three different dictionaries.

47


Here is an example:

>>> std1 = { "name" : "A", "year" : 2002 } >>> std2 = { "name" : "B", "year" : 2009 } >>> std3 = { "name" : "C", "year" : 2018 }

Let’s combine all three dictionaries and create a single nested dictionary in python.

>>> college = { "std1" : std1, "std2" : std2, "std3" : std3 }

METHOD

FUNCTION

clear( )

Removes all the elements from the dictionary

copy( )

Returns a copy of the dictionary

fromkeys( )

Returns a dictionary with the specified keys and value

get( )

Returns the value of the specified key 48


items( )

Returns a list containing a tuple for each key-value pair

keys( )

Returns a list containing the dictionary’s keys

pop( )

Removes the element with the specified key

popitem( )

Removes the last inserted key-value pair

update( )

Updates the dictionary with the specified key-value pairs

values( )

Returns a list of all the values in the dictionary

7.8 BOOLEAN Not all variables can take numerical values for themselves. The boolean data type in python consists of two value i.e. True or False. Bool ( ) generally accepts one parameter, which on testing procedure yields True or False output. If no parameter is passed, the default output is False in boolean in python.

>>> print (bool(1)) >>> a = True >>> print (a) >>> print (3>4) # test if 3 > 4 >>> str1 = "sush" >>> str1.islower() #test if string contains lower case Output: True True False True

49


“​The keywords True and False must have an UpperCase first letter. Using a lowercase true returns an error.​“

SOME CONCEPTS ABOUT BOOLEAN 1. 2. 3. 4.

If any contents are present, then it is true. Number is True, except 0. String is True, except empty strings. List, tuple, set, and dictionary are True, except empty ones.

>>> print('For True: ',int(True)) >>> print('For False: ', int(False)) Output: For True: 1 For False: 0 50


8 OPERATOR

In the previous section, we learned about various data types in python and respective methods. In this lesson onward we’ll dig into the semantics of the various operators in python. By the end of this section, you will have detailed knowledge about operators in python and their respective functions.

PYTHON OPERATORS Operators are symbols which are used to perform operations on values and variables. We also define operators in python as the constructs which can manipulate the value of operands. The data items are referred to as operands or arguments. We represent operators by keywords or special characters. ● ● ● ● ● ● ●

Arithmetic operators Comparison operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators

51


8.1 ARITHMETIC OPERATORS These operators in python are used to perform arithmetic operations like addition, subtraction, multiplication, division, etc. Python implements seven basic binary arithmetic operators, two of which can double as unary operators. [ unary operators are those operators that operate on only one operand example: unary plus(+a) ]. OPERATOR NAME

DESCRIPTION

a + b

Addition

Sum of a and b

a – b

Subtraction

Difference of a and b

a * b

Multiplication

Product of a and b

a / b

True division

Quotient of a and b

a // b

Floor division

Quotient of a and b, removing fractional parts

a % b

Modulus

Remainder after division of a by b

a ** b

Exponentiation a raised to the power of b

- a

Negation

The negative of a

+a

Unary plus

a is unchanged (rarely used)

>>> a = 6 >>> b = 4 >>> print('addition of a & b is ', a+b) >>> print('subtraction of a & b is ', a-b) >>> print('multiplication of a & b is ', a*b) >>> print('division of a & b is ', a/b) 52


>>> print('Modulus of a & b is ', a%b) >>> print('Floor division of a & b is ', a//b) >>> print('b exponent of a ', a**b) >>> print('negation of a is ', -a) >>> print('unary plus of is ', +a) Output: addition of a & b is 10 subtraction of a & b is 2 multiplication of a & b is 24 division of a & b is 1.5 Modulus of a & b is 2 Floor division of a & b is 1 b exponent of a 1296 negation of a is -6 unary plus of is 6 The floor division operator was added in Python 3; you should be aware if working in Python 2 that the standard division operator ( / ) acts like floor division for integers and like true division for floating-point numbers.

8.2 ASSIGNMENT OPERATORS Assignment operator in python to assign values of the right expression to the left operand. Usually, ‘=’ operator is used to assign value to the variable.

>>> a = 5 >>> print (a) Output: 5

53


Suppose we want to update the value with the new value. Various assignment operators (+=, – =, *=, /=, etc.) can be used in python to update the value of variables. We can also use a compound assignment operator, where we can add, subtract, multiply right operand to left and assign addition (or any other arithmetic function) to the left operand.

operator example same as ------------------------------------------- = x = 5 x = 5 += x += 5 x = x + 5 -= x -= 5 x = x - 5 *= x *= 5 x = x * 5 /= x /= 5 x = x / 5 %= x %= 5 x = x % 5 //= x //= 5 x = x // 5 **= x **= 5 x = x ** 5 &= x &= 5 x = x & 5 |= x |= 5 x = x | 5 ^= x ^= 5 x = x ^ 5 >>= x >>= 5 x = x >> 5 <<= x <<= 5 x = x << 5

Let's go with some examples of assignment operator in python :

>>> a = 5 >>> a+=3 >>> print ('a+=3 i.e a = a+3 is',a) >>> a = 5 >>> a*=3 >>> print ('a*=3 i.e a = a*3 is',a) 54


>>> a = 5 >>> a/=3 >>> print ('a/=3 i.e a = a/3 is',a) >>> a = 5 >>> a&=3 >>> print ('a&=3 i.e a = a&3 is',a) >>> a = 5 >>> a%=3 >>> print ('a%=3 i.e a = a%3 is',a) >>> a = 5 >>> a|=3 >>> print ('a|=3 i.e a = a|3 is',a) >>> a = 5 >>> a^=3 >>> print ('a^=3 i.e a = a^3 is', a) >>> a = 5 >>> a>>=3 >>> print ('a>>=3 i.e a = a>>3 is', a) Output: a+=3 i.e a = a+3 is 8 a*=3 i.e a = a*3 is 15 a/=3 i.e a = a/3 is 1.6666666666666667 a&=3 i.e a = a&3 is 1 a%=3 i.e a = a%3 is 2 a|=3 i.e a = a|3 is 7 a^=3 i.e a = a^3 is 6 a>>=3 i.e a = a>>3 is 0 55


8.3 LOGICAL OPERATORS Operator: Meaning Example ---------------------------------------------------------------------------------------------- and True if both the operands are true x and y or True if either of the operands is true x or y not True if the operand is false (complements the operand) not x

Let's go with some examples of logical operator in python :

>>> a = True >>> b = False >>> print(('a and b is',a and b)) >>> print(('a or b is',a or b)) >>> print(('not a is',not a))

Output: ('a and b is', False) ('a or b is', True) ('not a is', False)

8.4 BIT WISE OPERATORS The bitwise operator in python performs bit by bit operation on the values of the two operands. If we assign a = 5 and b = 4 then in bitwise operations a stores the value as 0101 and b as 0100. suppose we are going to do binary and (&) on a and b :

>>> a = 5 >>> b = 6 >>> print (" binary and i.e a&b is ",a&b) 56


Output: binary and i.e a&b is 4 Let's see how bit wise operator in python works :

a = 0100 b = 0101 a&b = 0100 & 0101 ---------- 0100 i.e. 4 These bitwise operators only make sense in terms of the binary representation of numbers. Let's go through some of the bitwise operator examples:

>>> a = 5 >>> b = 6 >>> print ("binary and i.e. a&b is:", a&b) >>> print ("binary or i.e. a|b is:", a|b) >>> print ("binary xor i.e. a^b is:", a^b) >>> print ("binary not i.e. ~b is:", ~b) >>> print ("binary left shift of 5 by 6 units i.e. a<<b is:", a<<b) Output: binary and i.e. a&b is: 4 binary or i.e. a|b is: 7 binary xor i.e. a^b is: 3 binary not i.e. ~b is: -7 binary left shift of 5 by 6 units i.e. a<<b is: 320 57


8.5 RELATIONAL OPERATORS Comparison operators are used to compare two values of two operands present on either side of the operator, return boolean value True or False. These comparison operators can be combined with the arithmetic and bitwise operators. They are also called Relational operators in python. The comparison operations are listed in the following table:

OPERATOR NAME

EXAMPLE

==

Equal

x == y

!=

Not equal

x != y

>

Greater than

x > y

<

Less than

x < y

>=

Greater than or equal to

x >= y

<=

Less than or equal to

x<=y

<>

Not equal

x<>y

>>> a = 5 >>> b = 9 >>> print ("a == b :",a==b) >>> print ("a != b :",a!=b) >>> print ("a > b :",a>b) >>> print ("a < b :",a<b) >>> print ("a >= b :",a>=b) >>> print ("a <= b :",a<=b)

58


Output: a == b : False a != b : True a > b : False a < b : True a >= b : False a <= b : True When working with Boolean values, Python provides operators to combine the values using the standard concepts of “and”, “or”, and “not”. These sorts of Boolean operations will become extremely useful when we begin discussing control flow statements such as conditionals and loops.

>>> a = 5 >>> b = 9 >>> c = 8 >>> print (a>b) >>> print (b>c) >>> print ( (a>b) or (b>c)) Output: False True True

Here, on the fifth sixth line we are doing logical operation ‘or’ on the value boolean of (a>b) and (b>c). Boolean of False or True gives the output True. Hence the output of the sixth line is True. 59


8.6 IDENTITY OPERATORS Identity operators in python are used to check the object identity of two operands which doesn’t mean equality (==). We use ‘is’ and ‘is not’ operators. Actually, Identity operators compare the same operands with the same memory locations. Two variables that are equal does not imply that they are identical. Lets understand it with example:

>>> a = 5 >>> b = 5 >>> print ("a is b :",a is b, " a == b :", a==b) >>> c = {5,4} >>> d = {5,4} >>> print ("c is d :",c is d, " c == d :", c==d) >>> print ('c is not d :', c is not d) Output: a is b : True a == b : True c is d : False c == d : True c is not d : True

In the above example, we see that a and b are integers of the same values, so they are equal as well as identical. But c and d are sets. They are equal but not identical. It is because the interpreter locates them separately in memory although they are equal in identity operators in python.

60


8.7 MEMBERSHIP OPERATORS Python’s membership operators test whether a value or variable is found in a sequence (string, list, tuple, set, and dictionary). If the value is present in the data structure, then the resulting value is true otherwise it returns false. These membership operator in python are an example of what makes Python so easy to use compared to lower-level languages such as C in

True if value is found in the sequence

not in

True if value is not found in the sequence

>>> print (2 in {2,3,4}) >>> print( 'e' in ('aeiou')) Output: True True # In a dictionary we can only test for presence of key, not the value >>> a = { "s":"sawid", "d":"diwas"} >>> print ("s" in a) >>> print ("sawid" not in a) Output: True True 61


OPERATOR PRECEDENCE Generally, a combination of variables, operators are termed as an expression. To evaluate these types of expressions there is a rule of precedence in Python. 1 is the highest & 13 is the lowest precedence and precedent decreases from left to right. PRIORITY OPERATOR

NAME

1

( )

Parentheses

2

**

Exponent

3

+x, -x, ~x

Unary plus, Unary minus, Bitwise NOT

4

*, /, //, %

Multiplication, Division, Floor division, Modulus

5

+, -

Addition, Subtraction

6

<<, >>

Bitwise shift operators

7

&

Bitwise AND

8

^

Bitwise XOR

9

|

Bitwise OR

10

==, !=, >, >=, <, <=, Comparisons, Identity, Membership is,is not, in, not in operators

11

not

Logical NOT

12

and

Logical AND

13

or

Logical OR

62


9 CONDITIONAL & LOOP Till now we were executing our python program sequentially. Let us suppose a condition where we need to execute a certain part of code based on condition satisfied. For example, we are given marks of a student in Maths. We need to print pass if he has obtained more than 40 marks, else we need to print fail. Here we check the condition, and a decision is made on the basis of condition satisfied. In this problem we use Python flow control.

>>> a = 50 >>> if (a>40) : print("Student has passed") >>> else: print ("Student has failed") Output: Student has passed

Without control flow, the program is simply a list of statements that are sequentially executed. Using control flow, decision making allows us to run a particular block of code for a particular decision until the condition is satisfied. Here we’ll cover conditional statements (including if, elif, and else) and loop statements (including for and while, and the accompanying break, continue, and pass).

63


9.1 IF STATEMENT Python includes if, else & a unique keyword is elif, a contraction of “else if ”. Else & elif are optional, also we can include as few or as many elif statements as we like. The if statement is used to test a specific condition. If the condition is true, a block of code (if-block) will be executed. The if-else statement is similar to if statement, except the fact that it also provides the block of the code for the false case of the condition to be checked. If the condition provided in the if statement is false, then the else statement will be executed. Nested if statements enable us to use if-else statements inside an outer if statement.

syntax : ---------- >>> if (condition): statements

>>> a = 'diwas' >>> if (a[1]=='i'): print("correct") Output: correct

Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Generally, four spaces are given to indent the statements which are a typical amount of indentation in python. Other programming languages often use curly-brackets for this purpose. ​See about python indentation here 64


EXAMPLE 01 Suppose we need to enter the number & check whether the number is odd or even. So lets start:

>>> a = int(input("enter a number")) >>> if (a%2==0): print(a, "is even") >>> if (a%2!=0): print (a," is odd") Output: enter a number6 6 is even

9.1.1 IF – ELSE STATEMENT The if-else statement provides an else block combined with the if statement which is executed in the false case of the condition. If the condition is true, then the if block is executed. Otherwise, the else block is executed. Let’s work on the above example again:

syntax : ---------- >>> if (condition): if-statements >>> else: else statements 65


>>> a = int(input("enter a number : ")) >>> if (a%2==0): print(a, "is even") >>> else: # we can also use elif instead of else print (a," is odd") Output: enter a number : 5 5 is odd EXAMPLE 02 Suppose we are given a percentage value of a student and we need to calculate the grade of the student. If he has got more than 80% then we need to print distinction. If he has got more than 60% then we need to print first division. Similarly, if he has obtained more than 40% then we need to print Just pass else we need to print fail. >>> a = float(input("enter percentage : ")) >>> if (a>=80): print(" Congratulations ! You have obtained distinction marks") >>> elif (a>=60): print(" Good ! You have obtained first division marks") >>> elif (a>=40): print(" Satisfactory result ! You have just pass marks") >>> else: print(" Sorry !! you are fail ! ") Output: enter percentage : 68.44 Good ! You have obtained first division marks

66


We use elif in this case which is used to test the condition when the if condition fails. If we have only one statement to execute, we can put the statement on the same line of if, else, elif statements. Let’s take above example again: >>> a = float(input("enter percentage : ")) >>> if (a>=80):print(" Congratulations ! You have obtained distinction marks") >>> elif (a>=60):print(" Good ! You have obtained first division marks") >>> elif (a>=40):print(" Satisfactory result ! You have just pass marks") >>> else:print(" Sorry !! you are fail ! ") Output: enter percentage : 68.44 Good ! You have obtained first division marks We can use logical operators like AND, OR in the test condition as shown in example below: >>> a = int(input("enter marks of Maths : ")) >>> b = int(input("enter marks of Physics : ")) >>> if (a>=40 and b>=40) : print(" you have passed on both subjects") >>> else: print("you have failed in at least one subject") Output: enter marks of Maths : 40 enter marks of Physics : 63 you have passed on both subjects

67


EXAMPLE 03 Largest Number out of 3 Numbers:

>>> a = int(input("Enter integer a : ")); >>> b = int(input("Enter integer b : ")); >>> c = int(input("Enter integer c : ")); >>> if a>b and a>c: print("a :",a," is the largest integer"); >>> elif b>a and b>c: print("b :",b," is the largest integer"); >>> elif c>a and c>b: print("c :",c," is the largest integer"); Output: Enter integer a : 5 Enter integer b : 3 Enter integer c : 9 c : 9 is the largest integer

EXAMPLE 04 : ODD OR EVEN

>>> a = int(input(“enter a number”) >>> if (a%2 == 0): print (a, ‘is even number’) >>> else: Print (a, ‘is odd number’)

68


9.1.2 NESTED IF ELSE STATEMENT In a nested if construct, we can have an if…elif…else construct inside another if…elif…else construct. We can use any number of these statements inside one another. Indentation is the only approach to find which block of statements belongs to which if-else construct.

syntax: -------------- if expression1:----------------------------------- statement(s) | if expression2: ------------------ | statement(s) | | if expression2:------- | | statement(s) | | | elif expression3: | | | statement(s) | | | else: ---------------- | | statement(s) | | elif expression3: | | statement(s) | | else: ----------------------------- | statement(s) | else:---------------------------------------------- statement(s)

69


EXAMPLE 04: GUESS A NUMBER

>>> a = int (input("enter value from 1 to 5 : ")) >>> if (a>=1 and a<=5): print ("number is between 1 & 5 ") if (a%2==0): print("Number is even") if (a==2): print ("number is 2") elif (a ==4): print ("number is 4") elif (a%2!=0): print("number is odd") if(a==1): print(" number is 1") elif(a==3): print("number is 3") else: print("number is 5") >>> else: print("Number not in range") Output: enter value from 1 to 5 : 4 number is between 1 & 5 Number is even number is 4

70


Suppose when we have to print “Python” 10 times, we can add ten print statements so that we can print “Python” ten times repeatedly. ● ● ● ● ● ● ● ● ● ●

print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’) print(‘Python’)

Now, suppose if someone told you to print (‘Python’) 1000 times what would you do? Will you execute a print statement 1000 times? So to minimize such lengthy coding loops are used. We can use two kinds of loop, they are: 1. For Loop 2. While Loop

9.2 FOR LOOP A FOR loop in python is used in executing blocks of code in iteration over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). This operation is known as traversal. With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc which is different than for loops used in other programming languages. Loop continues until we reach the last item in the sequence and the block of codes that needs to be executed in a loop is identified by​ i​ ndentation​.

“​Spaces

or tabs used in the beginning of the code is known as

indentation. Indentation is used to python to indicate which block of code a statement belongs to.​“

71


>>> vowel = ['a','e','i','o','u'] >>> for x in vowel: print(x)

Output: a e i o u Here, x is the variable that takes the value of the item inside the sequence on each iteration. Each time through the loop, the variable x takes on the value of the next object in the vowel. It prints every item inside the list until it reaches the last string ‘u’. This type of loop iterates over a collection of objects, rather than specifying numeric values or conditions. Let’s use for loop in dictionary :

>>> num = {'a': 1, 'b': 2, 'c': 3} >>> for m, n in num.items(): ... print('key =', m, ', value =', n) Output: key = a , value = 1 key = b , value = 2 key = c , value = 3

In the above example, we can see that item( ) is used to access both key and value from the dictionary. In list, set, dictionary and tuple, for loop iterates on number of items present. But in case of String ? Let’s take an example : 72


>>> a = "loop" >>> for y in a: print (y)

Output: l o o p Since string is a single item, for loop in string slices the item into individual characters and then iterates for the number of characters present in string. As in the above example, loop iterates for four times and prints individual characters.

>>> b = 0 >>> a = "programming" >>> for y in a: b=b+1 >>> print ("\n total characters : ", b) Output: total characters : 11

9.2.1 FOR LOOP USING RANGE To define the loop iterations for a finite number of times we use range ( ). It can also be used in list, dictionary, tuple, set, string by combining with the len( ) function to iterate through a sequence using indexing. The range( ) function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. But, we can also define starting value, incremental value as per our requirement.

73


>>> a = ('a','b','c','d') >>> for item in range(len(a)): print (a[item])

Output: a b c d EXAMPLE 01: PRINT FIRST FIVE NUMBER >>> for a in range (5): #starts from 0 & increment by 1 print (a) Output: 0 1 2 3 4 EXAMPLE 02: PRINT FIRST FIVE EVEN NUMBER >>> for a in range (0,10,2): print (a) Output: 0 2 4 6 8 74


“​In the above example, the first term is zero and in each iteration the number increments by 2 and ends at 10. In the FOR loop, the last number is ignored.​“

EXAMPLE 03: PRINT SUM OF 1 TO 100 >>> s= 0 >>> for b in range (1,101): s=s+b >>> print (" sum from 1 to 100 is : ",s) Output: sum from 1 to 100 is : 5050

9.2.2 NESTED FOR LOOPS When a for loop is present inside another for loop then it is called a nested for loop. Let's take an example of nested for loop.

>>> for a in range(1,5,1): for b in range(a): print('*',end =" ") #end =" " is used to print on same line print('\n') Output: * * * * * * * * * * 75


In the last tutorial, we looked ​for loop in Python​, where the number of iterations were known already. But what if we don’t know the number of iterations the codes need to be executed ? In this case we use a while loop. The while loop in Python is used to iterate blocks of code till test expression (condition) is true. Otherwise, it skips the block.

9.2 WHILE LOOP syntax --------------- while condition: #body_of_while In the while loop, first of all the condition given is checked. If the condition is satisfied then control flow executes the given block of code and iterates the code execution. If the testing condition is not satisfied, it skips the while body statements and jumps outside the while loop block. EXAMPLE 01: PRINT YOUR NAME 5 TIMES >>> name = str(input("enter your name : ")) >>> c= 5 >>> while (c>0): print(name) c=c-1 Output: enter your name : Diwas Diwas Diwas Diwas Diwas Diwas 76


In the above example variable value is set as 5. We have defined the condition that the while block is iterated until the value is greater than 0. Initially c is 5 which is greater than 0 hence the while block gets executed. In the first iteration, the value of c is decreased by 1 and hence becomes 4. In the fifth iteration the value becomes 0. While testing the condition, 0>0 which returns false so the condition is not satisfied and hence iteration stops.

“​Remember to update the value of the counter, else the loop will continue forever.​“ EXAMPLE 02 : PRINT SUM OF NUMBER FROM 1 TO 10 >>> n = 10 >>> sum = 0 >>> i = 1 >>> while i <= n: sum = sum + i i = i+1# update counter >>> print("The sum is", sum) Output: The sum is 55

EXAMPLE 03 : PRINT FROM 5 TO 1 >>> i = 5 >>> while i >= 1: print(i) i = i -1 >>> print("Done") 77


Output: 5 4 3 2 1 Done

EXAMPLE 04 : DRAW A PATTERN >>> i = 1 >>> while i <= 5: print( '*' * i) i = i + 1 Output: * ** *** **** *****

9.2.1 NESTED WHILE LOOP Nest is something like we have 7 days a week and each day has 24 hours. Number of days is the outer loop and the number of hours is the inner loop. For more details, If you start with Sunday and Sunday has 24 hours and it will start with 0th hour, 1 hour and so on to complete the whole day. And when you complete the entire 24 hour it will start new day i.e. Monday and for next day Monday should complete its entire hour which is similar to nested while loop means it should complete the inner loop first and then outer loop.

78


Simply, When a while loop is present inside another while loop then it is called nested while loop. Lets learn from examples: >>> a = 2 >>> while (a>0): print("first loop") b=2 while(b>0): print ("second loop") b=b-1 a=a-1 Output: first loop second loop second loop first loop second loop second loop We are going to show you how to build a guessing game using a while loop where you have only three chances to guess the number. After you guess the number, it will display message as “You Won” otherwise “Lost “ secrete_number = 9 guess_start = 0 max_guess = 3 while guess_start < max_guess: guess = int(input('Enter number:')) guess_start = guess_start + 1

79


if guess == secrete_number: print('You won') break print('Sorry')

Output: Enter number: 3 Sorry Enter number: 9 You won

BREAK & CONTINUE Break is used to exit a for loop or a while loop, whereas Continue is used to skip the current block, and return to the “for” or “while” statement. A break or continue statement found within nested loops applies to the nearest enclosing loop. EXAMPLE 01 : Write a program to print natural numbers from 1 to 10 and stop when the number reaches 5. >>> a = 1 >>> while (a<=10): if (a==5): break print (a) a=a+1

80


Output: 1 2 3 4

In this example, we are printing the first ten natural numbers. In each iteration the value of a increases by 1. During fifth iterations it reaches five. It checks the condition if a is equal to five. When it satisfies the condition, the break statement is executed and the flow of execution jumps out of execution of the while loop. Break & continue in python is used along with if statements. If we do not use it with an ‘if’ statement then the break statement will be encountered in the first iteration of loop and the loop would always terminate on the first iteration. The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Execution jumps to the top of the loop, and the controlling expression is re-evaluated to determine whether the loop will execute again or terminate. EXAMPLE 02: Write a program to print numbers from one to ten and skip number 5. >>> a = 1 >>> while (a<=10): if (a==5): a=a+1 print("number 5 is skipped") continue print (a) a=a+1 81


Output: 1 2 3 4 number 5 is skipped 6 7 8 9 10 We are skipping the print(a) statement inside the loop by using a continue statement when the number is equal to 5, this way all number 5 is skipped and the print statement executed for all the other numbers. >>> a = int(input("enter a number : ")) >>> print (‘factor of’,a, ‘is’, end= ‘ ’) >>> for i in range(2,a): for j in range (2,a+1): if (a%j==0): print (j,end=",") break a = int(a/j) Output: enter a number : 4 factor of 4 is : 2,2

82


PASS Pass in python is a NULL statement which is used when we have no codes to execute. Suppose, we declare a loop and we have no code to execute but we may have something in future. Then in this case we use a pass statement. EXAMPLE 03 : Write a program to print first 5 odd number >>> a = 1 >>> while (a<10): if (a%2==0): pass else: print (a) a=a+2 Output: 1 3 5 7 9 In the above example, when the number is even we are doing nothing. If it is odd then we are displaying the number.

83


PROGRAMMING EXAMPLES EXAMPLE 01: WRITE A PROGRAM TO CHECK PRIME NUMBER A prime number is a natural number greater than 1 whose only factors are 1 and itself. 1 is not a prime number as it doesn’t satisfy the definition of prime number. Some prime numbers are : 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, etc. >>> a = int (input("enter a number : ")) >>> c = 0 >>> if (a<1): print("invalid input ! Try next number ") >>> if(a==1): print ("1 is not prime") >>> else: for i in range(2,a,1): if (a%i==0): c=1 if (c==0): print(a," is prime") else: print(a," is not prime") Output: enter a number : 9 9 is not prime 84


EXAMPLE 02 : WRITE A PROGRAM TO FIND FIBONACCI SERIES # print fibonacci series >>> a = 1 >>> b = 0 >>> n = int(input("how many fibonacci series ?? ")) >>> while (n>=1): c = a+b a = b b = c print (c, end=",") n=n-1 Output: how many fibonacci series ?? 5 1,1,2,3,5

# print nth fibonacci series value >>> a = 1 >>> b = 0 >>> n = int(input("how many fibonacci series ?? ")) >>> while (n>=1): c = a+b a = b b = c n=n-1 >>> print (c,"is the required output") Output: how many fibonacci series ?? 6 8 is the required output 85


EXAMPLE 03: WRITE A PROGRAM TO CHECK ARMSTRONG NUMBER Armstrong number is defined as a number which is equal to the sum of its own digits raised to the power of the number of digits. Example:​ 1634 = 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 >>> sum = 0 >>> c = 0 >>> num = int(input("enter a number : ")) >>> temp = num >>> while(num>0): # to find length of number i.e. 153= 3 a = num%10 num= num//10 c=c+1 >>> num = temp >>> while(num>0): # 1*1*1+5*5*5+3*3*3 = 153 a = num%10 num= (num-a)/10 sum = int(sum + a**c) >>> if (sum == temp): print("Armstrong Number") >>> else: print (" Not an armstrong number") Output: enter a number : 153 Armstrong Number

86


EXAMPLE 04: WRITE A PROGRAM TO FIND HCF OF TWO NUMBER Highest common factor (H.C.F) is defined as the greatest number which divides each of them exactly. Also, HCF is the largest whole ​number which is a factor of both. >>> num1 = int (input ("enter first number : ")) >>> num2 = int (input ("enter second number : ")) >>> if num1 < num2: small = num1 >>> else: small = num2 >>> for i in range(1, small+1): if((num1 % i == 0) and (num2 % i == 0)): hcf = i >>> print(" HCF or GCD of ",num1,"&", num2,"is",hcf) Output: enter first number : 3 enter second number : 5 HCF or GCD of 3 & 5 is 1 Consider the numbers 12 and 15: The factors of 12 are : 1, 2, 3, 4, 6, 12. The factors of 15 are : 1, 3, 5, 15. 1 and 3 are the only common factors (numbers which are factors of both 12 and 15). Therefore, the highest common factor of 12 and 15 is 3. 87


EXAMPLE 05: WRITE A PROGRAM TO FIND LCM OF TWO NUMBER Least Common Multiple (L.C.M.) is defined as the smallest number which can be divided by each number. >>> num1 = int (input ("enter first number : ")) >>> num2 = int (input ("enter second number : ")) >>> if num1 < num2: small = num1 >>> else: small = num2 >>> for i in range(1, small+1): if((num1 % i == 0) and (num2 % i == 0)): hcf = i >>> lcm = int ((num1*num2)/hcf) >>> print(" LCM of ",num1,"&", num2,"is",lcm) Output: enter first number : 4 enter second number : 8 LCM of 4 & 8 is 8

4 : 2​ ​ x 2​ 8 : 2​ ​x 2​ ​ x 2​ LCM= 2​ x 2 x 2 = 8

88


EXAMPLE 06: WRITE A PROGRAM TO FIND FACTOR OF A NUMBER Factors are defined as the numbers which we multiply together to get another number. Factors are also defined as whole numbers that are multiplied together to produce another number where the original numbers are factors of the product number. >>> a = int(input("enter a number : ")) >>> for i in range(2,a): for j in range (2,a+1): if (a%j==0): print (j,end=",") break a = int(a/j) Output: enter a number : 4 2,2

20 = ​2 x 2 x 5 Hence, 2 and 5 are factors of 20. Factors are mostly prime numbers.

89


EXAMPLE 07: WRITE A FACTORIAL OF A NUMBER

NUMBER

TO

FIND

Factorial of a number is defined as the product of all the integers from 1 to that number. >>> a = int(input("enter a number : ")) >>> c = 1 >>> if (a==0): print (" factorial of 0 is 1 ") >>> else: for i in range(1,a+1): c=c*i >>> print ("\n factorial of ",a,"is",c) Output: enter a number : 4 factorial of 4 is 24 Keep in mind !! We don’t define factorial value for negative numbers, and the factorial of zero is one, 0! = 1.

EXAMPLE 08: WRITE A PROGRAM TO FIND SUM OF ITEMS OF LIST >>> a = [1,2,3,4,5] >>> sum = 0 >>> for i in a: sum = sum + i >>> print (" sum of items in list is : ",sum) Output: sum of items in list is : 15

90


EXAMPLE 09: WRITE A PROGRAM TO PRINT ALL VOWELS OF STRING >>> a = str(input("enter a string : ")).lower() >>> b = len(a) >>> c = 0 >>> while (c<=b-1): if a[c]=='a' or a[c]=='e' or a[c]=='i' or a[c]=='o' or a[c]=='u' : print(a[c]) c=c+1 Output: enter a string : Diwas i a

EXAMPLE 10: WRITE A PROGRAM TO SORT WORDS IN ALPHABETICAL ORDER >>> a = "apple cow dog ant" >>> a = a.split() >>> a.sort() >>> for word in a: print(word) Output: ant apple cow dog

91


EXAMPLE 11 : WRITE A PROGRAM TO CHECK PALINDROME STRING Palindrome string is defined as the string which can be read the same from backward and forward. It can also be defined as the string which is the same as the reversed string. Some examples of palindrome strings are : madam, lol, pop, radar, rubber etc. >>> a = str(input("enter a string : ")) >>> b = (a[::-1]) >>> if (a==b): print("Palindrome number") >>> else: print(" Not Palindrome number") Output: enter a string : sawid Not Palindrome number

92


10 FUNCTION Function, also called subroutine, method, or procedure is a block of one or more indented statements that perform a specific task. Functions help to break our program into smaller and modular chunks. Functions are used to increase the program readability, increase code reusability and decrease code redundancy. Functions can be defined in one place and called or invoked in another. This helps to make code more modular and easier to understand. Suppose we need to write a code of 10 lines in 5 different places in a program. In normal programming we need to write 50 lines, but we can create a function and can call it whenever and wherever we need to. Hence use of function increases re-usability. Similarly less code and dividing every specific task in individual modules increases code readability and decreases the possibility of errors.

SYNTAX >>> def function_name(parameters) : statement(s)

Keyword def is used to mark the start of a function which is followed by a function name. Naming of functions must be done as the rules of naming variables in python (link here). We use parameters, which are used to pass the value to the function. This parameter is optional. Statements in functions are written using indentation (usually four spaces). If we wish to return any value then we use the return keyword. Return is also optional.

93


TYPES OF FUNCTION 1. LIBRARY FUNCTION​: These are predefined built-in functions defined in python. Example: print( ), len( ) etc. 2. USER DEFINED FUNCTION​: These are functions written by developers.

HOW FUNCTION WORKS The flow of control a program jumps to the point where the function is defined from where the function is called when the function is called. Then it executes the blocks of codes inside the function. The return statement is used to exit a function and go back to the place from where it was called. If there is no return statement in the function code, the function ends, when the control flow reaches the end of the function body. Each time a functional call is made, the program flow jumps to the location of the body of the function and executes the statements there. Once the function operation is completed, it returns to the point from where the function was called.

DEFINING A FUNCTION

>>> def fun( ): print("hello world") In the above example we have defined a function named fun and we haven't used any parameters as it is optional. In the function body, we have used four spaces indent and printed hello world. Let's learn how to call the

94


function outside of the function body. To call a function we simply type the function name with appropriate parameters.

>>> fun( ) Output: hello world Functions are a construct to structure programs. In the above example we created a function with empty parentheses that do not take arguments, but we can define parameters in function definitions within their parentheses. Let's define another function add() which is used to add two numbers by passing parameters and returning value from function. >>> def add(a,b): sum = a+b return sum >>> sum = add(4,6) >>> print ("sum of 4 & 6 is ",sum) Output: sum of 4 & 6 is 10 We passed the number 4 in for the parameter and 6 in for the b parameter. These values correspond with each parameter in the order they are given.

DEFAULT ARGUMENTS Arguments are specified after the function name, inside the parentheses. We can add as many arguments as we want, separating them with a comma. A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that is sent to the function when it is

95


called. In the above example x & y are argument and a & b are parameters. There is always an equal number of parameters and arguments. In a case that argument is not passed to the function, we define a default value to the parameter. By using default arguments we can avoid the errors that may arise while calling a function without passing all the parameters. >>> def mul(a=2,b=6): return a*b >>> a = mul(4) >>> print ("multiplication is ",a) Output: multiplication is 24 In the above example we have defined a function mul which multiplies two numbers and returns a value. While calling the function, we have passed only one argument instead of two. This code works well because we have already defined the default value for both parameters. When one or both arguments are not passed, the default value is used in the function.

ARBITRARY ARGUMENTS We generally pass a known number of arguments while calling a function. We can pass arguments less than parameters when default parameters are declared. But what if we pass more numbers of arguments than parameters defined? In this condition we use arbitrary arguments. Python allows us to pass an arbitrary number of arguments into a function and then process those arguments inside the function. To define a parameter list as being of arbitrary length, a parameter is marked with an asterisk (*). 96


For example: >>> def names(*args): for name in args: print('Welcome', name) >>>names ('Diwas’, ‘Sush’, ‘Pari’, ‘Sunil’) Output: Welcome Diwas Welcome Sush Welcome Pari Welcome Sunil

LAMBDA FUNCTION Lambda function is an anonymous function that takes any number of arguments but takes only one expression. An anonymous function is a function defined without a name.

SYNTAX lambda arguments : expression Normal functions are defined using the def keyword whereas anonymous functions are defined using the lambda keyword. EXAMPLE 01: To add two numbers >>> x = lambda a, b : a + b >>> print(x(3,4)) Output: 7

97


EXAMPLE 02: To multiply three numbers >>> x = lambda a, b : a * b * c >>> print(x(3,4,2)) Output: 24

WHY LAMBDA FUNCTION ?? Lambda function is used when we need a nameless function for a short period of time. We generally use the lambda function inside another function. Let’s take an example: >>> def normal_function(n): return lambda a : a + n >>> callfn = normal_function(2) >>> print(callfn(5)) Output: 7

98


Lambda functions can be used together with Python's built-in functions like map( ), filter( ), reduce( ), etc.

LAMBDA WITH FILTER( ) The filter() function takes a lambda function together with a list as the arguments. This function can be used to filter out all the elements of a list which satisfies the condition and returns a new list. # filter() with lambda() # create list of number divisible by 3 >>> list_01 = [1,2,3,4,5,6,7,8,9,10] >>> new_list = list(filter(lambda x: (x%3 == 0) , list_01)) >>> print(new_list) Output: [3,6,9]

LAMBDA WITH MAP( ) The map() function takes a function together with a list as the argument. This function can be used to generate elements of a list returned by that function for each item. >>> original_list = [2,4,6,8,10,12,14,16] >>> new_list = list(map(lambda x: x * 2 , original_list)) >>> print(new_list) Output: [1,3,5,7,9,11,13,15] 99


LAMBDA WITH REDUCE( ) The reduce() function takes a function together with a list as the argument. We obtain a reduced output using this function. This is a part of the functools module. Let’s take a look at an example: >>> from functools import reduce >>> old = [1,2,3,4,5,6,7,8,9,10] >>> sum = reduce((lambda x, y: x + y), old) >>> print (‘Sum of the first ten natural number is :’,sum) Output: Sum of the first ten natural number is 55 Process involved = (((((((((1+2)+3)+4)+5)+6)+7)+8)+9)+10) = 55

FUNCTION OVERLOADING Function overloading, one of the features of object-oriented programming, is defined as the ability to create various functions with the same name but different in parameters and arguments. In reality, Python doesn't support function overloading. The latest created function replaces all the other previous functions.

>>> def area(a,b): print (a*b) >>> def area (a): print(a*a) #>>> #area(6,5) # TypeError: area() takes 1 argument but 2 were given >>> area (4) Output: 16 100


PROGRAMMING EXAMPLES EXAMPLE 01: ADD TWO NUMBERS >>> def add(x,y): return(x+y) >>> a = 3 >>> b = 5 >>> c = add(a,b) >>> print ( "sum of ",a," & ",b," is ",c) Output: sum of 3 & 5 is 8

>>> def add(x,y): return(x+y) >>> a = int(input ("enter first number ")) >>> b = int(input ("enter second number ")) >>> c = add(a,b) >>> print ( "sum of ",a," & ",b," is ",c) Output: enter first number 5 enter second number 6 sum of 5 & 6 is 11

101


EXAMPLE 02: AREA OF RECTANGLE >>> def area(l,b): return(l*b) >>> l = int(input ("enter length ")) >>> b = int(input ("enter breadth ")) >>> a = area(l,b) >>> print("area of rectangle is ",a) Output: enter length 5 enter breadth 6 area of rectangle is 30 EXAMPLE 03: ODD OR EVEN NUMBER >>> def oe(num): if (num%2==0): print(num," is even number") else: print(num," is odd number") >>> num = int(input ("enter a number : ")) >>> oe(num) Output: enter a number : 4 4 is even number

102


EXAMPLE 04: CHECK PRIME NUMBER >>> def prime(a): c = 0 if (a<1): print("invalid input ! Try next number ") elif(a==1): print ("1 is not prime") else: for i in range(2,a,1): if (a%i==0): c=1 if (c==0): print(a," is prime") else: print(a," is not prime") >>> num = int (input("enter a number : ")) >>> prime(num) Output: enter a number: 6 6 is not prime EXAMPLE 05: AREA OF RECTANGLE USING LAMBDA #>>> area = (lambda x,y : x*y)(5 , 4) >>> area = (lambda x,y : x*y) >>> print ( area(5,4)) Output: Area of rectangle is : 20

next method

103


11 RECURSION Recursion is defined as the process in which a function calls itself as a subroutine. The same function is called repeatedly by itself until the stopping condition is met. Recursion is taken as an efficient method of coding since we require very less code to write a complete program. The disadvantage of recursion is that it increases the complexity of the program and is harder to debug. The stopping condition of recursion are: 1. Solution has been found 2. When the base case is met. The base case is the condition in which the problem can be solved without recursion. 3. A maximum level of recursion is reached. The recursive function will continue to call itself until some stopping (base) condition is met to stop the recursion. >>> def add_natural(x): if (x==1): return 1 return (x+add_natural(x-1)) >>> num = int (input("sum of how many natural numbers ?? : ")) >>> sum = add_natural(num) >>> print ("sum is ",sum) Output: sum of how many natural numbers ?? : 5 sum is 15

104


In the above example, we are writing a program to print the sum of n natural number where n is taken from the user as input. Suppose n is 5. We have defined a function named add_natural where x is taken as a parameter. During function call, 5 is passed to the defined function. During the first iteration, x is 5 so if the condition is false. In return statement, it has called itself by reducing the value of x. Let's see below: 5 + add_natural(4)

: First iteration

4 + add_natural(3)

: Second iteration

3 + add_natural(2)

: Third iteration

2 + add_natural(2)

: Fourth iteration

1

: (stopping condition met)

Hence (5+4+3+2+1) i.e 15 is returned

BENEFITS OF RECURSION ● Reduces unnecessary calling of function as it calls itself until stopping condition is met ● Reduces the size of code as big and complex iterative solutions become easy and simple with Python recursion ● Tends to be less error-prone as it becomes much easier to visualize ● Many problem statements are recursive in essence: the best, most concise, clear and provably correct way Recursion is usually slower than an iterative solution as Python's stack depth is not unlimited. It requires extra storage space as for every recursive call separate memory is allocated for the variables. Unless we explicitly set the maximum limit of recursions, the program by default will throw a Recursion error after 1000 recursions. 105


EXAMPLE 01: To find factorial of a number using Recursion >>> def fac(x): if (x==0): return 1 return (x*fac(x-1)) >>> num = int (input("enter a number ?? : ")) >>> out = fac(num) >>> print ("factorial of ",num," is ",out) Output: enter a number ?? : 1 factorial of 1 is 1 EXAMPLE 02: To find n Fibonacci number using Recursion >>> def fib(n): if n == 1 : return 1 elif n == 2 : return 1 else: return (fib(n-1)+fib(n-2)) >>> num = int(input("how many fibonacci series ?? ")) >>> c = fib(num) >>> print (c,"is the required output") Output how many Fibonacci series ?? 6 8 is the required output 106


12 PYTHON AS OOP Procedural programming focuses on function and procedure whereas object-oriented programming focuses on class and objects. OOP binds the data and the functions that operate on them so that data can be abstracted, which is one of the important features of object-oriented programming. These objects are organized into classes, which allow individual objects to be grouped together. OOP focuses on collecting all of the objects a programmer wants to manipulate and identify how they relate to each other. We will study about Class and Objects in our next chapter. The important features of Object-Oriented programming are: ● ● ● ● ●

Class & Object Abstraction Encapsulation Inheritance Polymorphism

ENCAPSULATION Encapsulation is defined as the hiding of sensitive data from the user by wrapping data under a single unit. Data of a class is encapsulated so that other classes and objects can’t access those data without special access permission. Encapsulation provides greater data security. To achieve encapsulation, we must declare class variables/attributes as private. Private is an access specifier that defines how the members

107


(attributes and methods) of a class can be accessed. Other access specifiers are public, protected.

ABSTRACTION Abstraction refers to the process of hiding the internal behavior of the program and showing only user understandable code. It hides the internal structures, data types, objects, and functions which helps developers make changes and additions over time more easily. By virtue of data abstraction only the essential details are displayed to the user hiding any unnecessary implementation code. Let’s take a famous real-world example of a man calling his friend. The man needs to know to dial numbers or needs to know to pick up the phone. But he doesn’t know how his phone gets connected to his remote friend. This is what abstraction is.

INHERITANCE Inheritance refers to the concept of inheriting behaviors of the existing class to the new classes or objects. It means many child classes can be derived from the child class with some or behaviors inherited. Child classes are also known as derived classes. We will study about inheritance in our next chapter in detail. WHY INHERITANCE? 1. 2. 3.

Improve maintainability. Reduce Cost. Avoid re-code and support reusability.

108


POLYMORPHISM Polymorphism refers to certain items appearing in different forms or ways. Polymorphism provides the ability for classes to provide different implementations of methods that are called through the same name. We will study about polymorphism in our next chapter in detail.

SUMMARY ● OOP provides importance on data rather than procedures or functions. ● Data and associated processes are unified, grouping objects with common attributes, operations, and semantics. ● Supports data hiding by making it accessible only to the class in which it is defined. ● OOP approach helps in reducing the code size since classes can be just derived from the existing one and one needs to add only the new features and it helps users to save their time. ● OOP extends the handling of data types and operations. ● OOP hides unnecessary details in classes and delivers a simple and clear interface for working. 109


13 CLASS & OBJECT CLASS Class is a core concept in a style of programming known as Object-Oriented Programming. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class also describes object behavior. Consider the Class of motorcycles. There may be many motorcycles with different names and brands but all of them will share some common properties like all of them will have 2 wheels, Speed Limit, Mileage range, etc. So, Motorcycle is the class and wheels, speed limits, mileage are their properties. In many cases classes are used to represent real-world entities. Classes actually act as templates that are used to construct instances or examples of a class of things. An instance or object is therefore an example of a class. We define classes by using the class keyword. In Python, a class definition has the following format: class nameOfClass: __init__ attributes methods

110


Let’s create a class with the class name Smartphone. Suppose we have two objects Samsung and Apple that belong to the class of smartphones. Let objects' attributes are size, price, and methods be buy(). >>> class smartphone: #instance attributes next = " one method of instance attribute" def __init__(self, name, size, price): self.name = name self.size = size self.price = price #instance method def buy(self, location): return (‘Apple sell market is in’, location)

There is also a special method defined called __init__. This is an initializer also known as a constructor) for the class.

OBJECT An Object is an instance of a particular class or subclass with the class's own methods or procedures and data variables. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. Object determines the behavior of the class. Variables that belong to an object or class are referred to as fields. Objects can also have functionality by using functions that belong to a class. Such functions are called methods of the class. Another way to say this is that a method is an action that an object is able to perform. The fields and methods can be referred to as the attributes of that class. Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by 111


creating an instance of that class and passing in the values to be used for the parameters of the initialization method (with the exception of the first parameter self which is provided automatically by Python). For example, the following creates two instances of the class smartphone: >>> s = smartphone("Samsung","M", 300) >>> a = smartphone("apple","L", 900) We can create multiple different objects that are of the same class. However, each object contains independent copies of the variables defined in the class. In the above example, we have created two objects s & a under the same class smartphone. The variable s holds a reference to the instance or object of the class smartphone whose attributes hold the values 'Samsung' (for the name attribute) and ‘M’ (for size attribute) and 300 (for the price attribute). In turn variable a holds a reference to the instance or object of the class smartphone whose attributes hold the values 'apple' (for the name attribute) and ‘L’ (for size attribute) and 900 (for the price attribute). The two variables s and a reference separate instances or examples of the class smartphone.

ACCESSING ATTRIBUTES

We can access the attributes held by s and a using what is known as the dot notation. Let’s go with an example:

>>> print (s.name,"costs",s.price,"$") >>> print (a.buy("New York")) Output: Samsung costs 300$ Apple sell market is in New York

112


CONSTRUCTOR Constructor is used for initializing the instance members when we create the object of a class. A constructor always has a name init and the name init is prefixed and suffixed with a double underscore(_ _). In the above example, we have an instance variable name, size, price which we are initializing in the constructor. -----------SYNTAX------------- def __init__(self): #constructor body All classes have a function called ​init​(), which is always executed when the class is being initiated. We use built-in ​init​() function to assign values to object properties, or other operations that are necessary to do when the object is being created.

>>> class Dog: def __init__(self, name): self.name = name >>> x = Dog("votey") >>> print (x.name ) Output: votey

#creating class # constructor

Sometimes, we don't declare a constructor. In such condition, the default constructor is implicitly injected by python during program compilation, which is an empty default constructor and looks like: >>> def __init__(self): # no body, does nothing

113


Generally, there are two types of constructors on the basis of parameters. 1. default constructor: without any parameters 2. parameterized constructor: with parameters # default constructor >>> class default(): def __init__(self): self.num = 30 >>> x = default () >>> print (x.num) Output: 30

# parameterized constructor >>> class default(): def __init__(self,num): self.num = num >>> x = default (50) >>> print (x.num) Output: 50

SELF Self in the constructor is used to access variables that belong to the class and self is defined as the reference to the current instance of the class. We need not give the same name self, that means we can name it like variables but it has to be the first parameter of any function in the class. This is illustrated in the example below where in place of self we have used diwas.

114


>>> class john: def __init__(diwas, name): diwas.name = name >>> x = john("votey") >>> print (x.name )

#creating class # constructor

DESTRUCTOR del() ​method is known as a destructor method in Python. Destructors are called when an object needs to be destroyed. Destructors are used to delete unneeded objects to free the memory space. # syntax of destructor >>> def __del__(self): # body of destructor >>> class Point: def __init__( self): self.x = 3 self.y = 4 def __del__(self): class_name = self.__class__.__name__ print ( " object is now destroyed") >>> obj1 = Point() >>> del obj1 Output: object is now destroyed 115


INHERITANCE IN PYTHON Inheritance refers to the concept of inheriting behaviors of the existing class to the new classes or objects. It means many child classes can be derived from the child class with some or behaviors inherited. Child classes are also known as derived classes. In OOP features common to all the classes are defined in the superclass (Base Class) and derived class inherit common features from the superclass. The main advantage of using this concept of inheritance in Object-oriented programming is reusability. Let’s go with one example: class Person: def __init__(self, name, age): self.name = name self.age = age def birthday(self): print('Happy birthday to you', self.name)

Now we are going to define Employee as being a class that inherits the class Person. class Employee(Person): def __init__(self, name, age, id): super().__init__(name, age) self.id = id Here, we have created a child class Employee inherited from superclass Person. Inside the __init__ method we reference the __init__() method

116


defined in the class Person and used to initialize instances of that class (via the super().__init__() reference. print('Employee') e = Employee('Denise', 51,44) e.birthday() Output: Happy birthday to you Denise

POLYMORPHISM Polymorphism refers to certain items appearing in different forms or ways. Polymorphism provides the ability for classes to provide different implementations of methods that are called through the same name. Overloading is a kind of polymorphism. It allows a single name or operator to be associated with different operations, depending on the type of data it has passed. Polymorphism is one of the main features of OOP as it extends the handling of data types and operations. To make use of polymorphism, we’re going to create two distinct classes (Football() and Cricket() ) to use with two distinct objects. Each of these distinct classes need to have an interface that is in common( play() ) so that they can be used polymorphically, so we will give them methods that are distinct but that have the same name. >>> class Football(): def play(self): print("Football is played with legs")

117


>>> class Cricket(): def play(self): print("Cricket is played with the hand") Let’s instantiate these classes into two objects: >>> Ronaldo = Football() >>> Sachin = Cricket() To show polymorphism, we are creating a for loop that iterates through a tuple of objects. Here, we are calling the methods without being concerned about which class type each object is. >>> for game in (Ronaldo, Cricket): >>> game.play() Output: Football is played with legs Cricket is played with the hand This shows that Python is using these methods in a way without knowing or caring exactly what class type each of these objects is. That is, using these methods in a polymorphic way. 118


14 ARRAY

Array is a form of data structure that can store a sequential fixed-size array of the same type of elements. Also, an array is used to store a collection of data, but it is often useful to think of an array as a collection of values of the same type. So, arrays are similar to lists but with one difference that we need to have all the values of the same type. For example, if we say it is an int array then all the values stored in the array should be an integer type. If you say it is a float array then all the values stored in the array should be float. The main advantage of arrays is that they do not have a specific size which means we can expand or shrink it. Python does not have built-in support for Arrays, but Python Lists can be used instead. To work with arrays in Python we need to import a library and Numpy is one of the libraries used. Here, we will be importing a module called array. >>> import array

Instead of using array every time, we can use aliases which is an alternate term for a given data entity which is typically simpler to recognize. >>> import array as arr >>> arr.array()

While creating an array we have to specify two things: 1. Type 2. Values

119


TYPE In an array all the values should be of the same data type. If we have an array and its value as an integer we have to mention it is an int array. If it is a float array we have to mention it as a float. Compared with other programming languages int, float keywords can not work in Python. To mention the type of an array, we have to use Type code which means every type has a unique code. For example, the moment when we change type it will change the size in the memory, for a small integer we use byte, the normal integer will 2 bytes and we have a long integer which will take 4 bytes. Small float will take 4 bytes and double floats will take 8 bytes. For character we have to use U which is Unicode which takes 2 bytes to show data. Another question may arise: what if you want to have unsigned and signed integers? Signed integers are those types of integer that can have both positive and negative values. If the user wants to store only positive values in that case the user will be going for an unsigned integer because it starts with zero and ends at a particular value. So the advantage of an unsigned integer is that we will not consider negative numbers. Let's see the example for creating an array of integer types. >>> import array as ar >>> marks = ar.array('i',[20,30,40,60,70]) >>> print ("The newly created array is : ", end =" ") >>> for i in range (0, 3): print (marks[i], end =" ") Output: The newly created array is: 20 30 40 60 70

120


Commonly used type codes are listed as follows: TYPE CODE C TYPE

PYTHON TYPE MIN SIZE IN BYTE

b

Signed Char

int

1

B

Unsigned Char

int

1

u

Py_UNICODE

Unicode

2

h

Signed short

int

2

H

Unsigned short

int

2

i

Signed int

int

2

I (capital i )

Unsigned int

int

2

l ( small L)

Signed long

int

4

L

Unsigned long

int

4

q

Signed long long

int

8

Q

Unsigned long long int

8

f

float

float

4

d

double

float

8

Let’s use one function on an array i.e. buffer info which gives the size of an array in tuple form like (a, b) where a is the address of array and size of an array. >>> from array import * >>> marks = array('i',[20,30,-40,60,70]) >>> print('Using buffer function -->', marks.buffer_info()) Output: Using buffer function --> (1970670944664, 5) 121


APPEND Arrays are mutable i.e their elements can be changed in a similar way like lists. Using the built-in insert() function we can add elements to the array. As per the requirement, one or more elements can be added at the beginning, end, or any given index of an array. Append() can be used to insert a new element at the end. >>> import array as ar >>> a = ar.array('f', [1, 3, 4]) #float array >>> print ("Array before insertion : ", end =" ") >>> for i in range (0, 3): print (a[i], end =" ") >>> a.insert(1, 2) # inserting 2 at index 1 >>> print ("\n Array after insertion : ", end =" ") >>> for i in range (0, 4): print (a[i], end =" ") Output: Array before insertion: 1 3 4 Array after insertion : 1 2 3 4 >>> import array as ar >>> a = ar.array('f', [1,2,3]) #float array >>> a.insert(4) # inserting 4 at end >>> print ("\n Array after insertion : ", end =" ") >>> for i in range (0, 4): print (a[i], end =" ") Output: Array after insertion : 1 2 3 4

122


ACCESS In order to access the items of an array, we use the index operator [ ] in Python where index must be an integer. >>> import array as ar >>> a = ar.array('i', [2, 4, 6, 8]) >>> print("First element:", a[0]) >>> print("Second element:", a[1]) >>> print("Last element:", a[-1]) Output: First element: 2 Second element: 4 Last element: 8

>>> import array as ar >>> a = ar.array('f', [1, 2,3, 4]) #float array >>> print ("Array elements : ", end =" ") >>> for i in range (len(a)): print (a[i], end =" ") Output: Array elements: 1 2 3 4

The following are the important points to be considered. ● Index starts with 0. ● Array length is 10 which means it can store 10 elements.

123


CHANGE/UPDATE >>> import array as ar >>> a = ar.array('f', [1, 3, 3]) #float array >>> print ("Array before update : ", end =" ") >>> for i in range (0, 3): print (a[i], end =" ") >>> a[1] = 2 # updating value 2 at index 1 >>> print ("\n Array after update : ", end =" ") >>> for i in range (0, 3): print (a[i], end =" ") Output: Array before update: 1 3 3 Array after update: 1 2 3

REMOVE We use remove() and pop() methods to remove items from an array. We can also delete one or more items from an array using Python's del statement. If we want to remove elements from a specific position of the array, the index of the element is passed as an argument to the pop() method. >>> import array as ar >>> number = ar.array('i', [1, 2, 3, 3, 4]) >>> del number[2] # removing third element #output: 1 2 3 4 >>> del number # deleting entire array >>> number = ar.array('i', [1, 2, 3, 3, 4]) >>> numbers.remove(3) # deletes 3 from first found >>> print(numbers.pop(2)) # deletes 3 i.e items at index 2

124


NEW ARRAY WITH SAME VALUE Here, we are going to create a new array with the same value. >>> from array import * >>> marks = array('i',[20,30,-40,60,70]) >>> new_array = array(marks.typecode, (i for i in marks)) >>> new_array Output: array('i', [20, 30, -40, 60, 70])

How to create a new array with a square of the previous value? >>> new_array = array(marks.typecode, (i ** 2 for i in marks)) >>> new_array Output: array('i', [400, 900, 1600, 3600, 4900])

SEARCH We use a python in-built index() function to find the index of the first occurrence of value mentioned in arguments. >>> import array as ar >>> a = ar.array('i', [4,5,6,7,2,7,4]) >>> print ("The new created array is : ", end ="") >>> for i in range (len(a)): print (a[i], end =" ") >>> print ("The index of the 1st occurrence of 7 is : ", a.index(7))

125


Output: The new created array is : 4 5 6 7 2 7 4 The index of the 1st occurrence of 7 is: 3

CONVERT A LIST INTO AN ARRAY Lists can be converted to arrays using the built-in functions in the Python NumPy library. NumPy provides us with two functions to convert a list into an array: 1. numpy.array() 2. numpy.asarray()

USING NUMPY.ARRAY() >>> import numpy as np >>> original_list = [1,2,3,4,5] >>> print("original is ", end = " ") >>> print(type(original_list)) >>> changed_array = np.array(original_list) >>> print("\n final is ", end = " ") >>> print(type(changed_array)) Output: original is <class 'list'> final is <class 'numpy.ndarray'>

126


USING NUMPY.ASARRAY() >>> import numpy as np >>> original_list = [1,2,3,4,5] >>> print("original is ", end = " ") >>> print(type(original_list)) >>> changed_array = np.asarray(original_list) >>> print("\n final is ", end = " ") >>> print(type(changed_array)) Output: original is <class 'list'> final is <class 'numpy.ndarray'>

The main difference between np.array() and np.asarray() is that np.array() will make a copy of the object (by default) and convert that to an array, while np.asarray() will not. 127


15 FILE HANDLING

A file can be defined as an object on a computer that stores data, information, settings, or commands used with a computer program. File, identified by a filename, can be a document, picture, audio or video stream, data library, application, or other collection of data. In our daily life, we have used different forms of files such as music files, video files, text files, photo files. We typically break data into two categories i.e. text file and binary(computer-readable) file.

OPEN( ) In Python, the open () function is used to open a file in read or write mode. open() function which requires two arguments, first argument stores file path or file name, and the second argument is known as a mode to open the file. There are various methods (modes) for opening a file: ● “r”: opens read-only, but you can not modify or erase anything inside the file, generates an error if the file does not exist ● “w”: opens with write control, creates the file if it does not exist ● “a”: opens in append mode, creates the file if it does not exist ● “x”: opens a file for exclusive creation, returns an error if file exists ● “t”: opens text mode ● “b”: opens the binary mode ● “+”: opens file for both reading and writing

128


>>> file_1 = open("demofile.txt", "rt")

In the above example, we have used "r" for read, and "t" for text. The mode argument in Python is not mandatory. If not passed, then Python will assume it to be “​ rt ​” by default. >>> file_1 = open("demofile.txt")

READ( ) The read() method is used to read text from a file in Python. Usually read() is used to return the whole text, but we can also specify numbers of characters we want to read. >>> file_1 = open("demofile.txt", "rt") >>> print(file_1.read(5)) #reads five characters from file

What if we want to print only the first line of our data? For this problem, we have a readline() method. >>> file_1 = open("demofile.txt") >>> print('Printing first line from file \n', file_1.readline()) We can read a file line-by-line using a for loop. This is both efficient and fast. >>> file_1 = open("demofile.txt", "rt") >>> for line in file_1: print line

129


WRITE( ) To write some text to a file we use the write() method. Firstly, we must add the following parameter to the open() function. ● "a" - Append - will append to the end of the file, creates a file if the specified file does not exist ● "w" - Write - will overwrite any existing content, creates a file if the specified file does not exist ● "x" - Write - opens a file for exclusive creation, returns an error if the file exists >>> file_1 = open("demofile.txt", "w") #creates file if doesn’t exist >>> file_1.write("This writes to the file") >>> file_1.close()

This function acts similar to the write() function, however, instead of overwriting the file, the append() function appends content to the existing file. It is always a good method to close a file after reading or writing on it. Hence we use the close() function for it. We'll have to re-open it if we want to read from it again.

WITH STATEMENT with statement can also be used in file handling which is designed to provide much cleaner syntax and exceptions handling when you are working with code. Any files opened will be closed automatically after you are done in this method. >>> with open(“demofile.txt”, “w”) as file: >>> file.write(“Hello World”)

130


COPY FILE We can also copy the contents of one file into another file. >>> file = open('myData.txt','r') >>> file2 = open('new_file.txt', 'w') >>> for data in file: file2.write(data)

DELETE FILE >>> import os >>> if os.path.exists("demofile.txt"): os.remove("demofile.txt") >>> else: print("The file does not exist") BONUS: H ​ OW IMAGE IS STORED? >>> image = open('my_image.jpg', 'rb') >>> for i in image: print(i) Output: b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xd b\x00\x84\x00\t\x06\x07\x13\x12\x12\x15\x12\x12\x12\x16\x15\x15\x17\x19\x1f\ x16\x17\x18\x15\x16\x16\x1f\x18\x1b\x1d\x17\x17\x18\x16\x18\x19\x1a\x18\x18 ( \x18\x1b%\x1b\x18\x15"1!%)+...\x1a\x1f383-7(-.+\x01\n' b'\n' b'\n' b'\x0e\r\x0e\x1a\x10\x10\x1b0& %004.-+++--/-.0+/-+------------/--.--/-

131


16 MISCELLANEOUS

BINARY SEARCH >>> position = -1 >>> list = [5 , 8 , 10 , 20 , 40] >>> n = 40 >>> def search(list, n): lower_bound = 0 upper_bound = len(list) - 1 while lower_bound <= upper_bound: mid = (lower_bound + upper_bound) // 2 if list[mid] == n: globals ()['position'] = mid return True else: if list[mid] <n: lower_bound = mid + 1 else: upper_bound = mid - 1 return False >>> if search(list, n): print('Found at -->' , position + 1 ) >>> else: print('Not Found') Output: Found at --> 5 132


LINEAR SEARCH >>> position = -1 >>> list = [5 , 8 , 10 , 20 , 40] >>> n = 40 >>> def search(list, n): i = 0 while i < len(list): if list[i] == n: globals ()['position'] = i return True i += 1 return False >>> if search(list, n): print('Found at -->' , position + 1 ) >>> else: print('Not Found') Output: Found at --> 5

BUBBLE SORT >>> nums = [5,8,3,7,6,2,1] >>> def sort(nums): for i in range(len(nums) - 1 , 0, -1): for j in range(i): if nums[j] > nums[j + 1 ]: temp = nums[j] nums[j] = nums[ j + 1] nums[ j + 1] = temp

133


 print('\n For every iteration >>> sort(nums) >>> print('\n Sorted element ->', nums)  Final Output: Sorted element -> [8, 7, 6, 5, 3, 2, 1]Â

đ&#x;‘‡

\n',nums)Â

 SELECTION SORT >>> nums = [5,8,3,7,6,2,1] >>> def sort(nums): for i in range(len(nums) - 1):  maxpos = i  for j in range(i, len(nums)):  if nums[j] > nums[maxpos]:  maxpos = j     temp = nums[i]  nums[i] = nums[maxpos]  nums[maxpos] = temp     print('\n For every iteration \n',nums) >>> sort(nums) >>> print('\nSorted element ->', nums)  Final Output: Sorted element -> [8, 7, 6, 5, 3, 2, 1]Â

đ&#x;‘‡

 For stepwise output: ​click hereÂ

134


SCISSOR PAPER ROCK (​Download​) >>> import time >>> import sys >>> import random >>> def win(): print('The GAME: You won!') >>> def lost(): print('The GAME: You lost') >>> def draw(): print('The GAME: It’s a draw') >>> def the_game(): moves = ['rock', 'paper', 'scissor'] print('The GAME: rock, paper, scissor? ') attempts = 3 while True: if attempts == 0: print('Sorry, you provide wrong option to play a game. ') time.sleep(3) sys.exit(0) player = input('Player: ').lower() if player.lower() not in moves: print(f'The Game: Invalid option ! you have {attempts} attempts left.') attempts -= 1 else: computer = random.choice(moves) print(f'Computer: {computer}') if player == computer: 135


draw() elif player == 'rock' and computer == 'scissor': win() elif player == 'rock' and computer == 'paper': lost() elif player == 'paper' and computer == 'rock': win() elif player == 'paper' and computer == 'scissor': lost() elif player == 'scissor' and computer == 'paper': win() elif player == 'scissor' and computer == 'rock': lost() else: pass

play_again = input('The GAME: Retry? (y/n): ') if play_again.lower() == 'y': the_game() elif play_again.lower() == 'n': print('The GAME: Game over. Have a nice day') time.sleep(2.5) sys.exit(0) else: print('The GAME: Invalid options: Have a nice day') time.sleep(2.5) sys.exit(0) >>> if __name__ == '__main__': the_game() 136


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.