Unit – 2: Introduction to python
What is Pyhton ?
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics developed by
Guido van Rossum. It was originally released in 1991.
Features of python :
There are many features in Python, some of which are discussed below as follows:
1. Free and Open Source
Python language is freely available at the official website and you can download it from the given
download link below click on the Download Python keyword. Download Python Since it is open-source,
this means that source code is also available to the public. So you can download it, use it as well as
share it.
2. Easy to code
Python is a high-level programming language . Python is very easy to learn the language as compared to
other languages like C, C#, Javascript, Java, etc. It is very easy to code in the Python language and
anybody can learn Python basics in a few hours or days. It is also a developer-friendly language.
3. Easy to Read : As you will see, learning Python is quite simple. As was already established,
Python’s syntax is really straightforward. The code block is defined by the indentations rather than by
semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming . Python supports object-oriented
language and concepts of classes, object encapsulation, etc.
5. GUI Programming Support
Graphical User interfaces can be made using a module such as PyQt5, PyQt4, wxPython, or Tk in
python. PyQt5 is the most popular option for creating graphical apps with Python.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to remember the
system architecture, nor do we need to manage the memory.
7. Extensible feature
Python is an Extensible language. We can write some Python code into C or C++ language and also we
can compile that code in C/C++ language.
8. Easy to Debug:
Excellent information for mistake tracing. You will be able to quickly identify and correct the majority of
your program’s issues once you understand how to interpret Python’s error traces. Simply by glancing at
the code, you can determine what it is designed to perform.
9. Python is a Portable language
Python language is also a portable language. For example, if we have Python code for windows and
if we want to run this code on other platforms such as Linux, Unix, and Mac then we do not need to
change it, we can run this code on any platform.
10. Python is an Integrated language
Python is also an Integrated language because we can easily integrate Python with other languages like
C, C++, etc.
11. Interpreted Language:
Python is an Interpreted Language because Python code is executed line by line at a time. like other
languages C, C++, Java, etc. there is no need to compile Python code this makes it easier to debug our
code. The source code of Python is converted into an immediate form called bytecode.
12. Large Standard Library
Python has a large standard library that provides a rich set of modules and functions so you do not have
to write your own code for every single thing. There are many libraries present in Python such as regular
expressions, unit-testing, web browsers, etc.
13. Dynamically Typed Language
Python is a dynamically-typed language. That means the type (for example- int, double, long, etc.) for a
variable is decided at run time not in advance because of this feature we don’t need to specify the type of
variable.
14. Frontend and backend development
With a new project py script, you can run and write Python codes in HTML with the help of some simple
tags <py-script>, <py-env>, etc. This will help you do frontend development work in Python like
javascript. Backend is the strong forte of Python it’s extensively used for this work cause of
its frameworks like Django and Flask.
15. Allocating Memory Dynamically :
In Python, the variable data type does not need to be specified. The memory is automatically allocated to
a variable at runtime when it is given a value. Developers do not need to write int y = 18 if the integer
value 15 is set to y. You may just type y=18.
History Of Python :
Python was created by Guido van Rossum, and first released on February 20,
1991. While you may know the python as a large snake, the name of the Python programming language comes
from an old BBC television comedy sketch series called Monty Python's Flying Circus.
Writing and Execution of Python Program:
Download the IDLE on PC
Write a python code and save it.
To execute a file in IDLE, simply press the F5 key on your keyboard. You can also select Run →
Run Module from the menu bar. Either option will restart the Python interpreter and then run the code
that you've written with a fresh interpreter.
Python Syntax :
Execute Python Syntax
As we learned in the previous page, Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!")
Hello, World!
Or
C:\Users\Your Name>python [Link]
Simple Program :
# This program prints Hello, world!
print('Hello, world!')
Run Code
Output
Hello, world!
Variables: There are two types of variables in Python - Local variable and Global variable. Let's
understand the following variables.
Local Variable: Local variables are the variables that declared inside the function and have
scope within the function. Let's understand the following example.
Example -
1. # Declaring a function
2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The sum is:", c)
8. # Calling a function
9. add()
Output:
The sum is: 50
Global Variables: Global variables can be used throughout the program, and its scope is in
the entire program. We can use global variables inside or outside the function.
A variable declared outside the function is the global variable by default. Python provides
the global keyword to use global variable inside the function. If we don't use the global keyword,
the function treats it as a local variable. Let's understand the following example.
Example –
# Declare a variable and initialize it
1. x = 101
2.
3. # Global variable in function
4. def mainFunction():
5. # printing a global variable
6. global x
7. print(x)
8. # modifying a global variable
9. x = 'Welcome To Javatpoint'
10. print(x)
11.
12. mainFunction()
13. print(x)
Output:
101
Welcome To Javatpoint
Welcome To Javatpoint
Delete a variable: We can delete the variable using the del keyword. The syntax is
given below.
Syntax -
del <variable_name>
In the following example, we create a variable x and assign value to it. We deleted
variable x, and print it, we get the error "variable x is not defined". The variable x will
no longer use in future.
Example -
# Assigning a value to x
x=6
print(x)
# deleting a variable.
del x
print(x)
Output:
6
Traceback (most recent call last):
File "C:/Users/DEVANSH SHARMA/PycharmProjects/Hello/[Link]", line 389,
in
print(x)
NameError: name 'x' is not defined
Python Keywords :
Python has a set of keywords that are reserved words that cannot be used as variable names, function
names, or any other identifiers:
Keyword Description
and A logical operator
as To create an alias
assert For debugging
break To break out of a loop
class To define a class
continue To continue to the next iteration of a loop
def To define a function
del To delete an object
elif Used in conditional statements, same as else if
else Used in conditional statements
except Used with exceptions, what to do when an exception occurs
False Boolean value, result of comparison operations
finally Used with exceptions, a block of code that will be executed no matter if
there is an exception or not
for To create a for loop
from To import specific parts of a module
global To declare a global variable
if To make a conditional statement
import To import a module
in To check if a value is present in a list, tuple, etc.
is To test if two variables are equal
lambda To create an anonymous function
None Represents a null value
nonlocal To declare a non-local variable
not A logical operator
or A logical operator
pass A null statement, a statement that will do nothing
raise To raise an exception
return To exit a function and return a value
True Boolean value, result of comparison operations
try To make a try...except statement
while To create a while loop
with Used to simplify exception handling
yield To end a function, returns a generator
Python Data Types :
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in Python
programming, data types are actually classes and are instance (object) of these class.
Following are the standard or built-in data type of Python:
1) Numeric : In Python, numeric data type represent the data which has numeric value.
Numeric value can be integer, floating number or even complex numbers. These values are
defined as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
2) Sequence Type : In Python, sequence is the ordered collection of similar or different data
types. Sequences allows to store multiple values in an organized and efficient fashion.
There are several sequence types in Python –
String : In Python, Strings are arrays of bytes representing Unicode characters. A string is a
collection of one or more characters put in a single quote, double-quote or triple quote. In
python there is no character data type, a character is a string of length one. It is represented
by str class.
List : Lists are just like the arrays, declared in other languages which is a ordered
collection of data. It is very flexible as the items in a list do not need to be of the same type.
Tuples : Just like list, tuple is also an ordered collection of Python objects. The only
difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified
after it is created. It is represented by tuple class.
3) Boolean : Data type with one of the two built-in values, True or False. Boolean objects that are
equal to True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects
can be evaluated in Boolean context as well and determined to be true or false. It is denoted by the
class bool.
4) Set :In Python, Set is an unordered collection of data type that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various
elements.
5) Dictionary : in Python is an unordered collection of data values, used to store data
Dictionary
values like a map, which unlike other Data Types that hold only single value as an element,
Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
Each key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
‘comma’.
Python operator :
Operators are used to perform operations on variables and values. Python divides the operators in
the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Identity operators
Membership operators
Bitwise operators
i)Arithmetic Operators: Arithmetic operators are used with numeric values to perform
common mathematical operations:
Operator Name Example
+ Addition X+Y
- Substraction X–Y
* Multiplications X*Y
/ Division X/Y
% Modulus X%Y
** Exponentiation X ** Y
// X // Y
Floor Division
ii)Assignment Operators: Assignment operators are used to assign values to variables
Operator Example Same As
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
//= x //= 3 x = x // 3
**= x **= 3 x = x ** 3
&= x &= 3 x=x&3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
iii)Comparison Operators: Comparison operators are used to compare two
values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
iv)Logical Operators: Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are true x < 5 and x < 10
or Returns True if one of the statements is x < 5 or x < 4
true
not Reverse the result, returns False if the not(x < 5 and x <
result is true 10)
v)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:
Operator Description Example
is Returns True if both variables are the same x is y
object
is not Returns True if both variables are not the x is not y
same object
Membership Operators:
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in Returns True if a sequence with the specified value is x in y
present in the object
not in Returns True if a sequence with the specified value is x not in y
not present in the object
vi)Bitwise Operators: Bitwise operators are used to compare (binary)
numbers:
Operato Name Description
r
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left Shift left by pushing zeros in from the right and let the
shift leftmost bits fall off
>> Signed right Shift right by pushing copies of the leftmost bit in from the
shift left, and let the rightmost bits fall off
Indentation
Indentation refers to the spaces at the beginning of a code line .
Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
Python uses indentation to indicate a block of code.
Example
if 5 > 2:
print("Five is greater than two!")
Python Conditions and If statements:
if statement
The if statement is the most simple decision-making statement. It is used to decide whether a certain
statement or block of statements will be executed or not.
Syntax:
if condition:
# Statements to execute if
# condition is true
Here, the condition after evaluation will be either true or false. if the statement accepts Boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
Ex: i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")
Output:
I am Not in if
if-else statement
The if statement alone tells us that if a condition is true it will execute a block of statements and
if the condition is false it won’t. But if we want to do something else if the condition is false, we
can use the else statement with if statement to execute a block of code when the if condition is
false.
Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Ex: i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else
Block")
Output: i is greater than 15
i'm in else Block
i'm not in if and not in else Block
nested-if statement
A nested if is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, Python allows us to nest if statements
within if statements. i.e, we can place an if statement inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Example:
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than
15")
# Nested - if statement
# Will only be executed if
statement above
# it is true
if (i < 12):
print("i is smaller than 12
too")
else:
print("i is greater than
15")
Output:
i is smaller than 15
i is smaller than 12 too
Loops in Python:
Python programming language provides the following types of loops to handle looping
requirements. Python provides three ways for executing the loops. While all the ways provide
similar basic functionality, they differ in their syntax and condition-checking time .
While Loop in Python
In python, a while loop is used to execute a block of statements repeatedly until a given condition is
satisfied. And when the condition becomes false, the line immediately after the loop in the program is
executed.
Syntax:
while expression:
statement(s)
Example of Python While Loop: Let’s see a simple example of while loop in Python.
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
For Loop in Python:
For loops are used for sequential traversal. For example: traversing a list or string or array etc.
In Python, there is “for in” loop which is similar to for each loop in other languages. Let us learn
how to use for in loop for sequential traversals.
Syntax:
for iterator_var in sequence:
statements(s)
It can be used to iterate over a range and iterators.
Ex: n = 4 Output:
for i in range(0, n): 0
print(i) 1
2
3
Nested Loops:
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax:
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
The syntax for a nested while loop statement in the Python programming language is as
follows:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of any other type of loop.
For example, a for loop can be inside a while loop or vice versa.
Ex: # Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output:
1
2 2
3 3 3
4 4 4 4
Break Statement
The break statement in Python brings control out of the loop.
Ex: for letter in 'geeksforgeeks':
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
print('Current Letter :', letter)
Output:
Current Letter : e
Continue Statement:
The continue statement in Python returns the control to the beginning of the loop.
Ex: # Prints all letters except 'e' and 's'
for letter in 'geeksforgeeks':
if letter == 'e' or letter == 's':
continue
print('Current Letter :', letter)
Output:
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Pass Statements:
We use pass statement in Python to write empty loops. Pass is also used for empty
control statements, functions and classes.
Ex: # An empty loop
for letter in 'geeksforgeeks':
pass
print('Last Letter :', letter)
Output:
Last Letter : s