Introduction to Python tutorial

Python is a popular programming language. It is an interpreted, object-oriented, high-level, open-source programming language. It was created by Guido van Rossum in 1991.

Why to learn Python programming language?

The popularity of Python is growing rapidly. Python is one of the most popular programming languages which can be seen from the following graph as well.

python tutorial for beginners - why to learn python programming

Many leading industries are using Python programming languages like Google, Youtube, Dropbox, Raspberry Pi, Nasa, Netflix etc.

What are the applications of the Python programming language?

Some real time applications in this python tutorial are –

  1. Web development
  2. Game development
  3. Scientific and Numerical Applications
  4. Data analytics
  5. Artificial Intelligence and Machine learning
  6. System scripting

What are the prerequisites to learn python?

There are no such prerequisites to learn Python. But it will be helpful if you have a basic knowledge of any programming language concepts like what is a loop, what if and else does, how operators are used, etc.

Characteristics of Python programming

  1. Simple
  2. Easy to learn
  3. Easy to code
  4. Free and open-source
  5. Object-oriented programming language

Python programming basics

Creating first python program – Hello World

print("Hello World")

Hello World

print() function is used to print the value which is passed inside the parentheses.

Python variables – How to Define variable types

Variable: an element, feature, or factor that is liable to vary or change. In Python, a variable is a named unit of data that may be assigned a value that can be modified at any time.

Rules for defining a variable are:

  1. Variables names should be descriptive about the value they are holding.
  2. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. 
  3. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  4. Variable names are case-sensitive (age, Age and AGE are three different variables)

Python Operators

Operators are used to perform operations on variables and values.

Various Operators available to us in Python are:

Arithmetic operators

#Arithmetic operators are used with numeric values to perform common mathematical operations

print(10+7, 10-7, 10*7)

17, 3, 70

Assignment operators

#Assignment operators are used to assign values to variables

time_at_venue = 5
time_at_venue += 3
time_at_venue = time_at_venue + 3
print(time_at_venue)

11

Comparison operators

#Comparison operators are used to compare two values

distance_a = 10
distance_b = 12

print(distance_a = distance_b, distance_a >= distance_b, distance_a <= distance_b)

False, False, True

Logical operators

#Logical operators are used to combine conditional statements: 'and' 'or' 'not'

print(distance_a == distance_b and distance_a <= distance_b)
print(distance_a == distance_b or distance_a <= distance_b)

False

True

Identity operators

#Identity operators are used to compare the objects, not if they are equal, but
#If they are actually the same object, with the same memory location

print(distance_a is distance_b, distance_a is not distance_b)

False, True

Membership operators

#Membership operators are used to test if a sequence is presented in an object

weather = 'Humid'
print('mid' in weather)

True

Bitwise operators

#Bitwise operators are used to perform bitwise calculations on Integers

print(1 ^ 1)
print(1 & 0)
print(1 | 1)

0

0

1

Python Data Structures

Data structures are used for organizing and storing data in such a way that it is easy to access and can work efficiently. Python has the following built-in data structures:

List

Lists are a set of comma-separated items written within brackets. Elements are accessed by their index.

Python tutorial - Creating a python list

Tuples

Tuples are a sequence of immutable Python objects. These are just like python lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses.

python tutorial - creating a python tuple

Dictionary

Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element.

Dictionary holds key:value pair.

Python programming tutorial - Defining a python dictionary

Sets

Sets are both unordered and unindexed and are defined within curly brackets.

Python Arrays

Arrays in Python are used to store multiple values in one single variable.

To access arrays in Python, we need to first import the array module.

Create a new array in python

import array as arr

a = arr.array("i", [1, 2, 3, 4, 5])
a[0]

1

Reverse an array

import array as arr

a = arr.array("i", [1, 2, 3, 4, 5])
a.reverse()
a

array(‘i’, [5, 4, 3, 2, 1])

Pop an array

import array as arr

a = arr.array("i", [5, 4, 3, 2, 1])
a.pop()
a

array(‘i’, [1, 2, 3, 4])

Python Conditional Statements

Conditional statements or conditional expressions are features of a programming language, which perform different computations or actions depending on whether a programmer-specified boolean condition evaluates to true or false.

In python we have:

1.If statement

A programming conditional statement. If the condition is true, then a certain task is performed.

test = 5
if test>0:
  print("Positive")

Positive

2.if else

When the condition is true, the statement following the if is executed, otherwise, the statement following else is executed.

test = -5
if test>0:
  print("Positive")
else:
  print("Negative")

Negative

3.if elif else

It is used when multiple conditions are required to be checked.

test = 0
if test>0:
  print("Positive")
elif test==0:
  print("Zero")
else:
  print("Negative") 

Zero

4.nested if

If condition inside another if condition is known as nested if. It is used when we have very narrow parameters for our search.

test = 10
if test>=10:
 if test==0:
  print("Zero")
 else:
  print("Greater than Zero")
else:
print("Less than Zero")

Greater than Zero

Python Loops

Loop is a control flow statement for specifying iteration, which allows code to be executed repeatedly based on the nature of a condition.

In this python tutorial, there are 2 elements: 1 is action another is condition. The actions are repeated until the condition is TRUE.

There are two types of loops in the python language.

While loop

A while loop is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.

i = 5
while i>0:
  print(i)
  i=i-1

5

4

3

2

1

For loop

A for-loop steps through each of the items in a collection type, or any other type of object which is “iterable”.

Syntax:

for <item> in <collection>:
<statements>

If <collection> is a list or a tuple, then the loop steps through each element of the sequence.

If <collection> is a string, then the loop steps through each character of the string.

list1 = [1, 2, 3, 4, 5]
for i in list1:
print(i*i)

1

4

9

16

25

Break Statement

You can use the keyword break inside a loop to leave the while loop entirely. 

The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop. If the break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

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

0

1

2

Continue Statement

The keyword continues inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.

The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

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

0

1

2

4

5

Python OOPs

Object-oriented programming (OOP) is a method of structuring a program by bundling related properties and behaviors into individual objects. It works on the principles of abstraction, encapsulation, inheritance, and polymorphism.

It allows users to create the objects that they want and then, create methods to handle those objects.

Class – Classes are used to create new user-defined objects that contain information about something.

Object – Objects are instances of a class.

Inheritance – Inheritance allows us to define a class that inherits all the methods and properties from another class. Child class inherits all the properties of its parent class.

Inheritance – Inheritance allows us to define a class that inherits all the methods and properties from another class. Child class inherits all the properties of its parent class.

Constructor – ‘__init__’ function is the constructor used to initialize all the attributes of a class.

class job():
def_init_(self, Job_id, title, company, location, pay, deadline):
self.Job_id = Job_id
self.title = title
self.company = company
self.location = location
self.pay = pay
self.deadline = deadline
j = job(101, "Data Analyst", "TechLearn", "Noida", "6 lpa", "06-04-2021")
print(j.title)

Data Analyst

Python Functions

A function is a block of code that performs a particular task and we can call it at any time.

Python Main Function & Method Example: Understand __main__

In some Python scripts, we may see a function definition and a conditional statement which looks like:

def main():
  print("Hello World")
if __name__ == "__main__":
main()

Hello World

In this python tutorial, there is a function called main() that prints the phrase Hello World! There is also an if statement which checks the value of __name__ and compares it to the string “__main__”. When the if statement evaluates to True, the Python interpreter executes main().

Syntax:

def function_name(Parameters(optional)

Python Statements

return statement(optional)

Function call

To call a function in python, we simply use the name of the function and pass the required arguments.

Function Indentation

Indentations are important while writing a function. All the statements of the function should have the same indentation.

Arguments

Information can be passed to functions as arguments. These are specified after the function name, inside the parentheses.

1.Positional Arguments

When a function is called with some values, these values get assigned to the arguments according to their position.

def add(a,b):
s = a+b
 return s

add(4,5)

9

2.Keyword Arguments

Python allows functions to be called using keyword arguments, where value is passed with the parameter name like:

parameter_name = Value.

def add(a,b=100):
s = a+b
 return s

add(4)

104

Return statement

A function can contain one or more return statements. They can be situated anywhere in the function body. A return statement ends the execution of the function call and “returns” the result.If the return statement is without an expression or there is no return statement in the function, the special value “none” will be returned. 

Python Lambda Function

A Lambda function can take any number of arguments, but they contain only a single expression. 

An expression is a piece of code executed by the lambda function, which may or may not return any value.

x = lambda a : a + 100
print(x(5))

105

Python Queue: FIFO, LIFO Example

A Queue is a linear structure which follows a particular order in which the operations are performed..

The data that is entered first will be removed first. It has two ends front and rear. 

There are two types of queues in Python:

  1. FIFO queue – First In First Out : In this type of queue, the element which was entered first, is eliminated first.
  2. LIFO queue – Last In First Out : In this queue, the element last entered is first removed.

To access the queue in Python, we need to import the queue module.

Python New Line: How to Print WITHOUT Newline in Python

Everytime print statement is called in python, it prints in a new line.

print("techlearn")
print("TECHLEARN")

techlearn

TECHLEARN

To print without a newline, we use the end parameter which is passed as an argument in the print statement. The end parameter is used to append any string at the end of the output of the print statement in this python tutorial .

print("techlearn", end='')
print("TECHLEARN")

techlearn TECHLEARN

print("techlearn", end=',')
print("TECHLEARN")

techlearn, TECHLEARN

Python Strings

Python enables us to store a sequence of characters in the form of String and can be defined using single quotes or double-quotes.

name = 'John Doe'
name

‘John Doe’

name = "John Doe"
name

‘John Doe’

Operations on Strings:

We can perform the following operations on strings-

Replace

To replace a particular character or a sequence of characters in a Python string, we can utilize the replace() method.

name = "John Doe"
newname = name.replace('John', 'Jack')
print(name)
print(newname)

John Doe

Jack Doe

Join

We can convert a Python List into a Python string by using the join() method.

Syntax: separator’.join(listVariable)

Where separator is the character by which elements of string are to be separated.

strlist = ['John', 'is', 'a', 'good', 'guy']
finalstring = ' '.join(strlist)
finalstring

‘John is a good guy’

Split

To save all the words in a string in the form of a list, we can use the split() method in Python. It takes a separator as an argument, by default its value is whitespace or ‘ ‘.

name = "John Doe"
strlist = name.split()
strlist
[‘John’, ‘Doe’]

Splitting using comma as a separator.

var = 'John ate bananas, oranges after lunch'
var.split(',')
[‘John ate bananas’, ‘oranges after lunch’]

Reverse

To reverse a Python String, we can simply take the advantage of slicing operation by passing step parameter as -1.

name = "John Doe"
name.upper()

‘JOHN DOE’

name = "Hohn Doe"
name.lower()

‘John Doe’

Strip

Sometimes our string contains some extra whitespace at the start or end of the string. We can use strip(), rstrip(), and lstrip() methods to modify our string accordingly.

When we want to remove whitespaces from the start as well as the end of the string, we use the strip() method.

name = " John Doe   "
name.strip()

‘John Doe’

Count

If we want to find the number of occurrences of a particular character or a substring, then we can use count() method.

name = "john Doe"
name.count('o')

2

Format

The format() method in Python Strings enables us to insert the value(s) inside a string’s placeholder.

'The {} is situated at {} Bakers Street'.format(house,49)

‘The house is sitauted at 49 Bakers Street’

We can even assign names to the placeholders and insert their values accordingly.

'The {name} is situated at {number} Bakers Street'.format(number = 49, name = 'house')

‘The house is situated at 49 Bakers Street’

Length

To find the length of a list, we use len() method.

mylist = [1,2,3]
len(mylist)

3

Find

To find the starting index of a substring in a given Python String, we can use the find() method, which returns the index from which the substring starts, if the substring is not present then it will return -1. If multiple instances of the substring are present then it will return the index of first occurrence of substring.

name = 'John Doe'
name.find('Do')

5

name = 'John Doe'
name.find('o')

1

Python File Handling

Files are used to store our data. File handling refers to the operations that we perform on those files.

In Python, we can create, read, update and delete files.

The key function used for working with files in Python, is the open() function.

Syntax open(filename, mode)

There are four different methods (modes) for opening a file:

r – It is used for opening a pre-existing file for reading.

a – It opens a file in append mode and creates a new file in case if it doesn’t exist.

w – It opens a file for writing. It overwrites in case the file already exists and creates a new file otherwise.

x – It creates the specified file and returns an error if the file exists.

Copy a File

We can copy a file using the shutil library. So first we need to import it, using 

1. import shutilshutil.copyfile()

Syntax – shutil.copyfile(original, target)

original – here we need to send the path of the source file location

target – this is the destination path, the copied file can be found here

2. shutil.copystat()

shutil.copystat() method in Python is used to copy the permission bits, last access time, last modification time, and flags value from the given source path to given destination path.

The shutil.copystat() method does not affect the file content and owner and group information.

Syntax: shutil.copystat(source, destination, *, follow_symlinks = True)

source: A string representing the path of the source file.

destination: A string representing the path of the destination file.

follow_symlinks (optional) : The default value of this parameter is True. If it is False and source and destination both refer to a symbolic link then the shutil.copystat() method will operate on the symbolic links themselves rather than the files the symbolic links refer to.

Rename a File and Directory

In Python tutorial, the OS module provides functions for interacting with the operating system. It comes under Python’s standard utility modules.

os.rename()method in Python is used to rename a file or directory.

Syntax: os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)

source: path of the source file which is to be renamed.

destination: A path-like object representing the file system path.

src_dir_fd (optional): A file descriptor referring to a directory.

dst_dir_fd (optional): A file descriptor referring to a directory.

Python ZIP file

A ZIP file is an archive file format that supports lossless data compression.

Extracting a zip file

To extract all the files from a zip file, we use the function extractall().

from zipfile import ZipFile

#specifying the zip file name
file_name = "my_python_files.zip"

#opening the zip file in READ mode
with ZipFile(file_name, 'r') as zip:

  #printing all the content of the Zip file
  zip.printdir()

  #extracting all the files
  print('Extracting all the files now...')
  zip.extractall()
  print('Done!')

Python Exception Handling

Error in Python can be of two types i.e. Syntax errors and Exceptions. 

Errors are the problems in a program due to which the program will stop the execution. 

On the other hand, exceptions are raised when some internal events occur which changes the normal flow of the program.

In Python, Exceptions can be handled by try and except statements.

while True:
  user_input = input('Enter input')
  if user_input == 'exit':
   break
  try:
   num = int(user_input)
   print('It is an Integer')
  except ValueError:
   print('Not an Integer')

Enter input10

It is an Integer

Enter inputa

Not an Integer

Enter inputexit

The try block lets you test a block of code for errors.

The except block lets you handle the error. 

The finally block lets you execute code, regardless of the result of the try- and except blocks.

Python List

In Python, lists are a set of comma-separated items, which are written within square brackets. The items are accessed by their index.

example of python list

Methods used with Python List:

Comprehension

Python provides a concise way to create new lists from the existing list. Rather than using normal functions and loops for creating a list we can use List Comprehension as it is more compact and faster than normal loops.

veg
 = ["tomato", "potato", "onion", "brinjal", "garlic"]
newlist = [x for x in veg if "a" in x]
print(newlist)
[‘tomato’, ‘potato’, ‘brinjal’, ‘garlic’]

Append

The append() method in python adds a single item to the existing list. It doesn’t return a new list of items but will modify the original list by adding the item to the end of the list. After executing the method append on the list the size of the list increases by one.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.append('Jack')
print(Employee_name)
[‘John’, ‘Doe’, ‘Sebastian’, ‘Doe’, ‘Jack’]

Sort

The sort() method sorts the list in ascending order by default.

Syntax list.sort(reverse = True/False, key = function)

reverse – optional parameter. reverse = True is used for sorting in descending order.

Key – optional parameter. The list is sorted according to the number returned by the function (the lowest number first).

l = [100, 50, 165, 82, 123]
l. sort(reverse True)
print(1)
[165, 123, 100, 82, 50]

Length

The len() method returns the number of elements in a python object. This len() method is not specifically for lists but this method can be used with other python data structures.

a = "TechLearn"
len(a)

9

Reverse

The reverse method() reverses the element of the list. It doesn’t take any arguments. The reverse method() doesn’t return any value. It only updates the existing list.

Employee_name = ['John', 'Doe', 'Sebastian', 'Jack']
Employee_name.reverse()
print(Employee_name)
[‘Jack’, ‘Sebastian’, ‘Doe’, ‘John’]

Count

The count() method returns the number of occurrences of an element in a list. In simple terms, count() method counts how many times an element has occurred in a list and returns it.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
print(Employee_name.count('Doe'))

2

Remove

The remove() method removes the first matching element (which is passed as an argument) from the list.

Employee_name = ['John', 'Doe', 'Sebastian', 'Doe']
Employee_name.remove('Doe')
print(Employee_name)
[‘John’, ‘Sebastian’, ‘Doe’]

Delete

An item which has to be deleted should be specified by its index. The first index is 0, and the last index is -1.

Employee_name = ['Jack', 'Joe', 'Sebastian', 'Doe']
del(Employee_name[2])
print(Employee_name)
[‘Jack’, ‘Joe’, ‘Doe’]

Pop

pop() is an inbuilt function in Python that removes and returns the last value from the list or the given index value. 

Parameter : 

index (optional) – The value at index is popped out and removed. If the index is not given, then the last element is popped out and removed.

Employee_name.pop(-1)
print(Employee_name)
[‘Jack’, ‘Sebastian’, ‘Doe’]

Clear

The clear method() doesn’t take any parameters. The clear method() only empties the given list. It doesn’t return any value.

Employee_name.clear()
Employee_name
[ ]

Index

The index() is used to find the index of the given element in the list. A ValueError exception is raised, when the element is not found.

letters ['a', 'b', 'c', 'd', 'e']
ind = letters.index('d')
print("Index of d : ", ind)

Index of d: 3

Find Average of a list in Python with Example

By using the functions – sum() and len(), we can find the average of a list in python.

sum() returns the sum of all the elements of the list.

len() returns the length of the list.

Average = sum()/len()

list1 - [ 1, 2, 3, 4, 5]
average = sum(list1)/len(list1)
print(average)

3.0

Explore Goals and projects in python programming at TechLearn –

Data Science Goal

You can also access the complete python tutorial here

LEAVE A REPLY

Please enter your comment!
Please enter your name here