Python Tutorial – Python Programming For Beginners

Recommended by 52 users

May 5, 2017
Python Tutorial – Python Programming For Beginners
Add to Bookmark Email this Post 5.4K    0

Python Tutorial:

I will start this Python Tutorial by giving you enough reasons to learn Python.

Python is simple and incredibly readable since closely resembles the English language. It’s a great language for beginners, all the way up to seasoned professionals. You don’t have to deal with complex syntaxes, let me give you an example:

If I want to print “Hello World” in python, all I have to write is:

print ('Hello World')

It’s that simple.

This blog on Python tutorial includes the following topics:

Let me give you one more motivation to learn Python, It’s wide variety of applications.

Python Applications:

Python finds application in a lot of domains, below are few of those:

ython Applications - Python Tutorial - EdurekaThis is not all, it is also used for automation and for performing a lot of other tasks.

After this Python tutorial, I will be coming up with a separate blog on each of these applications.

Python Introduction:

Python is an open source scripting language, let’s look at some cool features of python.

Python Features - Python Tutorial - Edureka
Let’s move ahead in this Python tutorial and understand how Variables work in Python.

Variables in Python:

Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

Variables - Python Tutorial - Edureka

Fig: The figure above shows three variables A, B and C

In python you don’t need to declare variables before using it, unlike other languages like Java, C etc.

Assigning values to a variable:

Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

Consider the below example:

S = 10
print(S)

This will assign value ‘10’ to the variable ‘S’ and will print it. Try it yourself.

Now in this Python tutorial, is the time to understand Data types.

Data Types in Python:

Python supports various data types, these data types defines the operations possible on the variables and the storage method.

Below is the list of standard data types available in Python:

Python Data Types - Python Tutorial - EdurekaLet’s discuss each of these in detail. In this Python tutorial we will start with ‘Numeric’ data type.

Numeric:

Just as expected Numeric data types store numeric values.

They are immutable data types, this means that, you cannot change it’s value.

Python supports three different Numeric data types:

Integer type: It holds all the integer values i.e. all the positive and negative whole numbers, example – 10.

Float type: It holds the real numbers and are represented by decimal and sometimes even scientific notations with E or e indicating the power of 10 (2.5e2 = 2.5 x 102 = 250), example – 10.24.

Complex type: These are of the form a + bj, where a and b are floats and J represents the square root of -1 (which is an imaginary number), example – 10+6j.

Now you can even perform type conversion. For example you can convert the integer value to a float value and vice-versa. Consider the example below:

A = 10
# Convert it into float type
B = float(A)
print(B)

The code above will convert an integer value to a float type. Similarly you can convert a float value to integer type:

A = 10.76
# Convert it into float type
B = int(A)
print(B)

Now let’s understand what exactly are lists in this Python tutorial.

List Data Type:

You can consider the Lists as Arrays in C, but in List you can store elements of different types, but in Array all the elements should of the same type.

List is the most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Consider the example below:

Subjects = ['Physics', 'Chemistry', 'Maths', 2]
print(Subjects)

Notice that the Subjects List contains both words as well as numbers. Now, let’s perform some operations on our Subjects List.

List Operations:

The table below contains the operations possible with Lists:

Syntax Result Description
Subjects [0] Physics This will give the index 0 value from the Subjects List.
Subjects [0:2] Physics, Chemistry This will give the index values from 0 till 2, but it won’t include 2 the Subjects List.
Subjects [3] = ‘Biology’  [‘Physics’, ‘Chemistry’, ‘Maths’, ‘Biology’] It will update the List and add ‘Biology’ at index 3 and remove 2.
del Subjects [2] [‘Physics’, ‘Chemistry’,  2] This will delete the index value 2 from Subjects List.
len (Subjects) [‘Physics, ‘Chemistry’, ‘Maths’, 2, 1, 2, 3] This will return the length of the list
Subjects * 2 [‘Physics’, ‘Chemistry’, ‘Maths’, 2]

[‘Physics’, ‘Chemistry’, ‘Maths’, 2]

This will repeat the Subjects List twice. 
Subjects [::-1] [2, ‘Maths’, ‘Chemistry’, ‘Physics’] This will reverse the Subjects List

Now, let’s focus on Tuples.


Tuples:

A Tuple is a sequence of immutable Python objects. Tuples are sequences, just like Lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Consider the example below:

Chelsea = ('Hazard', 'Lampard', 'Terry')

Now you must be thinking why Tuples when we have Lists. Consider the below reason:

Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to do with it, is iterate through it. That’s when you can use a Tuple instead of a List.

Guys! all Tuple operations are similar to Lists, but you cannot update, delete or add an element to a Tuple. 

Now, stop being lazy and don’t expect me to show all those operations, try it yourself.

Time to move on and understand Strings.

String Data Type:

Strings are amongst the most popular types in Python. We can create them simply by enclosing characters in quotes. Python treats single and double quotes in exactly the same fashion. Consider the example below:


S = "Welcome To edureka!"
D = 'edureka!'

Let’s look at few operations that you can perform with Strings.

Syntax Operation
print (len(String_Name)) String Length
print (String_Name.index(“Char”)) Locate a character in String
print (String_Name.count(“Char”)) Count the number of times a character is repeated in a String
print (String_Name[Start:Stop]) Slicing
print (String_Name[::-1]) Reverse a String
print (String_Name.upper()) Convert the letters in a String to upper-case
print (String_Name.lower()) Convert the letters in a String to lower-case

I hope you have enjoyed the read till now. Next up, in this Python tutorial we will focus on Set.

Set Data type:

A set is an unordered collection of items. Every element is unique.

A set is created by placing all the items (elements) inside curly braces {}, separated by comma. Consider the example below:

Set_1 = {1, 2, 3}

In Sets every element has to be unique. Try printing the below code:

Set_2 = {1, 2, 3, 3}

Here 3 is repeated twice, but it will print it only once.

Let’s look at some Set operations:

Union:

Union of A and B is a set of all elements from both sets. Union is performed using | operator. Consider the below example:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A | B)
output = {1, 2, 3, 4, 5, 6}

Intersection:
Intersection - Python Tutorial - Edureka

Intersection of A and B is a set of elements that are common in both sets. Intersection is performed using & operator. Consider the example below:

A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print ( A & B )
Output = {3, 4}

Difference:

Set Difference - Python Tutorial - EdurekaDifference of A and B (A – B) is a set of elements that are only in A but not in B. Similarly, B – A is a set of element in B but not in A. Consider the example below:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A - B)
Output = {1, 2, 3}

Symmetric Difference:

Symmetric Difference - Python Tutorial - EdurekaSymmetric Difference of A and B is a set of elements in both A and B except those that are common in both. Symmetric difference is performed using ^ operator. Consider the example below:

A = {1, 2, 3, 4, 5}
B = {4, 5, 6, 7, 8}
print(A ^ B)
Output = {1, 2, 3, 6, 7, 8}

Now is the time to focus on the last Data type i.e. Dictionary

Dictionary Data Type:

Now let me explain you Dictionaries with an example.

I am guessing you guys know about Adhaar Card. For those of you who don’t know what it is, it is nothing but a unique ID which has been given to all Indian citizen. So for every Adhaar number there is a name and few other details attached.

Now you can consider the Adhaar number as a Key and the person’s detail as the Value attached to that Key.

Dictionaries contains these Key Value pairs enclosed within curly braces and Keys and values are separated with ‘:’. Consider the below example:

Dict = {'Name' : 'Saurabh', 'Age' : 23}

 You know the drill, now comes various Dictionary operations.

Dictionary Operations:

Access elements from a dictionary:

Dict = {'Name' : 'Saurabh', 'Age' : 23}
print(Dict['Name'])
Output = Saurabh

Changing elements in a Dictionary:

Dict = {'Name' : 'Saurabh', 'Age' : 23}
Dict['Age'] = 32
Dict['Address'] = 'Starc Tower'
Output = {'Name' = 'Saurabh', 'Age' = 32, 'Address' = 'Starc Tower'}


Enough with Data types, Now is the time to see various Operators in Python.

Check Out Our Python Course

Operators in Python:

Operators are the constructs which can manipulate the values of the operands. Consider the expression 2 + 3 = 5, here 2 and 3 are operands and + is called operator.

Python supports the following types of Operators:

Python Operators - Python Tutorial - Edureka

Let’s focus on each of these Operators one by one.

Arithmetic Operators:

These Operators are used to perform mathematical operations like addition, subtraction etc. Assume that A = 10 and B = 20 for the below table.

Operator Description Example
+ Addition Adds values on either side of the operator A + B = 30
– Subtraction Subtracts the right hand operator with left hand operator  A – B = -10
* Multiplication Multiplies values on either side of the operator A * B = 200
/ Division Divides left hand operand with right hand operator A / B = 0.5
% Modulus Divides left hand operand by right hand operand and returns remainder B % A = 0
** Exponent Performs exponential (power) calculation on operators A ** B = 10 to the power 20

Consider the example below:

a = 21
b = 10
c = 0

c = a + b
print ( c )

c = a - b
print ( c )

c = a * b
print ( c )

c = a / b
print ( c )

c = a % b
print ( c )
a = 2
b = 3
c = a**b
print ( c )
Output = 31, 11, 210, 2.1, 1, 8

Now let’s see comparison Operator.

Comparison Operators:

These Operators compare the values on either sides of them and decide the relation among them. Assume A = 10 and B = 20.

Operator Description Example
==
If the values of two operands are equal, then the condition becomes true.
(A == B) is not true
!=
If values of two operands are not equal, then condition becomes true.
(A != B) is true
 >  If the value of left operand is greater than the value of right operand, then condition becomes true.  (a > b) is not true
 <  If the value of left operand is less than the value of right operand, then condition becomes true.  (a < b) is true
 >=  If the value of left operand is greater than or equal to the value of right operand, then condition becomes true.  (a >= b) is not true
 <=  If the value of left operand is less than or equal to the value of right operand, then condition becomes true.  (a <= b) is true

Consider the example below:

a = 21
b = 10
c = 0

if ( a == b ):
   print ("a is equal to b")
else:
   print ("a is not equal to b")

if ( a != b ):
   print ("a is not equal to b")
else:
   print ("a is equal to b")

if ( a < b ): 
   print ("a is less than b") 
else: 
   print ("a is not less than b") 

if ( a > b ):
   print ("a is greater than b")
else:
   print ("a is not greater than b")

a = 5
b = 20
if ( a <= b ): 
   print ("a is either less than or equal to b") 
else: 
   print ("a is neither less than nor equal to b") 

if ( a >= b ):
   print ("a is either greater than  or equal to b")
else:
   print ("a is neither greater than  nor equal to b")
Output = a is not equal to b
         a is not equal to b
         a is not less than b
         a is greater than b
         a is either less than or equal to b
         b is either greater than or equal to b

Now in the above example, I have used conditional statements (if, else). It basically means if the condition is true then execute the print statement, if not then execute the print statement inside else. We will understand these statements later in the blog.

Assignment Operators:

An Assignment Operator is the operator used to assign a new value to a variable. Assume A = 10 and B = 20 for the below table.

Operator Description Example
= Assigns values from right side operands to left side operand c = a + b assigns value of a + b into c
+= Add AND It adds right operand to the left operand and assign the result to left operand c += a is equivalent to c = c + a
-= Subtract AND It subtracts right operand from the left operand and assign the result to left operand c -= a is equivalent to c = c – a
*= Multiply AND It multiplies right operand with the left operand and assign the result to left operand c *= a is equivalent to c = c * a
/= Divide AND It divides left operand with the right operand and assign the result to left operand c /= a is equivalent to c = c / a
%= Modulus AND It takes modulus using two operands and assign the result to left operand c %= a is equivalent to c = c % a
**= Exponent AND Performs exponential (power) calculation on operators and assign value to the left operand c **= a is equivalent to c = c ** a

Consider the example below:

a = 21
b = 10
c = 0

c = a + b
print ( c )

c += a
print ( c )

c *= a
print ( c )

c /= a
print ( c )

c  = 2
c %= a
print ( c )

c **= a
print ( c )
Output = 31, 52, 1092, 52.0, 2, 2097152, 99864

Bitwise Operators:

These operations directly manipulate bits. In all computers, numbers are represented with bits, a series of zeros and ones. In fact, pretty much everything in a computer is represented by bits. Consider the example shown below:

Bitwise And - Python Tutorial - EdurekaFollowing are the Bitwise Operators supported by Python:

Bitwise Operators - Python Tutorial - EdurekaConsider the example below:

a = 58        # 111010
b = 13        # 1101
c = 0

c = a &amp;amp; b     # 8 = 1000
print ( c )

c = a | b     # 63 = 111111
print ( c )

c = a ^ b     # 55 = 110111
print ( c )

c = a &amp;lt;&amp;lt; 2    # 232 = 11101000 
print ( c ) 

c = a &amp;gt;&amp;gt; 2    # 14 = 1110
print ( c )

Next up, in this Python tutorial we will focus on Logical Operators.

Logical Operators:

Logical Operators - Python Tutorial - EdurekaThe following are the Logical Operators present in Python:

Operator Description Example
and True if both the operands are true X and Y
or True if either of the operands are true X or Y
not True if operand is false (complements the operand) not X

Consider the example below:

x = True
y = False

print('x and y is',x and y)

print('x or y is',x or y)

print('not x is',not x)
Output = x and y is False
         x or y is True
         not x is False

Now, we will focus on Membership Operators.

Membership Operators:

These Operators are used to test whether a value or a variable is found in a sequence (Lists, Tuples, Sets, Strings, Dictionaries)

The following are the Membership Operators:

Operator Description  Example
in True if value/variable is found in the sequence 5 in x
not in  True if value/variable is not found in the sequence 5 not in x

Consider the example below:

X = [1, 2, 3, 4]
A = 3
print(A in X)
print(A not in X)
Output = True
         False

Now is the time to look at the last Operator i.e. Identity Operator.

Identity Operators:

These Operators are used to check if two values (or variables) are located on the same part of the memory. Two variables that are equal does not imply that they are identical.

Following are the Identity Operators in Python:

Operator Description Example
is True if the operands are identical x is True
is not  True if the operands are not identical x is not True

Consider the example below:



X1 = 'Welcome To edureka!'

X2 = 1234

Y1 = 'Welcome To edureka!'

Y2 = 1234

print(X1 is Y1)

print(X1 is not Y1)

print(X1 is not Y2)

print(X1 is X2)

Output = True
         False
         True
         False


I hope you have enjoyed the read till now. Next, we will look at various Conditional Statements.

Conditional Statements:

Conditional statements are used to execute a statement or a group of statements when some condition is true. There are namely three conditional statements – If, Elif, Else.

Consider the flowchart shown below:

 Conditional Statements - Python Tutorial - Edureka

Let me tell you how it actually works.

  • First the control will check the ‘If’ condition. If its true, then the control will execute the statements after If condition. 
  • When ‘If’ condition is false, then the control will check the ‘Elif’ condition. If Elif condition is true then the control will execute the statements after Elif condition.
  • If ‘Elif’ Condition is also false then the control will execute the Else statements.

Below is the syntax:

if condition1:
    statements

elif condition2:
    statements
    
else:
    statements

Consider the example below:

X = 10
Y = 12

if X < Y: 
    print('X is less than Y') 
elif X > Y:
    print('X is greater than Y')
else:
    print('X and Y are equal')

Output = X is less than Y


Now is the time to understand Loops.

Loops:

  • In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on.
  • There may be a situation when you need to execute a block of code several number of times.

A loop statement allows us to execute a statement or group of statements multiple times. The following diagram illustrates a loop statement:

Python Loops - Python Tutorial - EdurekaLet me explain you the above diagram:

  • First the control will check the condition. If it is true then the control will move inside the loop and execute the statements inside the loop. 
  • Now, the control will again check the condition, if it is still true then again it will execute the statements inside the loop.
  • This process will keep on repeating until the condition becomes false. Once the condition becomes false the control will move out of loop.

There are two types of loops:

  • Infinite: When condition will never become false.
  • Finite: At one point, the condition will become false and the control will move out of the loop.

There is one more way to categorize loops:

  • Pre-test: In this type of loops the condition is first checked and then only the control moves inside the loop.
  • Post-test: Here first the statements inside the loops are executed and then the condition is checked.

Python does not support Post-test loops.

Learn Python From Experts

Loops in Python:

In Python, there are three loops:

  • While
  • For
  • Nested

While Loop: Here, first the condition is checked and if it’s true, control will move inside the loop and execute the statements inside the loop until the condition becomes false. We use this loop when we are not sure how many times we need to execute a group of statements or you can say that when we are unsure about the number of iterations.

Consider the example:

count = 0
while (count < 10):
   print ( count )
   count = count + 1

print ("Good bye!")
Output = 0
         1
         2
         3
         4
         5
         6
         7
         8
         9
         Good bye!

For Loop: Like the While loop, the For loop also allows a code block to be repeated certain number of times. The difference is, in For loop we know the amount of iterations required unlike While loop, where iterations depends on the condition. You will get a better idea about the difference between the two by looking at the syntax:

for variable in Sequence:
    statements

Notice here, we have specified the range, that means we know the number of times the code block will be executed.

Consider the example:


fruits = ['Banana', 'Apple',  'Grapes']

for index in range(len(fruits)):
   print (fruits[index])

Output = Banana
         Apple
         Grapes

Nested Loops: It basically means a loop inside a loop. It can be a For loop inside a While loop and vice-versa. Even a For loop can be inside a For loop or a While loop inside a While loop.

Consider the example:



count = 1
for i in range(10):
    print (str(i) * i)

    for j in range(0, i):
        count = count +1

Output = 
1
22
333
4444
55555
666666
7777777
88888888
999999999


Now is the best time to introduce functions in this Python tutorial.

Functions:

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. 

Python Functions - Python Tutorial - Edureka
def add (a, b):
    return a + b
c = add(10,20)
print(c)
Output = 30

I hope you have enjoyed reading this Python tutorial. We have covered all the basics of Python in this tutorial, so you can start practicing now. After this Python tutorial, I will be coming up with more blogs on Python for Analytics, Python Oops concepts, Python for web development, Python RegEx, and Python Numpy. Stay tuned!

View Upcoming Python Batches

Got a question for us? Mention them in the comments section and we will get back to you.  

To get in-depth knowledge on Python along with its various applications, you can enroll here for live online training with 24/7 support and lifetime access.

Share on
Comments
0 Comments

24 X 7 Customer Support X

  • us flag 1-800-275-9730 (Toll Free)
  • india flag +91 88808 62004