Python Programming (136 Blogs) Become a Certified Professional
AWS Global Infrastructure

Data Science

Topics Covered
  • Business Analytics with R (26 Blogs)
  • Data Science (20 Blogs)
  • Mastering Python (86 Blogs)
  • Decision Tree Modeling Using R (1 Blogs)
SEE MORE

Introduction To Python- All You Need To know About Python

Last updated on Aug 23,2024 6.7K Views


The IT industry is booming with artificial intelligence, machine learning and data science applications. With the new age applications, demand for a python developer has also increased. Ease of access and readability has made python one of the most popular programming language nowadays. Now is the time to switch over to python and unleash the endless possibilities that python programming comes with. This article on Introduction to python will guide you with the fundamentals and basic concepts in python programming.

In this article, I will give you an introduction to python. Following are the topics that will be covered in this blog:

Introduction To Python

Python is a general purpose programming language. It is very easy to learn, easy syntax and readability is one of the reasons why developers are switching to python from other programming languages.

We can use python as object oriented and procedure oriented language as well. It is open source and has tons of libraries for various implementations.

features-introduction to python-edureka

Python is a high level interpreted language, which is best suited for writing python scripts for automation and code re-usability.

It was created in 1991 by Guido Van Rossum. The origin of its name is inspired by the comedy series called ‘Monty python’.

Guido Van Rossum - Introduction to python - EdurekaWorking with python gives us endless possibilities. We can use python in data science, machine learning, Artificial intelligence, web development, software development etc.

applications of python-introduction to python-edureka

In order to work with any programming language, you must be familiar with an IDE. You can find the setup for an IDE for python, on ‘python.org’ and install it on your system. The installation is seemingly easy and comes with IDLE for writing python programs.

installation-introduction to python-edureka

After you have installed python on your system, you are all set to write programs in python programming language.

Lets start with this introduction to python with keywords and identifiers.

Keywords & Identifiers 

Keywords are nothing but special names that are already present in python. We can use these keywords for specific functionality while writing a python program.

Following is the list of all the keywords that we have in python:

keywords-introduction to python-edureka


import keyword
keyword.kwlist
#this will get you the list of all keywords in python.
keyword.iskeyword('try')
#this will return true, if the mentioned name is a keyword.

Identifiers are user defined names that we use to represent variables, classes, functions, modules etc.

name = 'edureka'
my_identifier = name

Variables & Data Types

Variables are like a memory location where you can store a value. This value, you may or may not change in the future.

x = 10
y = 20
name = 'edureka'

To declare a variable in python, you only have to assign a value to it. There are no additional commands needed to declare a variable in python.

Data Types in Python

  1. Numbers
  2. String
  3. List
  4. Dictionary
  5. Set
  6. Tuple

Numbers 

Numbers or numerical data type is used for numerical values. We have 4 types of numerical data types.

#integers are used to declare whole numbers.
x = 10
y = 20
#float data types is used to declare decimal point values
x = 10.25
y = 20.342
#complex numbers denote the imaginary values
x = 10 + 15j
#boolean is used to get categorical output
num = x < 5
#the output will be either true or false here.

String 

String data type is used to represent characters or alphabets. You can declare a string using single ” or double quotes “”.

name = 'edureka'
course = "python"

To access the values in a string, we can use indexes.

name[2]
# the output will be the alphabets at that particular index.

List

List in python is like a collection where you can store different values. It need not be uniform and can have different values.

Lists are indexed and can have duplicate values as well. To declare a list, you have to use square brackets.

my_list = [10, 20, 30, 40, 50, 60, 'edureka', 'python']
print(my_list)

To access values in a list we use indexes, following are a few operations that you can perform on a list:

  • append
  • clear
  • copy
  • count
  • extend
  • insert
  • pop
  • reverse
  • remove
  • sort

Following is a code for a few operations using a list:

a = [10,20,30,40,50]
#append will add the value at the end of the list
a.append('edureka')
#insert will add the value at the specified index
a.insert(2,'edureka')
#reverse will reverse the list
a.reverse()
print(a)
#the output will be
['edureka', 50, 40, 30, 'edureka', 20, 10]

Dictionary

A dictionary is unordered and changeable, we use the key value pairs in a dictionary. Since the keys are unique we can use them as indexes to access the values from a dictionary.

Following are the operations you can perform on a dictionary:

  • clear
  • copy
  • fromkeys
  • get
  • items
  • keys
  • pop
  • getitem
  • setdefault
  • update
  • values
my_dictionary = { 'key1' : 'edureka' , 2 : 'python'}
mydictionary['key1']
#this will get the value 'edureka'. the same purpose can be fulfilled by get().
my_dictionary.get(2)
#this will get the value 'python'.

Tuple

Tuple is another collection which is ordered and unchangeable. We declare the tuples in python with round brackets. Following are the operations you can perform on a tuple:

  • count
  • index
mytuple = (10,20,30,40,50,50,50,60)
mytuple.count(40)
#this will get the count of duplicate values.
mytuple.index(20)
#this will get the index for the vale 20.

Set

A set is a collection which is unordered and unindexed. A set does not have any duplicate values as well. Following are some operations you can perform on a set:

  • add
  • copy
  • clear
  • difference
  • difference_update
  • discard
  • intersection
  • intersection_update
  • union
  • update
myset = { 10 ,20,30,40,50,60,50,60,50,60}
print(myset)
#there will be no duplicate values in the output

In any programming language, the concept of operators plays a vital part. Lets take a look at operators in python.

Operators

Operators in python are used to do operations between two values or variables. Following are the different types of operators that we have in python:

  • Arithmetic Operators
  • Logical Operators
  • Assignment Operators
  • Comparison Operators
  • Membership Operators
  • Identity Operators
  • Bitwise Operators

Arithmetic Operators 

Arithmetic operators are used to perform arithmetic operations between two values or variables.

arithmetic operaotrs-introduction to python-edureka

#arithmetic operators examples
x + y
x - y
x ** y

Assignment Operators 

Assignment operators are used to assign values to a variable.

Logical Operators 

Logical operators are used to compare conditional statements in python.

Comparison Operators 

Comparison operators are used to compare two values.

Membership Operators 

Membership operators are used to check whether a sequence is present in an object.

Identity Operators 

Identity operators are used to compare two objects.

Bitwise Operators 

Bitwise operators are used to compare binary values.

Now that we have understood operators in python, lets understand the concept of loops in python and why we use loops.

Loops  In Python

A loop allows us to execute a group of statements several times. To understand why we use loops, lets take an example.

Suppose you want to print the sum of all even numbers until 1000. If you write the logic for this task without using loops, it is going to be a long and tiresome task.

But if we use a loop, we can write the logic to find the even number, give a condition to iterate until the number reaches 1000 and print the sum of all the numbers. This will reduce the complexity of the code and also make it readable as well.

There are following types of loops in python:

  1. for loop
  2. while loop
  3. nested loops

For Loop 

A ‘for loop’ is used to execute statements once every iteration. We already know the number of iterations that are going to execute.

A for loop has two blocks, one is where we specify the conditions and then we have the body where the statements are specified which gets executed on each iteration.

for x in range(10):
    print(x)

While Loop 

The while loop executes the statements as long as the condition is true. We specify the condition in the beginning of the loop and as soon as the condition is false, the execution stops.

 

i = 1
while i < 6:
     print(i)
     i += 1
#the output will be numbers from 1-5.

Nested Loops

Nested loops are combination of loops. If we incorporate a while loop into a for loop or vis-a-vis.

Following are a few examples of nested loops:

for i in range(1,6):
   for j in range(i):
       print(i , end = "")
   print()
# the output will be
1
22
333
4444
55555

Conditional and Control Statements

Conditional statements in python support the usual logic in the logical statements that we have in python.

Following are the conditional statements that we have in python:

  1. if
  2. elif
  3. else

if statement

x = 10
if x > 5:
   print('greater')

The if statement tests the condition, when the condition is true, it executes the statements in the if block.

elif statement

x = 10
if x > 5:
   print('greater')
elif x == 5:
     print('equal')
#else statement

x =10
if x > 5:
   print('greater')
elif x == 5:
     print('equal')
else:
     print('smaller')

When both if and elif statements are false, the execution will move to else statement. 

Control statements

Control statements are used to control the flow of execution in the program. 

Following are the control statements that we have in python:

  1. break 
  2. continue 
  3. pass

break 


name = 'edureka'
for val in name:
    if val == 'r':
       break
    print(i)
#the output will be
e
d
u

The execution will stop as soon as the loop encounters break. 

Continue


name = 'edureka'
for val in name:
    if val == 'r':
       continue
    print(i)
#the output will be
e
d
u
e
k
a

When the loop encounters continue, the current iteration is skipped and rest of the iterations get executed.

Pass

name = 'edureka'
for val in name:
    if val == 'r':
       pass
    print(i)

#the output will be
e
d
u
r
e
k
a

The pass statement is a null operation. It means that the command is needed syntactically but you do not wish to execute any command or code.

Now that we are done with the different types of loops that we have in python, lets understand the concept of functions in python.

Functions

A function in python is a block of code which will execute whenever it is called. We can pass parameters in the functions as well. To understand the concept of functions, lets take an example.

Suppose you want to calculate factorial of a number. You can do this by simply executing the logic to calculate a factorial. But what if you have to do it ten times in a day, writing the same logic again and again is going to be a long task.

Instead, what you can do is, write the logic in a function. Call that function everytime you need to calculate the factorial. This will reduce the complexity of your code and save your time as well.

Related Learning: Python Automation Testing

How to Create a Function?

# we use the def keyword to declare a function

def function_name():
#expression
    print('abc')

How to Call  a Function?

def my_func():
    print('function created')

#this is a function call
my_func()

Function Parameters 

We can pass values in a function using the parameters. We can use also give default values for a parameter in a function as well.

def my_func(name = 'edureka'):
    print(name)

#default parameter

my_func()
#userdefined parameter
my_func('python')

Lambda Function

A lambda function can take as many numbers of parameters, but there is a catch. It can only have one expression.


# lambda argument: expressions
lambda a,b : a**b
print(x(2,8))
#the result will be exponentiation of 2 and 8.

Now that we have understood function calls, parameters and why we use them, lets take a look at classes and objects in python.

Classes & Objects

What are Classes?

Classes are like a blueprint for creating objects. We can store various methods/functions in a class.


class classname:
      def functionname():
          print(expression)

What are Objects?

We create objects to call the methods in a class, or to access the properties of a class.


class myclass:
     def func():
         print('my function')

#<span style="color: #ff6600;">creating</span> an object

ob1 = myclass()

ob.func()

__init__ function

It is an inbuilt function which is called when a class is being initiated. All classes have __init__ function. We use the __init__ function to assign values to objects or other operations which are required when an object is being created.


class myclass:
      def __init__(self, name):
          self.name = name
ob1 = myclass('edureka')
ob1.name
#the output will be- edureka

Now that we have understood the concept of classes and objects, lets take a look at a few oops concepts that we have in python.

OOPs Concepts

Python can be used as an object oriented programming language. Hence, we can use the following concepts in python:

  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

Abstraction

Data abstraction refers to displaying only the necessary details and hiding the background tasks. Abstraction is python is similar to any other programming language.

Like when we print a statement, we don’t  know what is happening in the background.

Encapsulation

Encapsulation is the process of wrapping up of data. In python, classes can be a example of encapsulation where the member functions and variables etc are wrapped into a class.

Inheritance

Inheritance is an object oriented concept where a child class inherits all the properties from a parent class. Following are the types of inheritance we have in python:

  1. Single Inheritance
  2. Multiple Inheritance
  3. Multilevel Inheritance

Single Inheritance

In single inheritance there is only one child class that inherits the properties from a parent class.


class parent:
     def printname(name):
         print(name)

class child(parent):
      pass
ob1 = child('edureka')
ob1.printname

Multiple Inheritance

In multiple inheritance, we have two parent classes and one child class that inherits the properties from both the parent classes.

Multilevel Inheritance

In multilevel inheritance, we have one child class that inherits properties from a parent class. The same child class acts as a parent class for another child class.

Polymorphism

Polymorphism is the process in which an object can be used in many forms. The most common example would be when a parent class reference is used to refer to a child class object.

We have understood the oops concepts that we have in python, lets understand the concepts of exceptions and exception handling in python.

Exceptional Handling

When we are writing a program, if an error occurs the program will stop. But we can handle these errors/exceptions using the try, except, finally blocks in python.

When the error occurs, the program will not stop and execute the except block.


try:
    print(x)
except:
       print('exception')

Finally

When we specify a finally block. It will be executed even if there is an error or not raised by the try except block.

try :
    print(x)

except:
      print('exception')
finally:
      print('this will be executed anyway')

Now that we have understood exception handling concepts. Lets take a look at file handling concepts in python.

File Handling

File handling is an important concept of python programming language. Python has various functions to create, read, write, delete or update a file.

Creating a File

import os
f = open('file location')

Reading a File

f = open('file location', 'r')
print(f.read())
f.close()

Append a File

f = open('filelocation','a')
f.write('the content')
f.close()
f = open('filelocation','w')
f.write('this will overwrite the file')
f.close()

Delete a file

import os
os.remove('file location')

These are all the functions we can perform with file handling in python.

I hope this blog on introduction to python helped you learn all the fundamental concepts needed to get started with python programming language.

This will be very handy when you are working on python programming language, as this is the basis of learning in any programming language.Once you have mastered the basic concepts in python, you can begin your quest to become a python developer. To know more about python programming language in depth you can enroll here for live online python training with 24/7 support and lifetime access. 

Have any queries? you can mention them in the comments and we will get back to you.

Upcoming Batches For Python Programming Certification Course
Course NameDateDetails
Python Programming Certification Course

Class Starts on 30th November,2024

30th November

SAT&SUN (Weekend Batch)
View Details
Python Programming Certification Course

Class Starts on 28th December,2024

28th December

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

Introduction To Python- All You Need To know About Python

edureka.co