What is -1 in python

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.

Operator Description Example
+ Addition: This Operator is used to add Two numbers in Python 10+15
Subtraction: This Operator is used to subtract the second operand from first. 20-10
* Multiply: This Operator is used to multiply two operands. 10*2
/ Division: This Operator is used to divide the first operand by second. 10/2
% Modulus: This Operator returns the remainder after dividing the first operand by the second operand. 10%2
// Floor Division: It will return non-decimal value after division e.g. result of 5//2 = 2 5//2
** Exponent: This operator is used to the first operand raised to the power of the second operand 10**2

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.

Operator Description Example
is This operator will return true if both objects are on the same memory location. x is y
is not This operator will return true if both objects are not on the same memory location. x is not y

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.

Operator Description Example
in Return true if the given sequence is present in the given object. x in y
not in Returns true if a given sequence is not present in Object. x not in y

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.

Operator Description Example
> Greater than: This Operator will return true if left side operand will greater than operand at the right side. 20>10
< Less Than: This Operator will return true if left side operand will be smaller then operand at the right side. 10>20
>= Greater than equal to: This operator will return to if operand at the left side will greater or equal to operand at the right side. 20>=10
<= Less than equal to: This operator will return to if operand at the left side will small or equal to operand at the right side. 10<=20
== Equal to: This Operator will return true if operands of both sides will be equal. 10==10
!= Not Equal: This Operator will return true if operands at both sides will not equal. 10!=20

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.

Operator Description Example
and Logical and: This Operator returns true if both operands will be true x and y
or Logical or: This Operator returns true if any one or both operand will be true x or y
not Logical not: This Operator return compliment result of the given operand x or y

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.

Operator Description Example
= Equal to an operator to assign value to a variable. x = 5
+= Plus Equal to an operator to assign value to the variable after adding given value in a previous value of a variable. x += 5
-= Minus Equal to an operator to assign value to the variable after subtracting given value from the previous value of a variable. x -= 5
*= Multiply Equal to an operator to assign value to the variable after Multiplying given value with the previous value of the variable. x *= 5
/= Divide Equal to an operator to assign value to the variable after Dividing given value from the previous value of the variable. x /= 5
%= Modulus Equal to an operator to assign Remainder to the variable after Dividing given value from the previous value of the variable. x %= 5
//= Divide(floor) Equal to an operator to assign a value(floor) to the variable after Dividing given value from the previous value of the variable. x //= 5
**= Exponent Equal to an operator to assign exponent(square) to the variable after calculating. x **= 5
&= Bitwise AND Equal to an operator to assign value to the variable after performing bitwise operator. x &= 5
|= Bitwise OR Equal to an operator to assign value to the variable after performing Bitwise OR operator. x |= 5
^= Bitwise XOR Equal to an operator to assign value to the variable after performing XOR operator. x ^= 5
>>= Bitwise right shift Equal to operator to assign value to the variable after performing bitwise right shift. x >>= 5
<<= Bitwise Left shift Equal to an operator to assign value to the variable after performing Bitwise left shift. x <<= 5

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..

What is -1 in python
What is -1 in python
What is -1 in python

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.

What is -1 in python

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 Operands

Python 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 Operators

Python programming language is rich with built-in operators.

  • Arithmetic Operators
  • Assignment Operators
  • Comparison (Relational) Operators
  • Logical Operators
  • Identity Operators
  • Bitwise Operators
  • Membership Operators

Arithmetic Operators

Python Arithmetic Operators
Symbol Operator Name Description
+ Addition Adds the values on either side of the operator and calculate a result.
- Subtraction Subtracts values of right side operand from left side operand.
* Multiplication Multiplies the values on both sides of the operator.
/ Division Divides left side operand with right side operand.
% Modulus It returns the remainder by dividing the left side operand with right side operand
** Exponent Calculates the exponential power
// Floor Division Here the result is the quotient in which the digits after decimal points are not taken into account.

Assignment Operators

Python Assignment Operators
Symbol Operator Name Description
= Equal Assigns the values of the right side operand to the left side operand.
+= Add AND Adds right-side operand value to the left side operand value and assigns the results to the left operand.
-= Subtract AND Subtracts right-side operand value to the left side operand value and assigns the results to the left operand.
*= Multiply AND Similarly does their respective operations and assigns the operator value to the left operand.
/= Division AND
%= Modulus AND
**= Exponent AND
//= Floor Division AND

Comparison (Relational) Operators

Python Comparison Operators
Symbol Operator Name Description
== Double Equal If the two value of its operands are equal, then the condition becomes true, otherwise false
!= or <> Not Equal To If two operand's values are not equal, then the condition becomes true. Both the operators define the same meaning and function
> Greater Than If the value of the left-hand operand is greater than the value of right-hand operand, the condition becomes true.
< Less Than If the value of the left-hand operand is less than the value of the right operand, then the condition becomes true.
<= Less Than Equal To If the value of the left-hand operand is less than or equal to the value of right-hand operand, the condition becomes true.
>= Greater Than Equal To If the value of the left-hand operand is greater than or equal to the value of right-hand operand, the condition becomes true.

Logical Operators

Python Logical Operators
Symbol Operator Name Description
or Logical OR If any of the two operands are non-zero, then the condition is true.
and Logical AND If both the operands are true, then the condition is true.
not Logical NOT It is used to reverse the logical state of its operand.

Identity Operators

For comparing memory locations of two objects, identity operators are used.

There are two types of identity operators. These are:

Python Identity Operators
Symbol Operator Name Description
is is The result becomes true if values on either side of the operator point to the same object and False otherwise.
is not is not The result becomes False if the variables on either side of the operator point to the same object

Bitwise Operators

These operators are used to manipulate with bits, & performs bit-by-bit operations.

There are six types of bitwise operators supported by Python. These are:

Python Bitwise Operators
Symbol Operator Name Description
& Binary AND This operator copies the bit to the result if it exists in both operands.
| Binary OR This operator copies the bit if it exists in either of the operands.
^ Binary XOR This operator copies the bit if it is set in one operand but not both.
~ Binary 1s Complement This is a unary operator and has the ability of 'flipping' bits.
<< Binary Left Shift The left operands value is moved left by the number of bits specified by the right operand using this operator.
>> Binary Right Shift The left operands value is moved right by the number of bits specified by the right operand using this operator.

Membership Operators

Python Membership Operators
Symbol Operator Name Description
in in The result of this operation becomes True if it finds a value in a specified sequence & False otherwise.
not in not in result of this operation becomes True if it doesn't find a value in a specified sequence and False otherwise.
What is -1 in python
report this ad

Page 2

Python 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:

  • The possible values for that type.
  • The operations that can be done with that values.
  • Conveys the meaning of data.
  • The way values of that type can be stored.

Data Types available in Python

Everything 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:

  • Numbers: An are integers (such as 1, 2, 3…), floats (such as 2.6, 4.8, etc.), fractions (such as ½. ¾, etc.), or even complex numbers.
    • int (signed integer)
    • float
    • long
    • complex
  • Sequences:
    • Strings: Sequence of Unicode characters, like an HTML document.
    • Bytes/Byte array: Any type of file.
    • Lists: An ordered sequence of values.
    • Tuples: An ordered, immutable sequence of values.
  • Boolean: Holds either true or false values.
  • Sets: An unordered container of values.
  • Dictionaries: A key-paired values set in an unordered way.

Because Python is a pure object-oriented programming language,  so other data types are also available.

  • Module
  • Function
  • Class
  • Method
  • File
What is -1 in python
report this ad


Page 3

Before 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.

What is -1 in python

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;

What is -1 in python

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 = 1

Here, 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.

What is -1 in python

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.

What is -1 in python

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.

What is -1 in python
report this ad


Page 4

Variables 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:

Value Data Type
5, 9 integers
Hello, Ok string (a combination of letters)

Python Variable Declaration

In 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 Variables

Python 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.5

In 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.
Another variable name 'width' is assigned with floating type value. Then both the values are printed or displayed using the 'print' statement.

Commons Rules for Naming Variables in Python

Python has some variable related rules that must be followed:

  • Variable names are case-sensitive.
  • Variable names must begin with a letter or underscore.
  • A variable name can only contain alphanumeric characters and underscore, such as (a-z, A-Z, 0-9, and _ ).
  • A variable name can not contents space.
  • Reserved words cannot be used as a variable name.

Python Variable Deletion

Python 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>
What is -1 in python
report this ad


Page 5

As 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.2

These 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 Types

Python provides four distinctive numerical types. These are:

  • signed int: include the range of both positive as well as negative numbers along with whole numbers without the decimal point.
  • long int: a special type of integer is having an unlimited size and is written like integer value before the letter L (either uppercase or lowercase).
  • float (real values): They are used with a decimal point to represent real numbers, and that decimal point (dot) is used to divide the integer and the fraction.
  • complex: are complex numbers that take the structure a+bJ where a and b are floating-point numbers and that 'J' represent the square root of -1 (imaginary number).

Type Conversion (Casting)

Python has the capability and feature to convert within an expression containing the mixture of different types of values internally.

  • int(v): is used to convert any value 'v' to a plain integer
  • long(v): is used to convert a value 'v' to a long integer
  • float(v): is used to convert a value 'v' to floating-point value
  • complex(v): is used convert a value 'v' to the complex number having real part 'v' and imaginary part as 0
  • complex(u,v): is used convert values u and v to the complex number with real part 'u' and imaginary part 'v'

Example:

x = 10.5 y = 5 #without type cast print (x + y) #after type cast print (int(x) + y)

Output:

15.5 15

The above example shows how float converted to an integer.

What is -1 in python
report this ad


Page 6

Decisions 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:

Python Conditional Statements
Statement Description
if Statements It consists of a Boolean expression which results are either TRUE or FALSE, followed by one or more statements.
if else Statements It also contains a Boolean expression. The if the statement is followed by an optional else statement & if the expression results in FALSE, then else statement gets executed. It is also called alternative execution in which there are two possibilities of the condition determined in which any one of them will get executed.
Nested Statements We can implement if statement and or if-else statement inside another if or if - else statement. Here more than one if conditions are applied & there can be more than one if within elif.

if Statement

The decision-making structures can be recognized and understood using flowcharts.

Figure - If condition Flowchart:

What is -1 in python

Syntax:

if expression: #execute your code

Example:

a = 15 if a > 10: print("a is greater")

Output:

a is greater

if else Statements

Figure - If else condition Flowchart:

What is -1 in python

Syntax:

if expression: #execute your code else: #execute your code

Example:

a = 15 b = 20 if a > b: print("a is greater") else: print("b is greater")

Output:

b is greater

elif Statements

elif - 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:

What is -1 in python

Syntax:

if expression: #execute your code elif expression: #execute your code else: #execute your code

Example:

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 equal

We can write if statements in both ways, within parenthesis or without parenthesis/ brackets, i.e. ( and ).

Single Statement Condition

If 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")
What is -1 in python
report this ad


Page 7

In 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 Python

Python provides three types of looping techniques:

Python Loops

Loop Description
for Loop This is traditionally used when programmers had a piece of code and wanted to repeat that 'n' number of times.
while Loop The loop gets repeated until the specific Boolean condition is met.
Nested Loops Programmers can use one loop inside another; i.e., they can use for loop inside while or vice - versa or for loop inside for loop or while inside while.

for Loop

The graphical representation of the logic behind for looping is shown below:

Figure - for loop Flowchart:

What is -1 in python

Syntax:

for iterating_var in sequence: #execute your code

Example 01:
for x in range (0,3) : print ('Loop execution %d' % (x))

Output:

Loop execution 0 Loop execution 1 Loop execution 2

Example 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 : d

while Loop

The graphical representation of the logic behind while looping is shown below:

Figure - while loop Flowchart:

What is -1 in python

Syntax:

while expression: #execute your code

Example:

#initialize count variable to 1 count =1 while count < 6 : print (count) count+=1 #the above line means count = count + 1

Output:

1 2 3 4 5

Nested Loops

Syntax:

for iterating_var in sequence: for iterating_var in sequence: #execute your code #execute your code

Example:

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 = 10

Loop Control Statements

These statements are used to change execution from its normal sequence.

Python supports three types of loop control statements:

Python Loop Control Statements

Control Statements Description
Break statement It is used to exit a while loop or a for a loop. It terminates the looping & transfers execution to the statement next to the loop.
Continue statement It causes the looping to skip the rest part of its body & start re-testing its condition.
Pass statement It is used in Python to when a statement is required syntactically, and the programmer does not want to execute any code block or command.

Break statement

Syntax:

break

Example:

count = 0 while count <= 100: print (count) count += 1 if count >= 3: break

Output:

0 1 2

Continue statement

Syntax:

continue

Example:

for x in range(10): #check whether x is even if x % 2 == 0: continue print (x)

Output:

1 3 5 7 9

Pass Statement

Syntax:

pass

Example:

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 : d
What is -1 in python
report this ad


Page 8

In 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 Statement

A 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: break

Program Output:

0 1 2

In 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 Statement

The 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 4

In 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.

What is -1 in python
report this ad


Page 9

A 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 Values

Characters 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 Chapter

If 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: rin

Updating a String Value or Variable

Reassigning 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 PyPython

Escape Characters

These 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:

  • \a: alert
  • \b: backspace
  • \cx: Control X
  • \e: escape
  • \f: Form feed
  • \n: Newline or next line
  • \r: carriage return
  • \s: space
  • \t: tab
  • \v: Vertical Tab
What is -1 in python
report this ad


Page 10

Sometimes 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 program

Similarly, 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 prprpr
What is -1 in python
report this ad


Page 11

Spaces 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 found

The 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.

Function Description
rstrip() rstrip() method removes whitespace at the end of a string.
lstrip() lstrip() method removes whitespace at the beginning of a string.
strip() strip() method removes whitespace at the beginning and end (both sides) of a string.

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 Gayle
What is -1 in python
report this ad


Page 12

In 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:

Symbol Operator Name Description
in in The result of this operation becomes True if it finds a value in a specified sequence and False otherwise.
not in not in The result of this operation becomes True if it doesn't find a value in a specified sequence and False otherwise.

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 Not

Example:

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.

What is -1 in python
report this ad


Page 13

Using 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.5
The 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 call

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144

If 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 Functions

Functions can be called in different ways.

These are:

  • Providing the mandatory argument only
  • Providing one of the optional argument
  • By giving all the arguments

  • Call Expression: myfun ('karl', 'os', *rest)
  • def : def display(message):
    print ('Hi' +  message)
  • return : def sum(a, b=2)
    return a+b
  • global : x = 'hello' def printer():

    global x; x='hi'

  • nonlocal : def outer(): a = 'old' def inner():

    nonlocal a; a = 'new'

  • yield : def sq(k)
    for I in range(k): yield i**2

Advantages Of Python Functions

  • Maximizing code reusability
  • Minimizing redundancy
  • Procedural decomposition
  • Make programs simpler to read and understand

Python Program That Returns Multiple Values From Function

To 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 3
What is -1 in python
report this ad


Page 14

Dealing 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 Lists

To 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 Values

List 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 Lists

Example:

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 Lists

Program 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: Robotics

Delete Elements From Lists

To 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];
What is -1 in python
report this ad


Page 15

Tuples are immutable lists and cannot be changed in any way once it is created.

Some of the characteristics features of Tuples are:

  • Tuples are defined in the same way as lists.
  • They are enclosed within parenthesis and not within square braces.
  • Elements of the tuple must have a defined order.
  • Negative indices are counted from the end of the tuple, just like lists.
  • Tuple also has the same structure where commas separate the values.

An example showing how to build tuples in Python:

Example:

tupl1 = ('computersc', 'IT', 'CSE'); tup2 = (6,5,4,3,2,1);

Accessing Values In Tuples

Programs 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 Tuples

They 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 Tuples

To 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;
What is -1 in python
report this ad


Page 16

The 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 Object

A 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

  • class: Classes are a user-defined data type that is used to encapsulate data and associated functions together. It also helps in binding data together into a single unit.
  • Data Member: A variable or memory location name that holds value to does a specific task within a program.
  • Member Function: They are the functions, usually a block of a code snippet that is written to re-use it.
  • Instance variable: A variable that is defined inside a method of a class.
  • Function Overloading: This technique is used to assign multiple tasks to a single function, and the tasks are performed based on the number of arguments or the type of argument the function has.
  • Operator Overloading: It is the technique of assigning multiple functions/tasks to a particular operator.
  • Inheritance: It is the process of acquiring the properties of one class to another, i.e., one class can acquire the properties of another.
  • Instantiation: It is the technique of creating an instance of a class.

Program for Class in Python

Example:

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 variables

Accessing Object Variables

We can access the object's variable using the dot (.) operator.
The syntax is:

my object_name.variable_name

Example:

print object.varabl

Accessing Attributes

Object 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 Functions

Instead of using general statements to access attributes, programmers can use the following functions:

  • getattr( obj, name [,default] ) : used to access object's attribute.
  • hasattr( object, name): used for checking whether the attribute exists or not.
  • setattr( obj, name, value ) : set or create an attribute, if it doesn't exist.
  • delattr( obj, name ) : used to delete an attribute.

Built-in Class Attributes

All the Python built-in class attributes can be accessed using dot (.) operator like other attributes.

The built-in class attributes are:

  • __dict__: This attribute is a dictionary that contains the class's -namespace.
  • __doc__: Used for class documentation string.
  • __name__: used as class-name.
  • __module__: used to define the module name for the class in which it is defined. In interactive mode, it is __main__.
  • __bases__: An empty tuple containing the base-class.
What is -1 in python
report this ad


Page 17

Inheritance, 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.

What is -1 in python

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 Python

Syntax:

class BaseClass1 #Body of base class class DerivedClass(BaseClass1): #body of derived - class

Three Ways of Parent-child Class Interaction

When 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:

  • Anything did to the child class also results in action on the parent class.
  • Anything done on the child-class alters the action done in the parent class.

Example of Inheritance

Example:

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, A102

In 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 Inheritance

Implicit 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 function

In 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

What is -1 in python
report this ad


Page 18

As 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:

  1. try/except: catch the error and recover from exceptions hoist by programmers or Python itself.
  2. try/finally: Whether exception occurs or not, it automatically performs the clean-up action.
  3. assert: triggers an exception conditionally in the code.
  4. raise: manually triggers an exception in the code.
  5. with/as: implement context managers in older versions of Python such as - Python 2.6 & Python 3.0.

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

  • Error handling: The exceptions get raised whenever Python detects an error in a program at runtime. As a programmer, if you don't want the default behavior, then code a 'try' statement to catch and recover the program from an exception. Python will jump to the 'try' handler when the program detects an error; the execution will be resumed.
  • Event Notification: Exceptions are also used to signal suitable conditions & then passing result flags around a program and text them explicitly.
  • Terminate Execution: There may arise some problems or errors in programs that it needs a termination. So try/finally is used that guarantees that closing-time operation will be performed. The 'with' statement offers an alternative for objects that support it.
  • Exotic flow of Control: Programmers can also use exceptions as a basis for implementing unusual control flow. Since there is no 'go to' statement in Python so that exceptions can help in this respect.

A Simple Program to Demonstrate Python Exception Handling

Example 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 error

The 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 zero

Output:

division by zero

The 'try - Except' Clause with No Exception

The 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 Exceptions

try: # 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' Clause

try: # all operations are done within this block. . . . . . . # if any exception encounters, this block may get skipped. finally: . . . . . . # this block will definitely be executed.
What is -1 in python
report this ad

Page 19

All 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 path

There 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:

What is -1 in python

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 Python

open() 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:

  • filename: It is the name of the file.
  • mode: It tells the program in which mode the file has to be open.
  • buffering: Here, if the value is set to zero (0), no buffering will occur while accessing a file; if the value is set to top one (1), line buffering will be performed while accessing a file.

Modes Of Opening File In Python

The file can be opened in the following modes:

Python File Opening Modes
Mode Description
r Opens a file for reading only. (It's a default mode.)
w Opens a file for writing. (If a file doesn't exist already, then it creates a new file. Otherwise, it's truncate a file.)
x Opens a file for exclusive creation. (Operation fails if a file does not exist in the location.)
a Opens a file for appending at the end of the file without truncating it. (Creates a new file if it does not exist in the location.)
t Opens a file in text mode. (It's a default mode.)
b Opens a file in binary mode.
+ Opens a file for updating (reading and writing.)

File Object Attributes

If 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: 0

File Reading In Python

For 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 lines

File Writing In Python

Similarly, 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 Exist

The 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 Python

In 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()
What is -1 in python
report this ad


Page 20

Here, 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 Python

Example:

dicto = {'Bookname' : 'Python', 'Price' : 210}

Accessing Dictionary Values

Dictionaries' 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 260

Creating a New Dictionary in Python

Example:

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 Counter

Let 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:

  • Create twenty-six variables, one for each letter of the alphabet & make the string traverse for each character, incrementing the corresponding counter variable.
  • Using a list, containing twenty-six elements & converting each letter to a specific number & use the number as an index to the list.
  • Programmers can also use dictionaries with letters as keys and counter as their corresponding values and add those items in the dictionary. Then, the programmer can increment the value of an existing item based on the repetition of every single letter.

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 Python

Programmers 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 Dictionary

Deleting 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 dictionary
What is -1 in python
report this ad


Page 21

There 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:

  1. The 'aware' object holds the details about time-zone and daylight saving information, whereas naïve objects do not have that feature.
  2. Naive objects are easy to understand and to work with.

Defining Tick

As 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.951356

Another 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: 14

Timetuple In Python

Python usually handles time's function as a tuple with nine numbers starting from zero (0) to eight (8).

0 Four digit number (year) 2016
1 Months 1 - 12
2 Day 1 - 31
3 Hour 0 - 23
4 Minute 0 - 59
5 Second 0 - 60
6 Days of the week 0 - 6 (where Zero designates Monday)
7 Days of a year 1 - 366
8 Daylight saving -1, 0, 1, -1

Timedelta Object

It 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 Time

Example:

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 Month

This 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 30
What is -1 in python
report this ad


Page 22

Here 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

  • Code Reuse: Modules let programmers save source code in files permanently & hence the codes in module files are persistent. Module codes can rerun as many times as required.
  • System Namespace Partitioning: In Python, the highest-level organizational unit of code is the Modules. Although they are just packages with names - these packages are self-contained. Like that of a local scope of functions, modules help to avoid name clashes across the program. So in a module, all the objects and codes are implicitly enclosed or bounded. Hence, modules are the natural programming tools used to group system components.
  • Shared Service or data Implementation: From the operational point of view, modules are also used to implement components that are shared across systems. For example, if a programmer needs to provide a global object which will be used by more than one file or function blocks, then the code can be used as a module that can be imported by several files.

import Statement

Programmers 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.
So the program will be:

Example:

import a #g.py file a.karl ('myself') #Prints "myself karl"

The figure below shows its working: 

What is -1 in python

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 Python

Python 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:

  • Find the module's file from the search-path
  • Compile it to byte-code (if needed)
  • To build the object, run the module's code

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.

What is -1 in python
report this ad


Page 23

Regular 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 Expression

Regular 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 Python

It 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 Function

This 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:

  • match(): is a method
  • pattern: this is the regular expression that uses meta-characters to describe what strings can be matched.
  • string: is used to search & match the pattern at the string's initiation.
  • flags: programmers can identify different flags using bitwise operator '|' (OR)

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 Function

It 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:

dyne

split Function

The 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 6

In the above program, \D+ represents one or more non-digit characters.

What is -1 in python
report this ad


Page 24

Python 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:

  • Low-Level Programming using sockets
  • Data encoding
  • HTTP and web-programming
  • High-Level client modules
  • Basic networking terms and their concepts etc.

Python Network Services

There are two levels of network service access in Python. These are:

  • Low-Level Access
  • High-Level Access

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 Socket

A 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:

  • Domain Name Servers (DNS)
  • IP addressing
  • E-mail
  • FTP (File Transfer Protocol) etc...

Socket Program

Python 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:

  • listen(): is used to establish and start TCP listener.
  • bind(): is used to bind-address (host-name, port number) to the socket.
  • accept(): is used to TCP client connection until the connection arrives.
  • connect(): is used to initiate TCP server connection.
  • send(): is used to send TCP messages.
  • recv(): is used to receive TCP messages.
  • sendto(): is used to send UDP messages
  • close(): is used to close a socket.

A Simple Network Program Using Python

Example:

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.close

Sending 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.

What is -1 in python
report this ad


Page 25

When 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:

  • Kernel Threads
  • User-space threads or User threads

Why Use Thread

Thread plays a significant role in application programming. All the GUI programs and web servers are threaded together. The main reasons for using threads are:

  • Parallel Computation: If any user has a multiprocessor machine, then the thread can allow doing parallel processing with the goal of an increase in processing speed.
  • Standardization: It became a standard approach for all programming languages as it increases programming speed.
  • Parallel I/O (Input/Output): When we talk about the speed of input & output, it is comparatively slow in CPU. By placing each i/o operations in multiple individual threads, programmers can make use of operations done in parallel with each other & with the computation speed.
  • Asynchronous Events: Multiple threaded applications can deal with asynchronous actions. For example, in a program, programmers may not know whether the next action will be to use the mouse or to use the keyboard. By planting a separate thread for each action, i.e., two threads both for mouse and keyboard, programmers are able to code a cleaner, efficient application, which is to use non-blocking I/O operations.

Thread Modules in Python

There 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

  • For a single process, multiple threads can be used to process and share the same data-space and can communicate with each other by sharing information.
  • They use lesser memory overhead, and hence they are called lightweight processes.
  • A program can remain responsive to input when threads are used.
  • Threads can share and process the global variable's memory.

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 Thread

It 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 Python

Example:

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: 4

Methods of Thread Class

The 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:

  • run(): It acts as the entry of the thread
  • start(): is used for starting the thread by calling the run()
  • isAlive(): is used to verify whether the still executing or not
  • getName(): is used for returning the name of a thread
  • setName(): is used to set the name of the thread
What is -1 in python
report this ad


Page 26

Until 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.

Browsing

What happens when a user clicks a hyperlink to browse a particular web-page or URL (Uniform Resource Locator).

The steps are:

  • Browser contacts the HTTP web server for demanding the URL
  • Parsing the URL
  • Look for the filename
  • If it finds that file, a request is sent back
  • Web browser takes a response from the webserver
  • As the server response, it either shows the received file or an error message.

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 CGI

The steps are:

  1. Find out which user is running the Web-server
  2. Check for server configuration to see if you can run the scripts in a particular directory
  3. Check for file's permission
  4. Make a clear assurance that scripts you made are readable and executable by the webserver user
  5. Make sure the Python-Script's first line refers to a webserver that the interpreter can run

The architecture of CHI is shown below:

What is -1 in python

Python CGI Program Structure

The 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 section

This is a simple Python script that writes its output to STDOUT file, i.e., on-screen.

Use of CGI Module

If 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 Header

Few are the important lists of HTTP headers frequently used in CGI programs. These are:

HTTP Header Value
Content-type text/html
Expires Date
Location URL
Set-Cookie String
Content-length N

CGI Environment Variables

Environment Variables Description
CONTENT_TYPE describes the data-type of the content
HTTP_COOKIE returns the visitor's cookie if one is set
CONTENT_LENGTH It is available for a POST request to define the length of query information
HTTP_USER_AGENT defines the browser type of the visitor
PATH_INFO defines the path of a CGI script
REMOTE_HOST defines the host-name of the visitor
REMOTE_ADDR defines the IP Address of the visitor
REQUEST_METHOD used to make request & the most common methods are - GET and POST
What is -1 in python
report this ad