In this tutorial, we will learn about Operators in Python. Operators are special symbols which normally use to perform some special task in the program. For example, you want to add two number. Here we will use + operator to add two numbers or you want to assign value to a variable. Here we will use = assignment operator to assign value to a variable. There are so many operators available in Python and they are divided into different categories. We learn here all the categories. Show
Arithmetic operators:Arithmetic operators are so simple. Arithmetic operators are used to performing simple mathematical computations like addition, subtraction, multiplication and division. There are total of seven operators in this category and these are as follow.
Example of Arithmetic Operators in Python:num1 = 20 num2 = 5 # Output: num1 + num2 = 25 print('num1 + num2 =',num1+num2) # Output: num1 - num2 = 15 print('num1 - num2 =',num1-num2) # Output: num1 * num2 = 100 print('num1 * num2 =',num1*num2) # Output: num1 / num2 = 4.0 print('num1 / num2 =',num1/num2) # Output: num1 // num2 = 4 print('num1 // num2 =',num1//num2) # Output: num1 ** num2 = 3200000 print('num1 ** num2 =',num1**num2)Identity Operators:Identity Operators are used to comparing two objects. It will return true if both objects share the same memory location.
Example of Identity operators in Python:str1 = "Owlbuddy" str2 = str1 print(str1 is str2) print(str1 is not str2)Membership Operators:Membership operators in Python are used to check if a sequence is present in Object.
Example of Membership operators in Python:names = ["Ravi", "Gurpreet"] print("Ravi" in names) print("Hardeep" not in names)Comparison operators:Comparison operators are used to comparing two values in Python and the result of this comparison will come like true or false. Here are some operators which come in this category.
Example of Comparison operators in Python:num1 = 20 num2 = 25 # Output: num1 > num2 is False print('num1 > num2 is',num1 > num2) # Output: num1 < num2 is True print('num1 < num2 is',num1 < num2) # Output: num1 == num2 is False print('num1 == num2 is',num1 == num2) # Output: num1 != num2 is True print('num1 != num2 is',num1 != num2) # Output: num1 >= num2 is False print('num1 >= num2 is',num1 >= num2) # Output: num1 <= num2 is True print('num1 <= num2 is',num1 <= num2)Logical operators in Python:Logical operators are used to making comparison between two expressions. There are three logical operators in Python.
Example of Logical operators in Python:x = True y = False # Output: Result of x and y is False print('Result of x and y is',x and y) # Output: Result of x or y is True print('Result of x or y is',x or y) # Output:Result of not x is False print('Result of not x is',not x)Assignment operators in Python:Assignment operators are used to assigning value to a variable in Python. There is a rich collection of assignment operators in Python.
Example of Assignment Operators in Python:num = 3 print("Value of num= "+num) num+=10 print("Value of num= "+num) num-=5 print("Value of num= "+num) num*=2 print("Value of num= "+num) num/=2 print("Value of num= "+num) num%=2 print("Value of num= "+num)
Spread the love:Please share this page on social media with your friends..
Message Help us to make this site best. In case you find any mistake in this tutorial please inform us.
Download Owlbuddy: Learn Programming Tutorials App Now. Operators provide a vital role in programming, and in combination with values and other identifiers form expressions and statements, which is also an essential building block for Python programming. Operators and OperandsPython operators are symbols that are used to perform mathematical or logical manipulations. Operands are the values or variables with which the operator is applied to, and values of operands can manipulate by using the operators. Let us take a Scenario: 6 + 2=8, where there are two operands and a plus (+) operator, and the result turns 8. Here a single operator is used to manipulate the values. The +, -, *, / and ** does addition, subtraction, multiplication, division & exponentiation respectively. Types of Python OperatorsPython programming language is rich with built-in operators.
Arithmetic Operators
Assignment Operators
Comparison (Relational) Operators
Logical Operators
Identity OperatorsFor comparing memory locations of two objects, identity operators are used. There are two types of identity operators. These are:
Bitwise OperatorsThese operators are used to manipulate with bits, & performs bit-by-bit operations. There are six types of bitwise operators supported by Python. These are:
Membership Operators
Page 2Python data types are different in some aspects from other programming languages. It is simple to understand and easy to use. Because Python is interpreted programming language and Python interpreter can determine which type of data is storing, so no need to define the data type of memory location. The data type determines:
Data Types available in PythonEverything in Python programming is an object, and each object has its own unique identity(a type and a value). There are many native(built-in) data types available in Python. Some important are:
Because Python is a pure object-oriented programming language, so other data types are also available.
Page 3Before understanding the concept of variables in Python, you have to know how variables work in other programming languages. In C, Java, and many other programming languages, the concept of a variable is linked to memory space, and a variable is perceived as a storage box that can store some value. Example: x = 1;In the above example, memory is allocated with the name x, and there the value 1 is stored. Here, we can see the memory as a container that stores the value, as shown in the picture below. This way, for each variable, there will be a new memory space created with the name of the variable, and if we change the value of the variable, then memory will be updated with the new value. Example: int x,y = 1;In this way, we can understand how the variable works in other programming languages. But in Python, the case is different, and here a variable is seen as a tag or name that is tied to some value. Example: x = 1Here, in the above Python example, a value 1 is created in the memory, and then the tag name x has been created, which is tied to the value. If we change the variable value to a new value, then a new value is created in memory, and the tag is shifted to a new value. In this case, the old value becomes un-referenced, and the garbage collector removes it. Assigning a variable to another variable creates a new tag connected to the same value. Example: int y = x;In the above example, we are storing the value of x in y. A new tag y will be generated, which will refer to the value 1. In this way, we can understand how variables in Python differ from other programming languages. Page 4Variables are identifiers of a physical memory location, which is used to hold values temporarily during program execution. Python interpreter allocates memory based on the values data type of variable, different data types like integers, decimals, characters, etc. can be stored in these variables. What are Values?Before learning about variables, you must know about values. A value is one of the essential parts of a program, like a letter or a number. The examples of such values can be:
Python Variable DeclarationIn Python, like many other programming languages, there is no need to define variables in advance. As soon as a value is assigned to a variable, it is automatically declared. This is why Python is called a dynamically typed language. The syntax for creating variables in Python is given below: Syntax: <variable-name> = <value>Assigning Values to VariablesPython interpreter can determine what type of data is stored, so before assigning a value, variables do not need to be declared. Usually, in all programming languages, equal sign = is used to assign values to a variable. It assigns the values of the right side operand to the left side operand. The left side operand of = operator is the name of a variable, and the right side operand is value. Example: name = "Packing box" # A string height = 10 # An integer assignment width = 20.5 # A floating point print (name) print (height) print (width)Output: Packing box 10 20.5In the above code snippet, the variable name 'height' is storing a value 10, and since the value is of type integer, the variable is automatically assigned the type integer. Commons Rules for Naming Variables in PythonPython has some variable related rules that must be followed:
Python Variable DeletionPython also provides the facility to delete a variable from memory. For this, the del command is used. The following is the general syntax for deleting a variable in Python: Syntax: del <variable-name>Page 5As we know, programming languages have their prime things - Numbers, Data types, Strings, Variables, etc., which play a significant role in constructing a program. When we say Numbers, we mean to say Python programming supports integers, floating-point numbers, and complex numbers. These are number-based data types that store various types of numeric values. Number objects get generated when programmers assign a value to them. For example: Example: variable_name1 = 10 variable_name2 = 6.2These reference to number objects can also be deleted by using del statement. The syntax for "del" statement is: Syntax: del variable_name[, variable_name2[….variable_name-N]All of them act as a class in Python, where integers and floating-point/decimal values are separated based on the presence or absence of decimal point between the values. 6 is an integer, whereas 6.2 is a floating-point value. Types of Numerical Data TypesPython provides four distinctive numerical types. These are:
Type Conversion (Casting)Python has the capability and feature to convert within an expression containing the mixture of different types of values internally.
Example: x = 10.5 y = 5 #without type cast print (x + y) #after type cast print (int(x) + y)Output: 15.5 15The above example shows how float converted to an integer. Page 6Decisions in a program are used when the program has conditional choices to execute a code block. Let's take an example of traffic lights, where different colors of lights lit up in different situations based on the conditions of the road or any specific rule. It is the prediction of conditions that occur while executing a program to specify actions. Multiple expressions get evaluated with an outcome of either TRUE or FALSE. These are logical decisions, and Python also provides decision-making statements that to make decisions within a program for an application based on the user requirement. Python provides various types of conditional statements:
if StatementThe decision-making structures can be recognized and understood using flowcharts. Figure - If condition Flowchart: Syntax: if expression: #execute your codeExample: a = 15 if a > 10: print("a is greater")Output: a is greaterif else StatementsFigure - If else condition Flowchart: Syntax: if expression: #execute your code else: #execute your codeExample: a = 15 b = 20 if a > b: print("a is greater") else: print("b is greater")Output: b is greaterelif Statementselif - is a keyword used in Python replacement of else if to place another condition in the program. This is called chained conditional. Figure - elif condition Flowchart: Syntax: if expression: #execute your code elif expression: #execute your code else: #execute your codeExample: a = 15 b = 15 if a > b: print("a is greater") elif a == b: print("both are equal") else: print("b is greater")Output: both are equalWe can write if statements in both ways, within parenthesis or without parenthesis/ brackets, i.e. ( and ). Single Statement ConditionIf the block of an executable statement of if - clause contains only a single line, programmers can write it on the same line as a header statement. Example: a = 15 if (a == 15): print("The value of a is 15")Page 7In programming, loops are a sequence of instructions that does a specific set of instructions or tasks based on some conditions and continue the tasks until it reaches certain conditions. It is seen that in programming, sometimes we need to write a set of instructions repeatedly - which is a tedious task, and the processing also takes time. So in programming, we use iteration technique to repeat the same or similar type of tasks based on the specified condition. Statements are executed sequentially, but there sometimes occur such cases where programmers need to execute a block of code several times. The control structures of programming languages allow us to execute a statement or block of statements repeatedly. Types of Loops in PythonPython provides three types of looping techniques: Python Loops
for LoopThe graphical representation of the logic behind for looping is shown below: Figure - for loop Flowchart: Syntax: for iterating_var in sequence: #execute your codeExample 01:for x in range (0,3) : print ('Loop execution %d' % (x))Output: Loop execution 0 Loop execution 1 Loop execution 2Example 02:for letter in 'TutorialsCloud': print ('Current letter is:', letter)Output: Current letter is : T Current letter is : u Current letter is : t Current letter is : o Current letter is : r Current letter is : i Current letter is : a Current letter is : l Current letter is : s Current letter is : C Current letter is : l Current letter is : o Current letter is : u Current letter is : dwhile LoopThe graphical representation of the logic behind while looping is shown below: Figure - while loop Flowchart: Syntax: while expression: #execute your codeExample: #initialize count variable to 1 count =1 while count < 6 : print (count) count+=1 #the above line means count = count + 1Output: 1 2 3 4 5Nested LoopsSyntax: for iterating_var in sequence: for iterating_var in sequence: #execute your code #execute your codeExample: for g in range(1, 6): for k in range(1, 3): print ("%d * %d = %d" % ( g, k, g*k))Output: 1 * 1 = 1 1 * 2 = 2 2 * 1 = 2 2 * 2 = 4 3 * 1 = 3 3 * 2 = 6 4 * 1 = 4 4 * 2 = 8 5 * 1 = 5 5 * 2 = 10Loop Control StatementsThese statements are used to change execution from its normal sequence. Python supports three types of loop control statements: Python Loop Control Statements
Break statementSyntax: breakExample: count = 0 while count <= 100: print (count) count += 1 if count >= 3: breakOutput: 0 1 2Continue statementSyntax: continueExample: for x in range(10): #check whether x is even if x % 2 == 0: continue print (x)Output: 1 3 5 7 9Pass StatementSyntax: passExample: for letter in 'TutorialsCloud': if letter == 'C': pass print ('Pass block') print ('Current letter is:', letter)Output: Current letter is : T Current letter is : u Current letter is : t Current letter is : o Current letter is : r Current letter is : i Current letter is : a Current letter is : l Current letter is : s Pass block Current letter is : C Current letter is : l Current letter is : o Current letter is : u Current letter is : dPage 8In Python, break and continue are loop control statements executed inside a loop. These statements either skip according to the conditions inside the loop or terminate the loop execution at some point. This tutorial explains break and continue statements in Python. Break StatementA break statement is used inside both the while and for loops. It terminates the loop immediately and transfers execution to the new statement after the loop. For example, have a look at the code and its output below: Example: count = 0 while count <= 100: print (count) count += 1 if count == 3: breakProgram Output: 0 1 2In the above example loop, we want to print the values between 0 and 100, but there is a condition here that the loop will terminate when the variable count becomes equal to 3. Continue StatementThe continue statement causes the loop to skip its current execution at some point and move on to the next iteration. Instead of terminating the loop like a break statement, it moves on to the subsequent execution. Example: for i in range(0, 5): if i == 3: continue print(i)Program Output: 0 1 2 4In the above example loop, we want to print the values between 0 and 5, but there is a condition that the loop execution skips when the variable count becomes equal to 3. Page 9A string is usually a bit of text in programming that is written to be displayed to users. It is known to Python when you want to display a string. This is because programmers use either double quote " or single quote ' to enclose a word or group of words to express a string. Example: ch = 'HelloPython' str1 = "String Chapter"Accessing String ValuesCharacters are not supported by Python, which makes it simpler as characters in Python are treated as strings of length one and hence considered as a sub-string. The program is showing the use of strings and how they are displayed on-screen. Example: ch = 'Hello Python' str1 = "String Chapter" print ("First value is: " , ch) print ("Second value is: " , str1)Output: First value is: Hello Python Second value is: String ChapterIf they are considered as a list of characters, then the example shown below will let you understand how they are treated individually: Example: ch = "Hello Python" str1 = "String Chapter" print ("First single sub-string is: " , ch[0]) print ("Set of sub-string is: " , str1[2:5])Output: First single sub-string is: H Set of sub-string is: rinUpdating a String Value or VariableReassigning the existing string-variable is more straightforward in Python. We have to use + operator along with the sub-string location. Let's show this as an example: Example: ch = "Hello Python" print ("UPDATED STRING WILL BE: " , ch [:8]+ "Python")Output: UPDATED STRING WILL BE: Hello PyPythonEscape CharactersThese are special characters represented by a backslash followed by the character(s), and they are used for particular purposes. They can be interpreted using both single and double-quotes. The lists of Escape Characters in Python are:
Page 10Sometimes we need to repeat the string in the program, and we can do this easily by using the repetition operator in Python. The repetition operator is denoted by a '*' symbol and is useful for repeating strings to a certain length. Example: str = 'Python program' print(str*3)The above lines of code will display the following outputs: Python programPython programPython programSimilarly, it is also possible to repeat any part of the string by slicing: Example: str = 'Python program' print(str[7:9]*3) #Repeats the seventh and eighth character three times prprprPage 11Spaces are also considered as a character inside a string, and sometimes unnecessary spaces in the string cause wrong results. For example, instead of typing 'Alex', a person typed his name 'Alex ' (see two spaces at the end of the string), and if we compare them using the '==' operator. Example: if 'Alex' == 'Alex ': print ("Hello Alex!") else: print ("Not found")Output: Not foundThe output of the above program will be 'not found', and this way, additional spaces may lead to wrong results. Therefore, such blank spaces should be removed from the string before being used. This is possible by using rstrip(), lstrip() and strip() methods in Python. These three functions do the same thing, but there is a slight difference between these three functions.
These three methods do not remove empty spaces between the strings and are usually used where the input is taken from the user. Example: name = ' Chris Gayle ' #remove spaces from left print (name.lstrip()) #remove spaces from right print (name.rstrip()) #remove spaces from both side print (name.strip())Output: Chris Gayle Chris Gayle Chris GaylePage 12In Python, we can check whether a string or character is a member of another string or not using "in" or "not in" operators. These two membership operators are described in the table below:
While comparing the string, these operators consider uppercase and lowercase letters or strings separately and make case sensitive comparisons. A Python Program to Know Whether a String Exists in the Main String or NotExample: str1 = input('Please enter first string: ') str2 = input('Please enter second string: ') if str2 in str1: print(str2+' found in the first string.') else: print(str2+' not found in the first string.')Output: Please enter first string: We are writing core python Please enter second string: python python found in the first string.The above program takes two inputs from the keyboard and checks whether the second string found in the first string or not. Page 13Using a 'def' statement for defining a function is the corner store of a majority of programs in Python. To group a set of statements, programmers use functions, and they can be run more than once in a program. They act like a pack of instructions that is invoked by a name. What are the Functions in Python?In simple words, Python functions are techniques used to combine a set of statements within a program. Functions also let programmers compute a result-value and give parameters that serve as function inputs that may change each time the code runs. Functions prove to be a useful tool when the operations are coded in it and can be used in a variety of scenarios. Functions are an alternative method of cutting-and-pasting codes rather than typing redundant copies of the same instruction or operation, which further reduces the future work for programmers. They are the most basic structure of a program, and so Python provides this technique for code re-use. Let's make a program using a function to make the average of any quantity of numbers. Example: def avrg(first, *rests): return (first + sum(rests)) / (1 + len(rests)) # Sample use, Putting values print (avrg(1, 2)) print (avrg(1, 2, 3)) print (avrg(1,2,3,4))Output: 1.5 2.0 2.5The keyword 'def' introduces a function definition. The statements that form the body of the function starts from the next line of function definition and needs indentation. The execution of the function introduces a new symbol table that is used for the function's local variable. In other words, all the variables that are assigned to the function store their value in the local symbol table. So global variables cannot be assigned with a value within a function; unless it is named under 'global' statement. To accept any number of keyword arguments, the arguments have to start with *. A * argument can appear only in the last position of function's argument. A fine concept of a function definition is that arguments can still appear after the * argument. Example: def g(a, *arg, b):Such arguments are known as a keyword-only argument. Python Program For Calculates The Fibonacci Series By Using Function.Example: def fibo(n): a = 0 b = 1 for i in range(0, n): temp = a a = b b = temp + b return a # Show the first 13 Fibonacci numbers. for c in range(0, 13): print(fibo(c)) #Function callOutput: 0 1 1 2 3 5 8 13 21 34 55 89 144If you compare with other programming languages, you might notice that 'fibo' is not a function, rather it's a procedure that is a function that doesn't return a value. It has to be kept in mind that every function without a return statement does return a value which is called 'none'; which usually gets suppressed by the interpreter. Calling FunctionsFunctions can be called in different ways. These are:
Functions-related Statements Or Expressions
Advantages Of Python Functions
Python Program That Returns Multiple Values From FunctionTo return multiple values, we can use normal values or return a tuple. Example: def karlos(): return 1, 2, 3 a, b, c = karlos() print (a) print (b) print (c)Output: 1 2 3Page 14Dealing with data in a structured format is quite generous, and this is possible if those data are set accordingly in a specific manner. So, Python provides these data structures named 'lists' and 'tuples' that are used to organize data in a single set. Python has six built-in sequences, and among them, the most famous is "lists and tuples". The lists are containers that hold some other objects in a given order. It usually puts into practice the sequence protocol and allows programmers to add or remove objects from that sequence. Each element of the sequence is assigned a number, i.e., the index and the first index is 0 (zero). This versatile data-type of Python is written in a sequence of the list separated by commas between expressions. Creating ListsTo build a list, just put some expressions in square brackets. The syntax is: Syntax: lst1 = [ ] # lst1 is the name of the list lst2 = [expression1 , …. , expression_N]Example: lst1 = ['computersc', 'IT', 'CSE']; lst2 = [1993, 2016]; lst3 = [2, 4, 6, "g", "k", "s"];Accessing Lists ValuesList apply the standard interface sequence in which len(L) returns the number of items present in the list, and L[i] represents the item at index i. Also L[i:j] returns new list containing objects within 'i' and 'j'. Program to Explain How to Access ListsExample: lst1 = ['computersc', 'IT', 'CSE']; lst2 = [1993, 2016]; lst3 = [2, 4, 6, "g", "k", "s"]; print ("lst1[0]", lst1[0]) print ("lst3[2:4]", lst3[2:4])Output: lst1[0] computersc lst3[2:4] [6, 'g']Updating ListsProgram to show how to add/update single or multiple elements in a list: Example: lst1 = ['computersc', 'IT', 'CSE']; print ("Second value of the list is:") print (lst1[1]) lst1[1] = 'Robotics' print ("Updated value in the second index of list is:") print (lst1[1])Output: Second value of the list is: IT Updated value in the second index of list is: RoboticsDelete Elements From ListsTo remove an element from the list, we can use the del-statement. The syntax for deleting an element from a list is: Syntax: del list_name[index_val];Page 15Tuples are immutable lists and cannot be changed in any way once it is created. Some of the characteristics features of Tuples are:
An example showing how to build tuples in Python: Example: tupl1 = ('computersc', 'IT', 'CSE'); tup2 = (6,5,4,3,2,1);Accessing Values In TuplesPrograms to show how to access values in Tuples: Example: tupl1 = ('computersc', 'IT', 'CSE'); tupl2 = (1993, 2016); tupl3 = (2, 4, 6, 8, 10, 12, 14, 16); print ("tupl1[0]", tupl1[0]) print ("tupl3[2:4]", tupl3[2:4])Output: tupl1[0] computersc tupl3[2:4] (6, 8)Updating TuplesThey are immutable, i.e., the values can't be changed directly. So we can just update by joining tuples. Let's demonstrate this with an example: Example: tupl1 = (2, 3, 4); tupl2 = ('ab', 'cd'); tupl3 = tupl1 + tupl2 print (tupl3)This code snippet will execute a combination of two tuples using the "+" operator. Output: (2, 3, 4, 'ab', 'cd')Delete Elements From TuplesTo delete a tuple, we can use the del-statement. Syntax: del tuple_name;Example: tupl3 = (2, 4, 6, 8, 10, 12, 14, 16); del tupl3;Page 16The python is an Object-oriented programming language. This means there exists a concept called 'class' that lets the programmer structure the codes of software in a fashioned way. Because of the use of classes and objects, the programming became easy to understand and code. Defining Class and ObjectA class is a technique to group functions and data members and put them in a container so that they can be accessed later by using a dot (.) operator. Objects are the basic runtime entities of object-oriented programming. It defines the instance of a class. Objects get their variables and functions from classes, and the class we will be creating are the templates made to create the object. Object-Oriented Terminologies
Program for Class in PythonExample: class karl : varabl = 'Hello' def function(self) : print ("This is a message Hello")Another program to explain functions inside a class: Example: class karl(object) : def __init__(self, x, y): self.x = x self.y = y def sample(self) : print ("This is just a sample code")In the above code, we created a class name karl using the 'class' keyword. And two functions are used namely __init__() (for setting the instance variable) & sample(). Classes are used instead of modules because programmers can take this class 'karl' & use it or modify it as many times as we want & each one won't interfere with each other. Importing a module brings the entire program into use. Creating Objects (Instance of A Class)Let's see an example to show how to create an object: Example: class student: def __init__(self, roll, name): self.r = roll self.n = name print ((self.n)) #... stud1 = student(1, "Alex") stud2 = student(2, "Karlos") print ("Data successfully stored in variables")Output: Alex Karlos Data successfully stored in variablesAccessing Object VariablesWe can access the object's variable using the dot (.) operator. Example: print object.varablAccessing AttributesObject attributes can also be accessed by using the dot operator. Example: stud1.display() stud2.display() print ("total number of students are: %d" % student.i)Use of Pre-defined FunctionsInstead of using general statements to access attributes, programmers can use the following functions:
Built-in Class AttributesAll the Python built-in class attributes can be accessed using dot (.) operator like other attributes. The built-in class attributes are:
Page 17Inheritance, abstraction, encapsulation, and polymorphism are the four fundamental concepts provided by OOP (Object Oriented Programming). Inheritance is a powerful feature of OOP that allows programmers to enable a new class to receive - or inherit all the properties & methods of existing class/classes. As we all came to know, that class is a blueprint or template of an object. Every object is built from a class, and the concept 'inheritance' is used to create a relationship between these blueprints. It is a feature of object-oriented programming which is used to define a new class with little or no modification to an existing class. The new class is called the derived class or child class, and the class from which this derived class has been inherited is the base class or parent class. The derived class is formed from a base class, plus it may include some extra additional features. This inheritance concept helps to reuse the code. In the above diagram, the features of the base class are present in the derived class, along with the features of the derived class. This base-class features can be accessible to derive class because of the concept of inheritance. The syntax of Inheritance in PythonSyntax: class BaseClass1 #Body of base class class DerivedClass(BaseClass1): #body of derived - classThree Ways of Parent-child Class InteractionWhen programmers use this type of object-oriented concepts and reuse codes, there are three ways a parent and a child class can interact with each other. These are:
Example of InheritanceExample: class Person: def __init__(self, first, last): self.firstn = first self.lastn = last def Name(self): return self.firstn + " " + self.lastn class Emp(Person): def __init__(self, first, last, staffnum): Person.__init__(self,first, last) self.staffno = staffnum def GetEmp(self): return self.Name() + ", " + self.staffno a = Person("Alex", "Karlos") b = Emp("Alex", "Karlos", "A102") print(a.Name()) print(b.GetEmp())Output: Alex Karlos Alex Karlos, A102In the above case, the object of the derived class is created and is used to invoke both of the functions of base-class as well as the derived class using a dot (.) operator. Here the result is not a part of the derived class. When the interpreter is not found in the class (derived) whose object is defined, then it continues checking that attribute in the base class. This process continues in a recursion if the base - class is itself derived from another class. Implicit InheritanceImplicit actions occur in Python Inheritance when a programmer defines a function in the parent but not in the child. This type of inheritance is shown using a simple example below: Example: class super (object) : def implicit(self) : print ("Super-Class with Implicit function") class sub(super) : pass su = super() sb = sub() su.implicit() sb.implicit()Output: Super-Class with Implicit function Super-Class with Implicit functionIn the above code, both objects of the base class, as well as derived class, can invoke the function of the base class. Also, the 'pass' statement under the 'sub' class is used to tell Python that the programmer wants an empty block, which is created under the 'sub' class, but it says there is nothing new to define in it. The above program also shows that - if we put any function in the base-class (here 'super'), then all the derived-class (here class 'sub') will also get the features automatically from the base-class, i.e., inherit all the behavior from the parent class Page 18As at the beginning of this tutorial, we have studied the types of errors that could occur in a program. Sometimes we want to catch some or all of the errors that could get generated, and as a programmer, we need to be as specific as possible. Therefore, Python allows programmers to deal with errors efficiently. Exceptions are events that are used to modify the flow of control through a program when the error occurs. Exceptions get triggered automatically on finding errors in Python. These exceptions are processed using five statements. These are:
The last was an optional extension to Python 2.6 & Python 3.0. Why are Exceptions Used?Exceptions allow us to jump out of random, illogical large chunks of codes in case of errors. Let us take a scenario that you have given a function to do a specific task. If you went there and found those things missing that are required to do that particular task, what will you do? Either you stop working or think about a solution - where to find those items to perform the task. The same thing happens here in case of Exceptions also. Exceptions allow programmers to jump an exception handler in a single step, abandoning all function calls. You can think exceptions to an optimized quality go-to statement, in which the program error that occurs at runtime gets easily managed by the exception block. When the interpreter encounters an error, it lets the execution go to the exception part to solve and continue the execution instead of stopping. While dealing with exceptions, the exception handler creates a mark & executes some code. Somewhere further within that program, the exception is raised that solves the problem & makes Python jump back to the marked location; by not throwing away/skipping any active functions that were called after the marker was left. Roles of an Exception Handler in Python
A Simple Program to Demonstrate Python Exception HandlingExample 01:(a,b) = (6,0) try:# simple use of try-except block for handling errors g = a/b except ZeroDivisionError: print ("This is a DIVIDED BY ZERO error")Output: This is a DIVIDED BY ZERO errorThe above program can also be written like this: Example 02:(a,b) = (6,0) try: g = a/b except ZeroDivisionError as s: k = s print (k) #Output will be: integer division or modulo by zeroOutput: division by zeroThe 'try - Except' Clause with No ExceptionThe structure of such type of 'except' clause having no exception is shown with an example. try: # all operations are done within this block. . . . . . . except: # this block will get executed if any exception encounters. . . . . . . else: # this block will get executed if no exception is found. . . . . . .All the exceptions get caught where there is try/except the statement of this type. Good programmers use this technique of exception to make the program fully executable. 'except' Clause with Multiple Exceptionstry: # all operations are done within this block. . . . . . . except ( Exception1 [, Exception2[,….Exception N ] ] ] ) : # this block will get executed if any exception encounters from the above lists of exceptions. . . . . . . else: # this block will get executed if no exception is found. . . . . . .The 'try - Finally' Clausetry: # all operations are done within this block. . . . . . . # if any exception encounters, this block may get skipped. finally: . . . . . . # this block will definitely be executed.Page 19All programs need the input to process and output to display data. And everything needs a file as name storage compartments on computers that are managed by OS. Though variables provide us a way to store data while the program runs, if we want out data to persist even after the termination of the program, we have to save it to a file. File and its pathThere are always two parts of a file in the computer system, the filename and its extension. Also, the files have two key properties - its name and the location or path, which specifies the location where the file exists. The filename has two parts, and they are separated by a dot (.) or period. Figure - File and its path: A built-in open method is used to create a Python file-object, which provides a connection to the file that is residing on the programmer's machine. After calling the function open, programmers can transfer strings of data to and from the external file that is residing in the machine. File Opening In Pythonopen() function is used to open a file in Python. It's mainly required two arguments, first the file name and then file opening mode. Syntax: file_object = open(filename [,mode] [,buffering])In the above syntax, the parameters used are:
Modes Of Opening File In PythonThe file can be opened in the following modes:
File Object AttributesIf an attempt to open a file fails, then open returns a false value. Otherwise, it returns a file object that provides various information related to that file. Example: # file opening example in Python fo = open("sample.txt", "wb") print ("File Name: ", fo.name) print ("Mode of Opening: ", fo.mode) print ("Is Closed: ", fo.closed) print ("Softspace flag : ", fo.softspace)Output: File Name: sample.txt Mode of Opening: wb Is Closed: False Softspace flag: 0File Reading In PythonFor reading and writing text data, different text-encoding schemes are used, such as ASCII (American Standard Code for Information Interchange), UTF-8 (Unicode Transformation Format), UTF-16. Once a file is opened using an open() method, then it can be read by a method called read(). Example: # read the entire file as one string with open('filename.txt') as f: data = f.read() # Iterate over the lines of the File with open('filename.txt') as f: for line in f : print(line, end=' ') # process the linesFile Writing In PythonSimilarly, for writing data to files, we have to use open() with 'wt' mode, clearing and overwriting the previous content. Also, we have to use the write() function to write into a file. Example: # Write text data to a file with open('filename.txt' , 'wt') as f: f.write ('hi there, this is a first line of file.\n') f.write ('and another line.\n')Output: hi there, this is a first line of file. and another line.By default, in Python - using the system default text, encoding files are read/written. Though Python can understand several hundred text-encodings but the most common encoding techniques used are ASCII, Latin-1, UTF-8, UTF-16, etc. The use of 'with' statement in the example establishes a context in which the file will be used. As the control leaves the 'with' block, the file gets closed automatically. Writing A File That Does Not ExistThe problem can be easily solved by using another mode - technique, i.e., the 'x' mode to open a file instead of 'w' mode. Let's see two examples to differentiate between them. Example: with open('filename' , 'wt') as f: f.write ('Hello, This is sample content.\n') # This will create an error that the file 'filename' doesn't exist. with open ('filename.txt' , 'xt') as f: f.write ('Hello, This is sample content.\n')In binary mode, we should use 'xb' instead of 'xt'. Closing A File In PythonIn Python, it is not system critical to close all your files after using them, because the file will auto close after Python code finishes execution. You can close a file by using the close() method. Syntax: file_object.close();Example: try: # Open a file fo = open("sample.txt", "wb") # perform file operations finally: # Close opened file fo.close()Page 20Here, we will learn about dictionaries, the operators, and methods used on dictionaries. It is nearly inconceivable to work with python program or scripts, without lists and dictionaries. Python dictionaries can be changed easily at runtime. Dictionary is like a list but in a general form. It can think like this; a dictionary is a mapping between a set of indexes or keys with a set of values, where each key maps to a value. A combination of a key and its value is called a key-value pair or item. Suppose we take an example and build a dictionary that maps words from English to French. So the keys and their values will be all strings. In the Python dictionary, each key is separated by a colon (:) from its values. Commas separate all the items, and the whole dictionary is enclosed within '{' and '}'. In the dictionary, all the keys should have to be unique with data type as strings, tuples, or numbers, and the values can be of any of these three types. Define a Dictionary In PythonExample: dicto = {'Bookname' : 'Python', 'Price' : 210}Accessing Dictionary ValuesDictionaries' values can be accessed by using the square braces, i.e. [ ], along with the key name to obtain the value. This are multiple item declaration procedures used to declare keys along with their values in Python's dictionary. Example: dicto = {'Bookname' : 'Python', 'Price' : 210} print (dicto['Bookname']) print (dicto['Price'])When the above code gets executed, the outcome will be: Output: Python 260Creating a New Dictionary in PythonExample: new_dict = dict() print (new_dict)or write new_dict = {} print (new_dict)Output: {}The function 'dict' creates a new dictionary with no items within it. This is because 'dict' is the name of a built-in function, and programmers should avoid using it as a variable name. Furthermore the curly braces { & } together represents an empty dictionary. So to use the dictionary to add items, Python programmers use square braces such as: Example: new_dict = dict() new_dict['First'] = 10; new_dict['Second'] = 20;For mapping a single item of a dictionary, programmers can use this procedure also. This is a one-by-one procedure of declaring items. The line creates an item that maps from key 'first' to the value 10. Similarly, in the second case also. Dictionary as Set of CounterLet us consider a situation where programmers are given, and they have to count how many times each letter appears. To do this, the techniques are:
It is based on the programmer what and how he/she wants to implement things into programming. An implementation is a method of doing or performing a computation based on your conception. In the above scenario, there is an advantage while using dictionaries - that we do not have to think or know ahead of which letter appears in the string and have to allot space and room for those letters. Updating Dictionary in PythonProgrammers can update or modify the existing dictionary by simply adding a new entry or a key-value pair or by deleting an item or entry. The code describes it below: Example: dicto = {'Bookname' : 'Python', 'Price' : 210} #Adding new entries dicto ['Author'] = 'TutorialsCloud' ; dicto ['Discount']= '10 Percent'; #Updating an Entry dicto ['Price'] = 200;Deleting Elements From DictionaryDeleting elements from a dictionary can be done either removing individual elements or use clear() to clear the entire dictionary's content. An example is shown below: Example: dicto = {'Bookname' : 'Python', 'Price' : 210, 'Author': 'TutorialsCloud'} del dicto['Price']; # It deletes only the key with the name 'Price' dicto.clear(); # The above code removes all entries in dictionary & makes the dictionary empty del dicto # The above code Deletes the entire dictionaryPage 21There are various ways Python supplies date and time feature to add to the program. Python's Time and calendar module help in tracking date and time. Also, the 'DateTime' provides classes for controlling date and time in both simple and complex ways. The differences between 'naive' and 'aware' objects are:
Defining TickAs we all can make an idea that time intervals have to be represented in floating-point numbers. Tick signifies the floating-point numbers in units of seconds in Python. Particular instants of time are represented in seconds from 12:00 am, 1st of January, of the year 1990. A popular module name 'time' is available, which provides functions that let's programmer work with the time and made conversion between time-representation possible. The pre-defined function time.time() is used to return the current time of the system. The daytime module exports the constants listed below: Two programs are shown showing the use of two different modules: Example: import time; ticktock = time.time(); print("Number of ticks:", ticktock)Output: Number of ticks: 1465927104.951356Another program showing datetime module: Example: from datetime import datetime presentime = datetime.now() print(" NOW THE TIME IS:", presentime) print("Todays Date is:", presentime.strftime('%Y-%m-%d') ) print("Year is:", presentime.year) print("MOnth is:", presentime.month) print("Day is:", presentime.day)Output: NOW THE TIME IS: 2016-06-14 18:01:25.831269 Todays Date is: 2016-06-14 Year is: 2016 MOnth is: 6 Day is: 14Timetuple In PythonPython usually handles time's function as a tuple with nine numbers starting from zero (0) to eight (8).
Timedelta ObjectIt is used to represent duration, i.e., the difference between two dates and or times. For invoking this, the syntax is: Syntax: datetime.timedelta([days, [,seconds [,microseconds [,milliseconds [, minutes [,hours [,weeks]]]]]])In the above scenario, all arguments are optional, and their default value is zero (0). Program To Get Current TimeExample: import time; curtime = time.localtime(time.time()) print("Current Time is:", curtime)Output: Current Time is: time.struct_time(tm_year=2016, tm_mon=6, tm_mday=14, tm_hour=0, tm_min=4, tm_sec=49, tm_wday=1, tm_yday=166, tm_isdst=0)Calendar Of A MonthThis facility is provided by the "calendar" module, which offers a wide range of methods to deal with monthly calendars. A simple program showing how to use: Example: import calendar calndr = calendar.month(2016, 6) print("The calendar for the month June of Year 2016 is:") print (calndr)Output: The calendar for the month June of Year 2016 is: June 2016 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30Page 22Here we will discuss the highest level program organization unit, which helps programmers to pack and organize program code and data for reusable purposes. What is Modular Programming?A module provides a simple way to organize program components into a system; grouping similar forms of code into a module makes code easier to understand. It is also referred to as a program object that binds data and can be used as a reference. In other words, it is a file that contains a Python program. Programmers use the 'import' statement to get access to the names in a module's global scope. We will learn about it a bit later. Python's module ultimately allows programmers to link individual files to a larger program system. Roles of Python Module
import StatementProgrammers can use any Python source code (i.e., .py files) as a module by implementing an 'import' statement in another Python program or Python file. Let take a scenario, a file name 'g.py' be chosen as the top-level file; it will be a simple text file of statements and will be executed from top to bottom as the interpreters do. The modules are - 'a.py' and 'b.py'. So to use the codes of a.py and b.py in the g.py program, we have to first define the codes as functions in both modules & then import the two Python codes using 'import' statement. The code will be: def karl(text) #a.py File print(text, 'karl')Now, the programmer wants to use the codes of a.py into the g.py file. Example: import a #g.py file a.karl ('myself') #Prints "myself karl"The figure below shows its working: So the syntax for import statement is: Example: import module_name1 [, module_name2 [module_nameN]]The module can be imported only when the interpreter encounters an import statement & if the module is present in the search path, i.e., the directories that the interpreter searches before importing module. Standard Library Modules in PythonPython comes with a vast collection of regularly used utility modules called standard library which contains a collection of over two-hundred modules along with platform-independent support system for common programming tasks such as network, internet scripting, text pattern matching, object persistence, GUI (Graphical User Interface) programs and much more. Though these tools are not the part of Python programming language, programmers can use them by importing the appropriate modules based on the needs. Since they are standard library modules, therefore they will be available & will work portably on most platforms on which the Python will be run. How does import Work?Because imports are an essential part of the Python program structure, let's go to the inside of its working technique in brief. From the C-programmers viewpoint - import operation is like #include of C Language, but in reality, 'import' is not the just textual insertion of one file into another. These are runtime operational statements that perform three distinct steps. These are:
It has to be kept in mind that the above three steps are performed only the first time the module is imported during program execution. If the program is run later importing the previous modules, bypass all these three steps and simply fetch the already loaded module-object in memory. Page 23Regular expressions are a very useful technique for extracting information from text such as code, spreadsheets, documents, or log-files. The first thing to keep in mind while implementing regular expression is that everything essentially needs to be a character, and programmers write patterns to match a specific sequence of characters/strings. Defining Regular ExpressionRegular expressions are characters in particular order that help programmers find other sequences of characters or strings or set of strings using specific syntax held in a pattern. Python supports regular expressions through the standard Python library's' which is packed with every Python installation. Here, we will be learning about the vital functions that are used to handle regular expressions. Many characters are having special meaning when they are used as regular expressions. It is mostly used in UNIX. Raw Strings in PythonIt is recommended to use raw-strings instead of regular strings. When programmers write regular expressions in Python, they begin raw strings with a special prefix 'r' and backslashes and special meta-characters in the string, that allows us to pass through them to regular-expression-engine directly. match FunctionThis method is used to test whether a regular expression matches a specific string in Python. The re.match(). The function returns 'none' of the pattern doesn't match or includes additional information about which part of the string the match was found. Syntax: re.match (pattern, string, flags=0)Here, all the parts are explained below:
Example: import re #simple structure of re.match() matchObject = re.match(pattern, input_str, flags=0)A Program by USING re.match: Example: import re list = [ "mouse", "cat", "dog", "no-match"] # Loop starts here for elements in list: m = re.match("(d\w+) \W(d/w+)" , element) # Check for matching if m: print (m . groups ( ))In the above example, the pattern uses meta-character to describe what strings it can match. Here '\w' means word-character & + (plus) symbol denotes one-or-more. Most of the regular expressions' control technique comes to a role when "patterns" are used. search FunctionIt works differently than that of a match. Though both of them use pattern, 'search' attempts this at all possible starting points in the string. It scans through the input string and tries to match at any location. Syntax: re.search( pattern, strings, flags=0)Program to show how it is used: import re value = "cyberdyne" g = re.search("(dy.*)", value) if g: print("search: ", g.group(1)) s = re.match("(vi.*)", value) if s: print("match:", m.group(1))Output: dynesplit FunctionThe re.split() accepts a pattern that specifies the delimiter. Using this, we can match the pattern and separate text data. 'split()" is also available directly on a string & handles no regular expression. Program to show how to use split(): Example: import re value = "two 2 four 4 six 6" #separate those non-digit characters res = re.split ("\D+" , value) # print the result for elements in res : print (elements)Output: 2 4 6In the above program, \D+ represents one or more non-digit characters. Page 24Python plays an essential role in network programming. The standard library of Python has full support for network protocols, encoding, and decoding of data and other networking concepts, and it is simpler to write network programs in Python than that of C++. Here, we will learn about the essence of network programming concerning Python. But for this, the programmer must have basic knowledge of:
Python Network ServicesThere are two levels of network service access in Python. These are:
In the first case, programmers can use and access the basic socket support for the operating system using Python's libraries, and programmers can implement both connection-less and connection-oriented protocols for programming. Application-level network protocols can also be accessed using high-level access provided by Python libraries. These protocols are HTTP, FTP, etc. Defining SocketA socket is the end-point in a flow of communication between two programs or communication channels operating over a network. They are created using a set of programming requests called socket API (Application Programming Interface). Python's socket library offers classes for handling common transports as a generic interface. Sockets use protocols for determining the connection type for port-to-port communication between client and server machines. The protocols are used for:
Socket ProgramPython has a socket method that let programmers' set-up different types of socket virtually. The syntax for the socket method is: Syntax: g = socket.socket (socket_family, type_of_socket, protocol=value)For example, if we want to establish a TCP socket, we can write the following code snippet: Example: # imports everything from 'socket' from socket import * # use socket.socket() - function tcp1=socket.socket(socket.AF_INET, socket.SOCK_STREAM)Here's another example to establish a UDP socket. The code is: udp1=socket.socket (socket.AF_INET, socket.SOCK_DGRAM)After you defined the socket, you can use several methods to manage the connections. Some of the important server socket methods are:
A Simple Network Program Using PythonExample: import socket T_PORT = 60 TCP_IP = '127.0.0.1' BUF_SIZE = 30 # create a socket object name 'k' k = socket.socket (socket.AF_INET, socket.SOCK_STREAM) k.bind((TCP_IP, T_PORT)) k.listen(1) con, addr = k.accept() print ('Connection Address is: ' , addr) while True : data = con.recv(BUF_SIZE) if not data: break print ("Received data", data) con.send(data) con.close()Save the file with filename - tcpserver.py It will open a web server at port 60. In the above program, everything you write in the client goes to the server. Now a simple Python client script: import socket T_PORT = 5006 TCP_IP = '127.0.0.1' BUF_SIZE = 1024 MSG = "Hello karl" # create a socket object name 'k' k = socket.socket (socket.AF_INET, socket.SOCK_STREAM) k.connect((TCP_IP, T_PORT)) k.send(MSG) data = k.recv(BUF_SIZE) k.closeSending messages back and forth using different basic protocols is simple and straightforward. It shows that programming takes a significant role n client-server architecture where the client makes data request to a server, and the server replies to those machines. Page 25When programmers run a simple program of Python, execution starts at the first line and proceeds line-by-line. Also, functions and loops may be the reason for program execution to jump, but it is relatively easy to see its working procedures and which line will be next executed. Programmers can put their fingers and can trace the lines of codes that will be executed; this is called single-threaded programming. However, in the case of multi-threaded programming, it's like putting a second finger on your program. Both the fingers move the same way and will be executed simultaneously. What are Threads?It is the execution of a tiny sequence of program instruction that can be managed independently and is a distinctive part of the operating system. Modern OS manages multiple programs using a time-sharing technique. In Python, there are two different kinds of thread. These are:
Why Use ThreadThread plays a significant role in application programming. All the GUI programs and web servers are threaded together. The main reasons for using threads are:
Thread Modules in PythonThere are two ways of accessing Python threads. These are by using: It is to be noted that the 'tread' module has been considered as of lesser use, and hence users get to use the 'threading' module instead. Another thing has to keep in mind that the module 'thread' treats the thread as a function, whereas the 'threading' is implemented as an object. Benefits of Threading
In a thread, there are three different parts. It has the beginning, an execution part, and a conclusion. It also has an instruction pointer that points to where the thread or process is currently running, and hence the thread can run several different program blocks concurrently. Using a New ThreadIt is achievable to execute functions in a separate thread using a module Thread. For doing this, programmers can use the function - thread.start_new_thread(). Syntax: thread.start_new_thread(function, args[, kwargs])Here, the first part is a method as told before & this method is a faster and more efficient way to create new threads. As the child thread starts, the function passes a list of args. The thread gets terminated when the function returns a value. The 'args' in the above syntax is a tuple of arguments. Program of Threading Using PythonExample: import threading def coder(number): print ('Coders: %s' , %number) return threads = [] for k in range(5): t = threading.Thread(target=coder, args=(k,)) threads.append(t) t.start()Output: Coders: 0 Coders: 1 Coders: 2 Coders: 3 Coders: 4Methods of Thread ClassThe threading module, as described earlier, has a Thread class that is used for implementing threads, and that class also contains some predefined methods used by programmers in multi-threaded programming. These are:
Page 26Until now, we had done a lot with programming that is not related to the web or the network. Now it's time for CGI. As the name suggests, CGI means the "Common Gateway Interface" for everything. CGI is one of the essential parts of HTTP (Hyper-Text Transfer Protocol). CGI is a set of standards that defines a standard way of passing information or web-user requests to an application program and getting data back to forward it to users. It is the exchange of information between the web server and a custom script. When the users requested the web-page, the server sends the requested web-page. The web server usually passes the information to all application programs that process data and sends back an acknowledged message; this technique of passing data back-and-forth between server and application is the Common Gateway Interface. The current version of CGI is CGI/1.1 & CGI/1.2 is under process. BrowsingWhat happens when a user clicks a hyperlink to browse a particular web-page or URL (Uniform Resource Locator). The steps are:
It may become possible to set-up an HTTP server because when a certain directory is requested, that file is not sent back; instead, it is executed as a program, and that program's output is displayed back to your browser. Configuring CGIThe steps are:
The architecture of CHI is shown below: Python CGI Program StructureThe output of the Python CGI script must consist of two sections separated by a blank line. The first part contains the number of headers that describe the client what kind of data is following. Python code header section looks something like this: Example: print ("Content-Type : text/html") # then comes the rest hyper-text documents print ("<html>") print ("<head>") print ("<title>My First CGI-Program </title>") print ("<head>") print ("<body>") print ("<h3>This is HTML's Body section </h3>") print ("</body>") print ("</html>")Save this file as CGI.py. When you open that saved file, the output becomes: Output: This is HTML's Body sectionThis is a simple Python script that writes its output to STDOUT file, i.e., on-screen. Use of CGI ModuleIf programmers write CGI scripts in Python, they can add these lines: import cgitb cgitb.enable()The above code triggers a special exception handler that will display a detailed report in the web-browser in case of any error occurrence. HTTP HeaderFew are the important lists of HTTP headers frequently used in CGI programs. These are:
CGI Environment Variables
|