Está en la página 1de 25

Python Tutorial – A Complete Guide to Learn

Python Programming
Python Tutorial:
Python is a high-level, object-oriented, interpreted programming language,
which has garnered worldwide attention. Stack Overflow found out that 38.8%
of its users mainly use Python for their projects. According to the website’s
survey, Python’s popularity surpassed that of C# in 2018 – just like it surpassed
PHP in 2017. On the GitHub platform, Python surpassed Java as the second-
most used programming language, with 40% more pull requests opened in
2017 than in 2016. This makes Python certification one of the most sought-after
programming certifications. In this Python Tutorial, I will be discussing the
following topics:

1. What is Python?
2. Python Features
3. Python Applications
4. Python and PyCharm Installation
5. Python IDE
6. Python Code Basics
1. Python Variables
2. Python Data Types
1. Lists
2. Tuples
3. Sets
4. Dictionary
5. Strings
6. Numeric
3. Python Operators
4. Python Conditional Statements
1. If Statement
2. Elif Statement
3. Else Statement
5. Python Loops
1. While Loop
2. For Loop
3. Nested Loop
6. I/O Operations
7. Python Functions

What is Python?
As I have mentioned Python is an open-source object-oriented programming
language. It first appeared in 1991 and has become extremely popular among
data scientists. StackOverflow calls it as the fastest growing programming
language.
But, what I mean by interpreted language, let’s understand what is an
interpreter first.

Python Interpreter:
An interpreter is a computer program that directly executes, i.e. performs,
instructions written in a programming or scripting language, without requiring
them previously to have been compiled into a machine language program. So
unlike Java, Python uses an interpreter.
Let us now install Python.

Python Installation:
I will be installing Python in Windows 10 OS. You can try installing Python in
Linux, Mac etc. If you face any issue mention it in the comments section.
Following are the steps to install Python
1. Go to www.python.org/downloads/
2. Select the Operating System and also the version of Python. I am
downloading 3.6.0 in my windows machine.
Open the installer and click on “Run”.

3. Click on “Install Now” and check on “Add Python 3.6 to PATH”.


4. Start IDLE which is a Python GUI and start scripting.

I don’t prefer using IDLE for coding in Python, instead, I will download PyCharm
which is an IDE (Integrated Development Environment). It will only be fair if I
explain to you what is an IDE before I proceed with this Python tutorial blog.

Python IDE (Integrated Development Environment):


IDE typically provides code editor, compiler/ interpreter and debugger in one
GUI (Graphical User Interface). It encapsulates the entire process of code
creation, compilation and testing which increases the productivity of developers.
A developer working with an IDE starts with a model, which the IDE translates
into suitable code. The IDE then debugs and tests the model-driven code, with
a high level of automation. Once the build is successful and properly tested, it
can be deployed for further testing through the IDE or other tools outside of the
IDE.
I am going to use PyCharm, you can use any other IDE that you want.
Installing PyCharm (Python IDE):
Go to www.jetbrains.com/pycharm/download/#section=windows

Here, the community version is free, but for the professional version, you need
to buy the license. I will be working on the PyCharm community version.
Now, let us have a look at why one should even consider Python as a preferred
or first programming language.

Why Learn Python?


Python’s syntax is very easy to understand. The lines of code required for a task
is less compared to other languages. Let me give you an example – If I have to
print “Welcome To Edureka!” all I have to type:
1print (“Welcome To Edureka!”)
Let’s look at some cool features of Python:

1. Simple and easy to learn


2. Free and Open Source
3. Portable
4. Supports different programming paradigm
5. Extensible

If you are wondering where you can use Python (Python Application), let me tell
you that is where Python stands out.

Python Applications:

1. Artificial Intelligence
2. Desktop Application
3. Automation
4. Web Development
5. Data Wrangling, Exploration And Visualization
Let us now start coding in Python, as I have mentioned above I will be using
PyCharm.

Trending Courses in this category

Python Certification Training for Data Science


5 (14150)
36k Learners Enrolled Live Class
Best Price 424 499

Similar CoursesPython Programming Certification CourseMachine Learning


Certification Training using PythonData Analytics with R Certification Training

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.

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:
1S = 10
2print(S)
This will assign value ‘10’ to the variable ‘S’ and will print it. Try it yourself.
Now in this Python Tutorial, we’ll 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:

Let’s discuss each of these in detail. In this Python tutorial, we’ll 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:
1A = 10
2# Convert it into float type
3B = float(A)
print(B)
4
The code above will convert an integer value to a float type. Similarly you can convert a float value
to integer type:

1A# =Convert
10.76
it into float type
2B = int(A)
3print(B)
4
Now let’s understand what exactly are lists in this Python Tutorial.

List:

 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:

1Subjects = ['Physics', 'Chemistry', 'Maths', 2]


2print(Subjects)
Notice that the Subjects List contains both words as well as numbers. Now, let’s perform some
operations on our Subjects List.
Let’s look at few operations that you can perform with Lists:

Syntax Result Description


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

Subjects [::-1] [2, ‘Maths’, ‘Chemistry’, ‘Physics’] This will reverse the Subjects List
Next in Python Tutorial, 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:

 Tuples cannot be changed unlike lists


 Tuples use parentheses, whereas lists use square brackets. Consider the example below:

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


Now you must be thinking why Tuples when we have Lists?
So the simple answer would be, Tuples are faster than Lists. If you’re defining a constant set of
values which you just want to iterate, then use 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.
Next in Python Tutorial, let’s understand Strings.

Strings:
Strings are amongst the most popular data 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:
1S = "Welcome To edureka!"
2D = '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
Count the number of times a character is repeated in a
print (String_Name.count(“Char”))
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:

 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:

1Set_1 = {1, 2, 3}
In Sets, every element has to be unique. Try printing the below code:
1Set_2 = {1, 2, 3, 3}
Here 3 is repeated twice, but it will print it only once.
Python Certification Training for Data ScienceWatch The Course Preview
Let’s look at some Set operations:
Union:
Union of A and B is a set of all the elements from both sets. Union is performed using | operator.
Consider the below example:
A = {1, 2, 3, 4}
1B = {3, 4, 5, 6}
2print ( A | B)
3
Output = {1, 2, 3, 4, 5, 6}

Intersection:

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:
1A = {1, 2, 3, 4}
2B = {3, 4, 5, 6}
3print ( A & B )
Output = {3, 4}

Difference:

Difference 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:
1A = {1, 2, 3, 4, 5}
2B = {4, 5, 6, 7, 8}
3print(A - B)
Output = {1, 2, 3}
Symmetric Difference:

Symmetric 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:
1A = {1, 2, 3, 4, 5}
2B = {4, 5, 6, 7, 8}
3print(A ^ B)
Output = {1, 2, 3, 6, 7, 8}
Next in Python Tutorial, it’s the time to focus on the last Data type i.e. Dictionary

Dictionary:
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:
1Dict = {'Name' : 'Saurabh', 'Age' : 23}
You know the drill, now comes various Dictionary operations.
 Access elements from a dictionary:
1Dict = {'Name' : 'Saurabh', 'Age' : 23}
2print(Dict['Name'])
Output = Saurabh

 Changing elements in a Dictionary:


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

Next in Python Tutorial, let’s understand the 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:

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
Subtracts the right hand operator with left hand
– Subtraction A – B = -10
operator
* 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
Divides left hand operand by right hand operand and
% Modulus B%A=0
returns remainder
A ** B = 10 to the
** Exponent Performs exponential (power) calculation on operators
power 20
Consider the example below:
1
2
3 a = 21
b = 10
4 c =0
5
6 c =a +b
7 print ( c )
8
c = a - b
9 print ( c )
10
11c = a * b
12print ( c )
13
14c = a / b
print ( c )
15
16c = a % b
17print ( c )
18a = 2
b = 3
19c = a**b
20print ( c )
21
22
Output = 31, 11, 210, 2.1, 1, 8
Now let’s see comparison Operators.

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
== (A == B) is not true
condition becomes true.
If values of two operands are not equal, then condition
!= (A != B) is true
becomes true.
If the value of left operand is greater than the value of
> (a > b) is not true
right operand, then condition becomes true.
If the value of left operand is less than the value of right
< (a < b) is true
operand, then condition becomes true.
If the value of left operand is greater than or equal to
>= (a >= b) is not true
the value of right operand, then condition becomes true.
If the value of left operand is less than or equal to the
<= (a <= b) is true
value of right operand, then condition becomes true.
Consider the example below:

1 ab == 21
10
2 c =0
3
4 if ( a == b ):
print ("a is equal to b")
5 else:
6 print ("a is not equal to b")
7
8 if ( a != b ):
print ("a is not equal to b")
9
else:
10 print ("a is equal to b")
11
12if ( a < b ): print ("a is less than b")
13 else: print ("a is not less than b")
14
if ( a > b ):
15 print ("a is greater than b")
16else:
17 print ("a is not greater than b")
18
19a = 5
b = 20
20if ( a <= b ): print ("a is either less than or equal to b")
21 else: print ("a is neither less than nor equal to b")
22
23if ( a => b ):
print ("a is either greater than or equal to b")
24else:
25 print ("a is neither greater than nor equal to b")
26
27
28
29
30
31
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 this Python Tutorial blog.
Python Certification Training for Data ScienceWatch The Course Preview

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 c = a + b assigns
=
operand value of a + b into c
+= Add AND It adds right operand to the left operand and assign the c += a is equivalent
result to left operand to c = c + a
It subtracts right operand from the left operand and assign c -= a is equivalent to
-= Subtract AND
the result to left operand c=c–a
It multiplies right operand with the left operand and assign c *= a is equivalent
*= Multiply AND
the result to left operand to c = c * a
It divides left operand with the right operand and assign c /= a is equivalent to
/= Divide AND
the result to left operand c=c/a
%= Modulus It takes modulus using two operands and assign the result c %= a is equivalent
AND to left operand to c = c % a
**= Exponent Performs exponential (power) calculation on operators and c **= a is equivalent
AND assign value to the left operand to c = c ** a
Consider the example below:
1
2
a = 21
3 b = 10
4 c =0
5
6 c =a + b
7 print ( c )
8
c += a
9 print ( c )
10
11c *= a
12print ( c )
13
c /= a
14print ( c )
15
16c = 2
17c %= a
18print ( c )
19
c **= a
20print ( c )
21
22
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:
Following are the Bitwise Operators supported by Python:
Consider the example
below:
1
2 a = 58 # 111010
3 b = 13 # 1101
4 c = 0
5
6 c =a & b
print ( c ) # 8 = 1000
7
8 c =a | b
9 print ( c ) # 63 = 111111
10
11c = a ^ b
print ( c ) # 55 = 110111
12
13c = a >> 2
14print ( c ) # 232 = 11101000
15
16c = a << 2
17print ( c ) # 14 = 1110
18
Output = 8,63,55,232,14
Next up, in this Python Tutorial we will focus on Logical Operators.
Logical Operators:

The 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:
1x = True
2y = False
3
4print('x and y is',x and y)
5
6print('x or y is',x or y)
7
print('not x is',not x)
8
Output = x and y is False
x or y is True
not x is False
Now in Python Tutorial, we’ll learn about 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) or not. 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]
1A = 3
2print(A in X)
print(A not in X)
3
4
Output = True
False
Next in Python Tutorial, it’s time we understand 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:
1
2 X1 = 'Welcome To edureka!'
3
X2 = 1234
4
5 Y1 = 'Welcome To edureka!'
6
7 Y2 = 1234
8
9 print(X1 is Y1)
10
print(X1 is not Y1)
11
12print(X1 is not Y2)
13
14print(X1 is X2)
15
Output = True
False
True
False

I hope you have enjoyed the read till now. Next in Python Tutorial, let’s 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:
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:


1
if condition1:
2 statements
3
4elif condition2:
5 statements
6
else:
7 statements
8
Consider the example below:
1X = 10
2Y = 12
3
4ifelif
X < Y: print('X is less than Y')
X > Y:
5 print('X is greater than Y')
6else:
7 print('X and Y are equal')
8
Output = X is less than Y

Now is the time to understand Loops.


Python Certification Training for Data ScienceWatch The Course Preview

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:

Let 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:
1count = 0
2while (count < 10):
3 print ( count )
count = count + 1
4
5
print ("Good bye!")
6
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:
1for variable in Sequence:
2 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:
1fruits = ['Banana', 'Apple', 'Grapes']
2
3for index in range(len(fruits)):
print (fruits[index])
4
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:
1count = 1
2for i in range(10):
3 print (str(i) * i)
4
for j in range(0, i):
5
count = count +1
6
Output =
1
22
333
4444
55555
666666
7777777
88888888
999999999

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

Trending Courses in this category

Python Certification Training for Data Science


5 (14150)
36k Learners Enrolled Live Class
Best Price 424 499

Similar CoursesPython Programming Certification CourseMachine Learning


Certification Training using PythonData Analytics with R Certification Training

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.
1def add (a, b):
2 return a + b
3 c = add(10,20)
print(c)
4
Output = 30

Python I/O Operation:

How To Open A File Using Python?


Python has a built-in function open(), top open a file. This function returns a file
object, also called a handle, as it is used to read or modify the file accordingly.
We can specify the mode while opening a file. In the mode, we specify whether
we want to

 read ‘r’
 write ‘w’ or
 append ‘a’ to the file. We also specify if we want to open the file in text
mode or binary mode.

The default is reading in text mode. In this mode, we get strings when reading
from the file.
o = open("edureka.txt") # equivalent to 'r' or 'rt'
1o = open ("edureka.txt",'w') # write in text mode
2o = open ("img1.bmp",'rb' ) # read and write in binary mode
3

How To Close A File Using Python?


When we are done with operations to the file, we need to properly close the file.
Closing a file will free up the resources that were tied with the file and is done
using Python close() method.
1o = open ("edureka.txt")
2o.close()
I hope you have enjoyed reading this Python Tutorial. We have covered all the basics of Python, 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

También podría gustarte