Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

Python Keywords

Python Keywords

Keywords are the reserved words that have special meanings to the compiler. They cannot be used as a variable. Keywords are the part of the syntax, for example:

return (a+b)

Here return is a keyword, whereas, a and b are variables.

Below is the list of all keywords used in Python:

and else lambda
or except None
assert finally nonlocal
break try pass
continue raise global
class from return
def import False
del in True
if is for
elif not while
with yield  

Descriptionof Python keywords

if

Python if statement is the simplest conditional statement. It is used to decide whether a block of the statement will be executed or not.

a = 20 
if (a>15): 
    print("I am bigger than 15") 

Output:

I am bigger than 15

else

An else statement is associated with if statement. When if statement’s condition is false then else block is executed. The following example makes it clear:

a = 20
b = 30
if (a> b):
    print('a is greater than b')
else:
    print('b is greater than a') 

Output

b is greater than a

elif

The elif is short for else-if. It is used for checking multiple conditions, which means that if the previous condition is false than check for the next condition. For example:

a=10
b=10 
if (a>b): 
    print('a is smaller than b') 
elif (a == b): 
    print(' a is equal to b') 
else: 
    print('a is greater than b') 

Output:

a is equal to b

True

True keyword is used to represent a boolean true.  If the given statement is true then interpreter returns true. For example:

print(1==1)

Output:

True

False

False Keyword is used to represent a boolean false. If the given statement is false then interpreter returns false. For example:

 print(1>1) 

Output:

False

assert

The assert is a keyword which is used as a debugging tool.It helps in a smooth flow of code. It helps us to find bugs more conveniently

Assertions are mainly assumptions that a programmer knows andalways wants it to be true. Hence puts them in code so that failure of that statement doesn't allow the code to execute further.

a = 10
b = 0
print('a is dividing by Zero')
assert b != 0
print(a / b)

Output:

a is dividing by Zero

Runtime Exception:

Traceback (most recent call last):
File "/home/40545678b342ce3b70beb1224bed345f.py", line 4, in 
assert b != 0, "Divide by 0 error"
AssertionError: Divide by 0 error 

and

and, or, not are the logical operators in Python. In and operator, if both operands are true, then the condition will become true. For example:

 a=100
if (a>90) and (a<101):
    print('Both conditions are true.a is ',a) 

Output:

Both conditionsare true. a is 100

The Truth table of and operator is given below:

A B A and B
True True True
True False False
False False False
False True False

or

or operator returns true if one of the statement is true

a=100
if (a>90) or (a>99):
    print('If anyone condition is true then a is’,a) 

Output:

If anyone condition is true then a is 100

The truth table is following

A B A or B
True True True
True False True
False True True
False False False

not

not operator returns true if given statement is false

 a = 100
if(not(x>105)):
    print('a is', a) 

Output:

a is 100

The truth table ofnot is given below:

A Not A
True False
False True

class

The class keyword is used to define a class in Python. Class is a collection of data (variables) and methods. The class can represent a real-world state. It is the main concept of OOPs (Object Oriented programming).

class Myclass:
#Variables……..
def function_name(self):
#statements………

del

The del keyword is used to delete the reference of the object.

a=5
del a
print(a)

Output:

Python Keywords

In the above code, variable a is no longerusedbecause the reference of the variable is deleted.

def

The def keyword is used to define a function. A function is used to divide our program into smaller and modularsub-parts. It provides reusability to our program. As programs grow larger, the function makes it more manageable.

def function_name(arguments): 
#function block

return

It is used inside the function to exit it and returns a value or none.

def add (a, b):
    sum=a+b
    return sum
sum = sum (20,30)
print ('The sum is ', sum)

Output:

The sum is 50

pass

The pass keyword is used when we want to execute nothing or create a placeholder for future code, if you declare an empty function or class, you will get an error without using pass statement.

class Myclass:
    pass
def myfun(arguments):
    pass

try, except

Exceptions are the runtime errors. Few examples of exception are ValueError, ZeroDivisior, NameError, TypeError, etc. try-except blocks are used to handle exceptions in Python.

a = 0
try:
    b = 1/a
except Exception as e:
    print(e)

Output:

division by zero

raise

The raise keyword allows to throws an exception at any time. For example:

 a = 10
if (a>5):
    raise Exception('a should not be exceeded than 5') 

Output:

Exception: a should not be exceeded than 5

finally

The finally block will always be executed no matter whethertry-expect block raises an error or not. For example:

try:
    a=0 
    b=20 
    v = b/a 
    print(v) 
except Exception as e: 
    print(e) 
finally: 
    print('Finally Always executed')

Output:

division by zero
Finally Always executed 

import

The import keyword is used to import modules into the current namespace.

import datetime 
x = datetime.datetime.now() 
print(x)

Output:

2019-08-05 16:19:16.334428

from

The fromkeyword is used for a specific function or attributes into the current namespace.

from math import sqrt
 x = sqrt(16) 
 print("The square root of 16 is ", x) 

Output:

The square root of 16 is 4.0

as

as keyword is used to create an alias while importing a module. With the help ofas, we can provide a user-defined name while importing a module. For example: importing a Python module calendar using alias name as cal.

import calendar as cal 
print(cal.month_name[1])

Output:

January

for

for is a keyword that is used for looping or iterating over a sequence (dictionary, list, string, set or tuple).

With for loop we can execute a set of statement once for each item in iterator(list, tuple, set, etc).

names = ['Ajay','Himanshu','Abhay','Anubhav']
for i in names:
    print(i)

Output:

Ajay
Himanshu
Abhay
Anubhav 

while

A while loop is executed until the given condition evaluates to false or break statement is encountered. It is also used to make an infinite loop.

a=0
while(a<=5):
    a = a+1
    print(a)  

Output:

1
2
3
4
5 

break

The break keyword is used to terminate the loop, even the condition is true. The control of the program passes to the outer statement after the body of the break statement.

a=0
while(a<5):
if(a==3):
    break
    a = a+1
    print(a)
print("end of program")

Output:

1
2
end of program 

continue

The continue keyword is used to stop the current iteration, and continues with the next statement

i = 0
while i <5:
    i += 1 
    if i == 3:
    continue
    print(i)

Output:

1
2
4
5 

with

The with keyword is used in exception handling.

It makes code cleaner and much more readable. It simplifies the management of shared resources like file streams. For example:

#without using with statement 
file = open('file_path', 'w')  
file.write('hello world !') 
file.close()

An exception during the file.write() call in the above implementation can prevent the file from closing properly, which may lead to several bugs in the code.

Any changes in files do not reflect until the file is properly closed.

# using with statement
with open('file_path', 'w') as file: 
 file.write('hello world !')

In the above code, there is no need to call file.close()while using withstatement.

Thus, with statement helps to avoid bugs and ensures that a resource is appropriately released.

The with statement is popularly used with file streams, as shown above, and with Locks, sockets, sub-processes, etc.

lambda

The keyword lambda is used to define an anonymous function (function with no name). It is an inline function. A standard function is defined by using def keyword.

Lambda function can have multiple arguments but only one expression. In the following example, lambda function evaluates square of 1 to 5.

x=lambda x: x**2
for i in range(1,6):
    print(x(i))

Output:

1
4
8
16
20 

global

When we declare a variable outside the function, it becomes global by default. If we want to access a global variable inside the function, we must use the global keyword.

a=10
def sum():
    global a
    print(a**2)
    return a
print(sum())

Output:

100
10 

nonlocal

The keyword nonlocal is related to the global keyword. It is used to work with variables inside a nested function (function inside a function).

If we want to modify the value of a non-local variable inside a nested function, then we must declare it with nonlocal.

def outside_function():
    a = 20
    def inside_function():
        nonlocal a
        a = 30
        print("Inner function: ",a)
inside_function()
 print("Outer function: ",a)
 outside_function()

Outside:

Inner function:  30

Outer function:  30

is

The is keyword is used to test if two-variable refers to the same object or testing object identity. It returns true if they refer to thesame object and return false if they do not refer to the same object, even if the two objects are 100% the equal. For example:

x=6
y=6
print(x is y)

Output:

True

In above code x and y refers to the same object.But in another example:

 [] == []
True
>>>[] is []
False
 >>>  {} == {}
True
 >>> {} is {}
False 

An empty list or dictionary is the same as another empty one. But they are not identical objects as they are stored separately in memory. It is because the list and dictionary are mutable which means value can be changed.

None

The None keyword is a special constant used to define a null value. It is an object of its own data type, the NoneType.

We must take special care that None does not indicate False, 0 or any empty list, dictionary, string, etc.

def return_void():
    a = 1
    b = 2
    c = a * b
x = return_void()
print(x)

Output:

None

In the above program, return_void()function does not return a value although it performs multiplication of two number. It prints None because function has returned None automatically.

yield

The yield statement prevents the function's execution temporally and returnsvalues to the caller.

It can produce a sequence of values whereas return sends a specified value back to its caller.

def simpleGenerator():
    yield 1
    yield 2
    yield 3

# Driver code to check above generator function 
forvalue in simpleGenerator():
    print(value) 

Output:

1
2
3



ADVERTISEMENT
ADVERTISEMENT