Our Special Offer - Get 3 Courses at 24,999/- Only. Read more
Hire Talent (HR):+91-9707 240 250

Python Tutorial

Python Video Tutorials | Learn Python in 3 Hours | Must Watch it!

Our Python tutorial introduces the reader informally to the basic concepts and features of the Python language. We hope these Python Tutorials are useful and will help you to get the best job in the networking industry. These Python Tutorials are prepared by Python Professionals based on MNC Companies expectation. Stay tuned we will update New Python Tutorials Frequently. If you want to learn Practical Python Training then please go through this Python Training in ChennaiPython Training in Bangalore, and Python Training in Pune.

Besant Technologies supports the students by providing Python Tutorials for the job placements and job purposes. Python is the leading important course in the present situation because of more job openings and the high salary pay. We provide the Python online training also for all students around the world through the Gangboard medium. These are top Python Tutorials, prepared by our institute experienced trainers.

These Python tutorial are suitable for both freshers and experienced professionals at any level. These tutorials are for intermediate to somewhat advanced Python professionals, but even if you are just a beginner or fresher you should be able to understand the tutorials by examples and explanations here we give.

What is Python?

Python is a programming language easy to learn and powerful. There are two primary factors why we have to use Python® is software quality and developer productivity. It’s commonly used in a variety of domains like Web programming, Internet Scripting, database, numeric and scientific programming, Gaming thus it also known as general purpose language.

The major technical strengths of this language are readability, easy to use and learn, it’s free and supported object-oriented, it is portable.

Python Training has dynamically typed language so every operation can be done on the fly. Python codes can be shipped or placed on the web more securely as it execution involves Python® Virtual Machine ( PVM ) and bytecode compilation which is platform independent.

Python® can communicate to other parts of the application using the variety of component integration. For an example using CPython component, python can call C/C++ libraries and can be called from C/C++ programs. It will also have support for accessing java objects, .NET objects through Jython, IronPython respectively.

As in Python, everything is the object, every operation seems to be easier than other scripting languages. Python® codes are equal to one third and one-fifth of C/C++ and Java programs in term of a number of lines. It has powerful memory management to reuse garbage collections.

Python supports different types of objects like numbers, string, tuples, list, the dictionary to store data and do operations on stored data. It has common methods and operations on sequence objects ( list, string, tuples ) like indexing, slicing, extended slicing.

Python is a popular programming language.

It was created in 1991 by Guido van Rossum. It is used for:

  • web development (server-side),
  • software development,
  • mathematics,
  • system scripting.

Why Python?

There are innumerable python courses in Bangalore. All you need is to pick one to receive training and you are more than good to go. By learning this course, you will avail yourself of multiple benefits, some of which are as follows-

  • Testing short code snippets become easy with Python‘s interactive mode. There is also an integrated development and learning environment (IDLE) for python.
  • New modules can be added to python for its extension.
  • To get a programmable interface, applications can be embedded with python.
  • A lot of operating systems including Unix, Mac OS, and Linux support this programming language.
  • Python is also heavily used in the data analytics domain. Tasks like getting data from databases, XML files, from the web and from text files can easily be performed using python. And that is probably the reason why python training in data analytics in Bangalore is quite a rage.

Python Syntax

The syntax of the Python language is the set of rules that define how a Python program will be written and interpreted in a runtime.

Example: 

>>>X=1
>>>If x<0.5:
Print(“the proper identification is important”)  

Description:

In the above example, the value 1 is assigned to x and if the condition is used in the above example  In the if condition the proper identification is important in this otherwise it shows indent error.

PYTHON VARIABLE

Python variable is a reserved memory location to store values. In other words, a variable in a python program gives data to the computer for processing. Every value in Python has a datatype. Different data types in Python are Numbers, List, Tuple, Strings, Dictionary, etc

Example:

>>x = 10
>>y = x+5

Description:

  • The value 10 is named in the variable X. if we call the x value it uses value 10.
  • It stores the value of x +5 in a variable named y.

PYTHON CASTING

Python casting which Is a simple process to convert into one type to another type and it done with functions such as int() or float() or str().

Example:

>>>X = 10
>>>Type(x)
<type’ int’>
>>>Str(x)
‘10’
>>>Float(x)
10.0

Description:

  • The ‘x’ value is 10 in the integer form which it converts into string by using the function str (x). Now, the  x =‘10’ is in the  string
  • After casting string value is converted into float by using the function float(x).

PYTHON STRING

A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. String literals in python are surrounded by either single quotation marks or double quotation marks.  strings in Python are arrays of bytes representing Unicode characters.

Example:

>>>Print(“it is a string”)
it is a string
>>>X = “it is a string”
>>Y = ’12’

Description:

  • In the above example, the  print(“it is a string”) is  used for printing the string in the output .
  • The second example it stores the value “it is a string” ( string type)  in a variable named ‘X’. 
  • The value ‘12’ is a string type which is stored in a variable named Y

PYTHON OPERATORS

Operators are the constructs that can manipulate the value of operands. Operators are different types. they are,

Operator Data Types:

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

Example:

>>>A,b=4,2
>>>C= a+b
>>>c
6
>>>D=a-b
>>>D
2
>>>E=a*b
>>>E
8
>>>f= a/b
>>>f
2

Description:

  • The value 4 and 2 is stored in the variable A and b
  • The addition of the a and  b value is stored in the variable c
  • The subraction of the a and b is stored in the variable D
  • The multiplication of the a and b is stored in the variable E

PYTHON LIST

List is collection of different objects which are ordered as well as mutable. Since the declaration of all values follows the same syntax “var = value”, based on the value representation the type of the var is determined.

Representation of List data type ->

Creation of list data:

To create a list data type we can just give an empty square braces to a varVar = [] # creates an empty list objects and referred to Var.

Also, we can call the list function call to create a list object

Var = list() # this also creates the same empty list

To create a list with static values, we have to give comma separated objects within square braces.

Var = [1,2,’apple’,’baby’]

The same way we can pass an iterable to the list function call

Var = list(“iterable”) # -> [‘I’,’t’,’e’,’r’,’a’,’b’,’l’,’e’]

Adding elements into a list object:

To add the element to an existing list object we have two methods to perform this operation.

Append and insert:

Append -> used to add the object to the last index of the list object we can use this method

Insert -> used to add the objects to a specific index in the list object.

Syntax for append and insert methods are

Append -> obj.append(value)

Insert -> obj.insert(index,value)

Example usage:

>>> a = [1,2,’apple’,’baby’]
>>> print(a)
[1, 2, ‘apple’, ‘baby’]
>>> a.append(‘value’)
>>> print(a)
[1, 2, ‘apple’, ‘baby’, ‘value’]
>>> a.append(‘data’)
>>> print(a)
[1, 2, ‘apple’, ‘baby’, ‘value’, ‘data’]
>>> a.insert(1,’text’)
>>> print(a)
[1, ‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’]
>>>
When we give index value greater than the length of the list object, the values/objects will be appended to the list
>>> a.insert(100,’last’)
>>> print(a)
[1, ‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]

Accessing any values from a list object

To access any element or object from a list we can just do indexing

Syntax-> obj[index]

We can either do forward or reverse indexing. Forward indexing starts from 0 to len(obj)-1.
Reverse indexing starts from -1 from the last index.
>>> print(a)
[1, ‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]
>>> print(a[0])
1
>>> print(a[5])
‘value’
>>> print(a[-1])
‘last’
>>> print(a[-3])
‘value’
We can also use for loop to access each values from a list.
>>> print(a)
[1, ‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]
>>> for i in a:
print(i,end = ‘ ‘)
1 text 2 apple baby value data last
>>>

Modify a value from list :

If we need to modify an value in a list, just refer to the index element and give a new value to it

Syntax -> obj[index] = New_Value

>>> print(a)
[1, ‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]
>>> a[2] = ‘modified’
>>> print(a)
[1, ‘text’, ‘modified’, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]
>>>

Remove element from a list:

To delete any element from a list we can either use the built in ‘del’ keyword or we can use the built-in object methods of list -> pop, remove

Del -> del obj[index] # deletes specific index value from list

Pop -> index based removal of values/objects from a list

Remove -> value based removal

Syntax->

Obj.pop([index]) -> if index is specified, the particular index element will be removed from the list, else last index will be removed

Obj.remove(value) -> first occurrence of value from the list will be removed off.

>>> del a[0]
>>> print(a)
[‘text’, 2, ‘apple’, ‘baby’, ‘value’, ‘data’, ‘last’]
>>> a.pop() # removes the last index
‘last’
>>> a.pop(3) # removes the third index element
‘baby’
>>> print(a)
[‘text’, 2, ‘apple’, ‘value’, ‘data’]
>>>
Also there is another method available with list object from 3.x version of python, clear method
Clear -> used to delete all the available values in the list and makes it empty
>>> a
[‘text’, 2, ‘apple’, ‘value’, ‘data’]
>>> a.clear()
>>> print(a)
[]
>>

Merge two different list into one.

To ad two list into one we can use the built-in extend method in list objects.

Syntax-> obj.extend(another_list)

>>> x = [1,2,3,4]
>>> y = [5,6,7,8]
>>>
>>> x.extend(y)
>>>
>>> print(x)
[1, 2, 3, 4, 5, 6, 7, 8]
>>

PYTHON TUPLES

Tuple is also the collection of objects but immutable(unchangeable). The representation of the tuple object is normal parenthesis.

Syntax-> var = value
a = (1,2,3,4)
a = tuple(5,6,7,8)

In tuple object we will not be able to any set of write operations.

Only read attributes are available in python tuple objects

Accessing elements in a tuple

To access element in the tuple we can use the indexing.

Also we can iterate over them using for loop also.

Example:

>>> a = 1,2,3,4
>>>
>>> a[0]
1
>>> for i in a:
print(i)
1
2
3
4
>>

PYTHON DICTIONARY

Dictionary data type is also a collection which uses Key value pair. If we have access any values we must use the specific key for it.

Representation of dict data type -> {}

Creation of Dictionary:

To create a dictionary we can use the empty braces or call the direct function call

>>> d = {}
>>> print(d)
{}
>>> x = dict()
>>> print(x)
{}
>>

To create a static dictionary we can use the following syntax:

Syntax -> {key:value,key1:value1,key2:value2,….}
Also in dict function call we can pass an iterator with two index elements which acts as a key value pair for dict object creation
Syntax-> dict([(k,v),’kv’,[‘k’,’v’]])
dict(key = value, key1 = val1, ….)

Examples:

>>> d = {‘key’:’value’,’k’:’v’,’k1′:’v1′}
>>> x = dict([‘kv’,(‘k1′,’v1’),[‘a’,’apple’]])
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘v’, ‘k1’: ‘v1’}
>>> print(x)
{‘k’: ‘v’, ‘k1’: ‘v1’, ‘a’: ‘apple’}
>>

All keys in the dictionary must be immutable data type. If we pass an mutable object as dictionary key it will raise an error

Adding elements into a dictionary:

To add elements into an existing dictionary we can use the following syntax

Syntax -> obj[key] = value

Examples:

>>> d[‘d’]=’data’
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘v’, ‘k1’: ‘v1’, ‘d’: ‘data’}
>>> d[‘t’]=’test’
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘v’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>

Accessing any element in a dictionary is using the same indexing concept, except instead of index positions we use the respective keys to access the particular values.

Examples:

>>> d[0] # will raise key error since indexing wont work here. it will search for key 0Traceback (most recent call last):
File “<pyshell#110>”, line 1, in <module>
d[0] # will raise key error since indexing wont work here. it will search for key 0
KeyError: 0
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘v’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> d[‘key’]
‘value’
>>> d[‘t’]
‘test’
>>> d[‘d’]
‘data’
>>

Modification of values in dictionary:

To modify an value for key in a dictionary we can just access that particular key element and just pass on the new value. Instead creating a duplicate record it will get updated to the existing record of dictionary

Examples:

>>> print(d)
{‘key’: ‘value’, ‘k’: ‘v’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>>
>>> d[‘k’] = ‘new value’
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>

Deleting an entry from dictionary:

To remove a entry from a dictionary object we can either use del keyword or built in methods of python dict objects.

Examples:

{‘k’: ‘v’, ‘k1’: ‘v1’, ‘a’: ‘apple’}
>>> del x[‘k’]
>>> print(x)
{‘k1’: ‘v1’, ‘a’: ‘apple’}
>>> x.pop(‘k1’)
‘v1’
>>> print(x)
{‘a’: ‘apple’}
>>>
>>> x.popitem() # deletes last index element
(‘a’, ‘apple’)
>>

Dictionary object methods clear() -> Used to remove all the entities in a dictionary

Examples:

>>> print(x)
{‘k’: ‘v’, ‘k1’: ‘v1’, ‘a’: ‘apple’}
>>> x.clear()
>>> print(x)
{}
>>>
Copy() -> used to take copy of exact dictionary in another memory loc>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> print(id(d))
61096320
>>> x = d.copy()
>>> print(x)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> print(id(x))
65646480
>>>
Fromkeys() -> used to form a dictionary with set of keys and default values
>>> {}.fromkeys([‘a’,’e’,’i’,’u’,’o’])
{‘a’: None, ‘e’: None, ‘i’: None, ‘u’: None, ‘o’: None}
>>> {}.fromkeys(“aeiou”,’default’)
{‘a’: ‘default’, ‘e’: ‘default’, ‘i’: ‘default’, ‘o’: ‘default’, ‘u’: ‘default’}
>>
Get() -> used to fetch the value for a key of dict_obj. If key is not available does nothing or passes the default value given in the function call
>>> d
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>>
>>> d.get(‘k’)
‘new value’
>>> d.get(‘x’) # does nothing even if the key is not available
>>>
>>> d.get(‘x’,’default’)
‘default’
>>> d.get(‘k’,’default’)
‘new value’
>>>
Items() -> returns all the key value pairs of a dictionary object as an iterator
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> d.items()
dict_items([(‘key’, ‘value’), (‘k’, ‘new value’), (‘k1’, ‘v1’), (‘d’, ‘data’), (‘t’, ‘test’)])
>>>
Keys() ->  used to return all the keys of a dictionary object as an iterator
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> d.keys()
dict_keys([‘key’, ‘k’, ‘k1’, ‘d’, ‘t’])
Setdefault() -> used to fetch the value of the key specified, if the key is not available a new one will be created with None object if value is not specified.. Else key will be created with the value provided.
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’}
>>> d.setdefault(‘x’)
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’, ‘x’: None}
>>> d.setdefault(‘x1′,’value’)
‘value’
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’, ‘x’: None, ‘x1’: ‘value’}
>>>
Update() -> Used to update the dictionary record, ie, merging two dictionaries into one.
>>> print(x)
{‘a’: ‘new’, ‘b’: ‘baby’, ‘key’: ‘updated’}
>>> print(d)
{‘key’: ‘value’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’, ‘x’: None, ‘x1’: ‘value’}
>>> d.update(x)
>>> print(d)
{‘key’: ‘updated’, ‘k’: ‘new value’, ‘k1’: ‘v1’, ‘d’: ‘data’, ‘t’: ‘test’, ‘x’: None, ‘x1’: ‘value’, ‘a’: ‘new’, ‘b’: ‘baby’}
>>>
Note that in the above dictionary d the new keys will be added and the existing key in d will be update with new dictionary values
Values() -> used to fetch all the values of an existing dictionary
>>> d.values()
dict_values([‘updated’, ‘new value’, ‘v1’, ‘data’, ‘test’, None, ‘value’, ‘new’, ‘baby’])
>>

PYTHON SET

Set is also a data type in python which is unchangeable and holds unique value, ad unordered.

Representation -> {}

The difference between dictionary and set is,

Dictionary will hold key-value pairs

Set data type will hold only unique keys

Accessing an element from the set:

To access any element from a set element we cannot use the same indexing concept since the set element are unordered. But we can use the for loop to iterate over the existing values in a set.

Examples:

>>> s = {1,2,3,4,5}
>>>
>>> s
{1, 2, 3, 4, 5}
>>> s[0] # throws Type error only
>>> for i in s:
print(i)
1
2
3
4
5

You can note that in the above accessing through index is not allowed but using a for loop we can access the elements.

Also we cannot change any objects inside a set element after declaration.

Adding element into a set element is simply carried out with the help of add and update method of a set object.

Add() -> add one element to the set element

Update() -> adds more thean one element to the set element

Examples:

>>> print(s)
{1, 2, 3, 4, 5}
>>> s.add(‘6’)
>>> s
{‘6’, 1, 2, 3, 4, 5}
>>> s.update([‘a’,’b’,’c’,’d’])
>>> s
{‘6’, 1, 2, 3, 4, 5, ‘d’, ‘c’, ‘b’, ‘a’}
>>>

Deleting an entry from a list element

To delete we do have different methods, either we can use remove or discard method of set object. Also we can use the pop element to remove the random element . And also we can the base del keyword to delete any set object itself.

Examples:

>>> print(s)
{‘6’, 1, 2, 3, 4, 5, ‘d’, ‘c’, ‘b’, ‘a’}
>>> s.remove(‘6’)
>>> print(s)
{1, 2, 3, 4, 5, ‘d’, ‘c’, ‘b’, ‘a’}
>>> s.pop()
1
>>> s.pop()
2
>>> s.discard(‘d’)
>>> print(s)
{3, 4, 5, ‘c’, ‘b’, ‘a’}
>>

Other data types must have atleast one index to be True condition

Python Decision Making

Python if/else statement:

Generally if we want to write any algorithms or automate an logic, we will be utilizing three different ways to handle the logic

Based on condition -> if statement

Based on iteration -> for statement

Iteration based on cnd -> while statement

if/else block

Used for writing condition or validation based logics in python

Syntax

If condition:

Stmts

Here indentation plays a major role in writing the blocks of statements. So maintain a proper indentation to segregate the blocks.

What are the conditional statements we can use in if block

We can directly use the Boolean values (True/False)

We can use any Expression or function which returns Boolean value

< , > , <= , >= , == , !=

We can use the direct data type with value also a True condition.

Numerical -> except 0 all are True condition

Other data types must have atleast one index to be True condition

Examples:

if True:

print(“Hello”)

print(“hi”)

if False:

print(“Not executed”)

if True:

print(“hello”)

n = 10

if n<=10:

print(“True”)

if n>10:

print(“Greater”)

a = []

if a:

print(“Hello”)

# if/else block

n=15

if n<10:

print(“Lesser”)

else:

print(“Greater”)

if n<=10 and n%5==0:

print(“success”)

elif n>10 and n%5==0:

print(“Cnd1”)

else:

print(“not satisfied”)

n=18

a,b,c = 1,2,3

if a>b and a>c:

print(“A is bigger”)

elif b>c:

print(“B is big”)

else:

print(“C is big”)

s = ‘qwytgnvb’

if ‘a’ in s or ‘e’ in s or ‘i’ in s or ‘o’ in s or ‘u’ in s:

print(“Vowels present”)

else:

print(“No vowels”)

PYTHON FOR LOOP

DEFINITION:

Iteration through different types of datatypes in sequence

Datatypes such as: List, Tuples.,

Examples: 1

Input_list = [ 2,4,6]
For x in input_list:
Print(x)

Explanation:

  1. Input list is the input of list datatype
  2. For is the keyword and in is also the keyword.
  3. X indicates temporary variable for iteration.
  4. Print(x) is the operation inside the for loop

Output:

2
4
6

Enumerate: Enumerate is a function, generally used within “for” loop for fetching the respective index of the input data.Input:Input_data = “Dhoni”

Examples: 2 

For x in Input_data:
Print(x)

Output:

0, “D”
1, “h”
2,”o”
3, “n”
4, “I”

To separate the index and value from the input data we need to use two temporary variable within for loop.

Examples: 3

Input_data = [“cat”, “dog”,”goat”]
For x, y in enumerate(Input_data):
Print(x)
Print(y)
Note: “x” will carry index of the input and “y” carries its value

Output:

0
1
2
“cat”
“dog”
“goat”

Conditional statements within for loop

Various conditional operators like if, else, while  and also various other keyword like “return” and “Continue” can be used in along.

Examples: 4

Input_data = “Dhoni”For x , y in enumerate(Input_data):
If x == “h”:
Print(“in the loop)
Else:
Print(“Not in the loop”)

Note: Above statement will print Else block, because “x” variable will only contain index data but in the above statement we trying to substitute string to it.

Output

Output:Not in the loop
Possible Solution:
If x == 2

By default for loop will keep travelling till the last value of the input even if it finds its condition satisfied in between.

Examples: 5

Input_data = [“cat”,”dog”,”goat”,”cow”]
For x in Input_data:
If x == “dog”:
Print(“Animal is “ , x)
Else:
Print(“please loop again”)

Output:

Please loop again
Animal is dog
Please loop again

Note: Even though our condition got satisfied on finding “dog” string my loop still traveling till the last value in the input

Drawback: unwanted memory and time getting consumed

Possible solution:

For x in Input_data:If x == “dog”:
Print(“Animal is “, x)
Return
Else:
Print(“please loop again”)

Note: return will stop the looping moments conditions get satisfied.

“Continue” is the opposite of “return”. It will enable code through ignore the data to be inside that particular if condition.

Examples: 6

Input_data = [“a”,”b”,”c”,”d”]
For x in Input_data:
If x == “b”:
Continue
Print(x)
Output:
a
c
d

Python While Loops

Description:

As long as the condition is “True” process after the condition will be executed.

Examples

Print(“Looping”)
data_input += 1

Note: If there is no increment option, then entire loop will traverse for n number of times

Output:

Looping
Looping
Looping
Looping
Looping
Looping

Break-in a while:

Break statement is used to stop the loop abruptly.

Examples:

Input_data = 1
While Input_data < 6:
Print(“looping”)
If Input_data == 3:
Break
Input_data += 1

Output:

Looping
Looping
Looping

Continue:

Continue statement does execute the process excluding the condition statement. (Reference in For Loop Topic)

PYTHON FUNCTION

DESCRIPTION:

. Function is block of statement or operation executed when it is called.

. Function reduces memory and time consumption

Types of Function:

Type 1: Function with Empty Arguments

Code:Def Run();
Print(“running”)
Run()
Output:
Running

Type 2 : Function with Arguments

Def Cricket(Name, Team):Print(Name , “plays for”, Team)
Cricket(“Dhoni”, “CSK”)

Output:

Dhoni plays for CSK

Note: First data in the calling will always get assigned to the first arguments in functions and so on.

Type 3: Function with Default Arguments

Def Cricket(Name , Team = “CSK):
Print(Name , “plays for “, Team)
Cricket(“Dhoni”)

Output:

Dhoni plays for CSK

Note:

  • If no data is passed for Team through function calling, its default value will be substituted.
  • Default arguments should come after non default arguments

Type 4: Function with Keyword Arguments.

Def Cricket(name,team):Print(name, “plays for “, team)
Cricket(“csk”, “dhoni”)

Output;

Csk plays for dhoni.

Note: Since arguments and function calling matches patterns, csk and dhoni values was assigned to improper variable.

To avoid those trouble we will be opting for  below keyword arguments.
Def Cricket(name, team):Print(name,”plays for “, team)
Cricket(team = “CSK”, name = “Dhoni”)

Output:

Dhoni plays for CSK.

NOTE:

Even though order were not proper between arguments and calling, values or data’s will be assigned to proper variable using keywords match.

*args and **Kwargs

* args is used to call function with multiple data’s

**Kwargs is used to call function with multiple data’s along with keywords.

Def Score(*runs): 

Examples:
Print(runs)
Score(25, 37, 58)
Output:
(25,37,58)

Note:
Even though only one data assigned inside function definition, we can pass n number of arguments because arguments inside function definition is added along with “*”

Output of *args always in tuple format

Def Score(**runs):

Examples:
Print(runs)Score(India=372, Pakisthan = 290)
Output:
{India:372, Pakisthan:290}
Note:
Output of **kwargs will be always in dictionary.

Function with Return Statements.

Descriptions:

Return statements is used in function to send back some acknowledgement back to function with data.

Examples:

Def Cricket(name):
Print(name)
Return “Success”
C = Cricket(“Dhoni”)
Print( C)

Output:

Dhoni
Success
Note:
if nothing is passed after return statement and if you still print the calling or calling object you will get output as none.

LAMBDA EXPRESSION:

DESCRIPTIONS:

Lambada expression is also called anonymous expression.

Multiple arguments with one expression.

Var = lambda a : a *a

Print(Var(2))

Output:

4

Example 2: (using lambda function anonymous inside another function)

def myfunc(n):

mydoubler = myfunc(2)

print(mydoubler(11))

output:

22

PYTHON ARRAYS

Arrays are the group of data stored in a single variable and can be accessed through index of the stored variable.

Input = [“cat”, “dog”, “goat”]

Print(Input[1]) à dog

Note:

Above prints the first index of the variable “Input”

Looping the data in the array can be done using “for” loop.

Functions used with Arrays.

Examples:

Append:
Input.append(“cow”)
Output:
[“cat”, “dog”,”goat”,”cow”]
Extend:
Input.extend([“cow”,”ant”])
Output:
[“cat”,”dog”,”goat”,”cow”,”ant”]
Pop:
Input.pop()
Output:
[“cat”,”dog”]
Remove:
Input.remove(“dog”)
Output:
[“cat”, “goat”]

Similarly many other functions used in the arrays in same manner:

Sort() à Sort the list in ascending order

Insert() à Insert the data by mentioning the exact position

Copy() à copy one list into another

Index() à Finding the index of particular value in the list

Count à finding the repeated value among the list

Reverse() à Reversing the entire list on the backward.

Clealr() à Clear the data in the list but not the list.

Note:

Append()  is used to add data in only one position

Extend() is used to add more than one position of data.

Sort() is used to sort the list in either way.(Ascending and Descending)

Python Classes/Objects

Class: It is a container having attributes (Variables) and behaviors (Functions)

Object: Its Referential memory location for accessing Class functions and attributes

Class and Object illustration:

For deleting memory location: del p1.age (del Ref_var.attribute)

Class and object are bounded under object definition is called as encapsulation.

Certain behaviors only shown to outside/objects are known as Data abstraction. Private variables unable to seen by object definition is called as data hiding

The properties of classes are derived from one to another is known as Inheritance.

Many shaped same name behaviors/functions are having same name is known as polymorphism/overloading.

Python Iterators:

List, Tuple, Dictionary, Strings and Sets are Iterators- Objects

Countable and retrievable elements are called iterators. This operation called iterators.

Iterators and Iteration illustration

Looping and iter() functions are used to iterate the values from the container_variable.

When we are creating class iteration we can make certain exception to stop the iteration.

Examples:

def __next__(self):#under MyNum Class
if self.val <= 100:
x = self.val
self.a += 1
return x
else:
raise StopIteration

Python Modules

Modules are nothing but another python file.it may be user defined or inbuild function from library

For example inbuild module: import pandas

Modules:

**Package: If the python folder directory contains __init__.py file then that directory import called as Package.

Python Dates:

datetime is a in build package allows user to access the date related operations.

Date time package

We can modify user defined dates also

Date time package:

user_defined = datetime.datetime(2020, 6, 1)
print(user_defined.strftime(“%B”))
#output:June
User_date = datetime.datetime(2020, 5, 17)
print(user_date)
#output: 2020-05-17 00:00:00

There are many more operations available in datetime package. Explore more as per your requirement.

Python JSON

JSON– is a lightweight data can be transferred to one format to another format.

JSON will be built on two structures:

Different languages contains different notations for collection of variables. To make it one format simpler we can convert and transfer in certain format is known as JSON formatting.

Examples:

Seperators: x = {
“name”: “Siva”,
“age”: 23,
}
print(json.dumps(x, indent=4, separators=(“. “, ” = “))) #indent is using for spacing

output:

{
 “name” = “Siva”.
 “age” = 23.
}

Python to JSON conversion shown above**

We can make JSON dumped variable as alphabetical format as well

json.dumps(x, sort_keys=True) #Print the values in alphabetical order 

Examples:

x = {
“name”: “Siva”,
“age”: 23,
}
print(json.dumps(x, sort_keys=True))

output:

{
“age”: 23,
“name”: “Siva”,
}

Python PIP

Python Exception Handler

It will be caught runtime exception.Try..except..finally is the syntax for this

Even if the code doesn’t have any errors finally block will be executed.

Python File Handling

Basic File Operations:

Syntax:

Var = open(Filename, Mode)

Description:

Var – Variable to do the file handling

Open – Keyword for opening a file

Mode – Mode of operation to be executed.

Types of Mode (Operation):

R – Reading a file

W – Writing a file

RB – reading a binary file

WB – writing a binary file

W + – Writing and Reading

R + – Reading and Writing

A – appending a file

Ab – appending a binary file

A+ – appending along with read and write operation.

Ab + – appending binary with read and write operation.

Examples: 1

Writing a file:
Var = open (“filename.txt”, “w”)
Var.write(“Writing onto the file”)
Var.close()
Output:
Open “filename.txt” and you can see the following string.
Writing onto the file.

Note:

  • During write operation it is mandatory to close the file.
  • While opening a file it will check for the file in the current directory of the python file.
  • If there is no file exist, then it will create its own and do the operation.
  • Every time you write on the same file, your data will be overwritten each time.

Reading a File

Examples:

Var = open(“filename.txt”, “r”)
Var.read()
Output:
“it reads the content from the file”

Note:

  • While reading, there should be file exist in the mentioned name. if not, it will throw an error saying “file not found”.
  • No need to close the file if it is read operation.

Other options:

Var.read() – This will read entire string from the file and stores.

Var.read(2) – Reads upto 2nd string form the entire file.

Var.readline() – Reads only first line of the string.

Var.readline(3) – Reads upto 3 string only from the first line

Var.readlines() – Reads the entire string in a file in list format using space as the divider .

Tips:

Var.readlines() is commonly used while doing file operation. Since it gives enormous ways of handling and manipulation easy.

Appending the file

Since write operation overwrites the content every time we write on to the same file.

Examples:

To overcome this, we can use “a” mode of operation.

Var = open(“filename.txt”, “a”)
Var.write(“content into the file”)
Var.close()

Note:

  • Every time you do write on the file, all the string will be getting appended along with the previous string.
  • “ab” file mode operation is used for appending a binary file.

W+ and R+:

Earlier mode of operations will enable us to do only one operation a time. To do both the operation, we need to use either r+ or w+ operation.

Examples:

Var = open(“filename.txt”, “w+)
Var.write(“Content on the file”)
Print(Var.read())
Var.close()
Output:
Open a file and you can see the content.
But but, you can’t see the same in print(var.read()) line

Reason behind empty read() statement:

  1. File operation always works based on Pointer or cursor of the file.
  2. Every time you write a file and then read on the second line, your pointer on the file might be pointing out at the last line of the write.
  3. when try to read, your pointer will be at the last line of the string. There is no line after that pointer so it is returning empty.

Solution for reading a file along the way of writing a file:

Var = open(“filename.txt”, w+)

R + – will do the same operation similar to W +

R + –  does similar operation to that of the “append”

Wb – content which we writing should be binary content.

Deleting a File

Deleting a file needs a library to be imported

Import os

Os.remove(“filename.txt)

Deletion on checking the file or folder

Import os

If os.path.exists(“filename.txt”):

Os.remove(“filename.txt”)

Else:

Print(“no such file”)

Besant Technologies WhatsApp