You are on page 1of 46

Introduction to Python

• Python is a simple, general purpose, high level, interpreted and object-oriented


programming language.
• Guido Van Rossum is known as the founder of Python programming.
• Guido van Rossum was a fan of the popular BBC comedy show of that
time, "Monty Python's Flying Circus". So he decided to pick the
name Python for his newly created programming language.
• Syntax
• There is no use of curly braces or semicolon in Python programming language.
It is English-like language. But Python uses the indentation to define a block
of code. Indentation is nothing but adding whitespace before the statement
when it is needed. 
• Where is Python used?
• Python is a general-purpose, popular programming language and it is used in almost every technical
field. The various areas of Python use are given below.
• Data Science
• Date Mining
• Desktop Applications
• Console-based Applications
• Mobile Applications
• Software Development
• Artificial Intelligence
• Web Applications
• Enterprise Applications
• 3D CAD Applications
• Machine Learning
• Computer Vision or Image Processing Applications.
• Speech Recognitions
• Python Popular Frameworks and Libraries
• Python has wide range of libraries and frameworks widely used in
various fields such as machine learning, artificial intelligence, web
applications, etc. We define some popular frameworks and libraries of
Python as follows.
• Web development (Server-side) - Django Flask, Pyramid, CherryPy
• GUIs based applications - Tk, PyGTK, PyQt, PyJs, etc.
• Machine Learning - TensorFlow, PyTorch, Scikit-learn, Matplotlib,
Scipy, etc.
• Mathematics - Numpy, Pandas, etc.
• Python Version List
• Python programming language is being updated regularly with new
features and supports. There are lots of update in Python versions,
started from 1994 to current release.
• A list of Python versions with its released date is given:
• Python provides us the two ways to run a program:
• Using Interactive interpreter prompt
• Using a script file
• Python Identifiers
• Python identifiers refer to a name used to identify a variable, function,
module, class, module or other objects. There are few rules to follow
while naming the Python Variable.
• A variable name must start with either an English letter or underscore
(_).
• A variable name cannot start with the number.
• Special characters are not allowed in the variable name.
• The variable's name is case sensitive.
• Python Variables
• Variables are the example of identifiers. An Identifier is used to identify the
literals used in the program. The rules to name an identifier are given below.
• The first character of the variable must be an alphabet or underscore ( _ ).
• All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore, or digit (0-9).
• Identifier name must not contain any white-space, or special character (!, @,
#, %, ^, &, *).
• Identifier name must not be similar to any keyword defined in the language.
• Identifier names are case sensitive; for example, my name, and MyName is
not the same.
• Examples of valid identifiers: a123, _n, n_9, etc.
• Examples of invalid identifiers: 1a, n%4, n 9, etc.
• Declaring Variable and Assigning Values
• Python does not bind us to declare a variable before using it in the
application. It allows us to create a variable at the required time.
• The equal (=) operator is used to assign value to a variable.
• Object References
• It is necessary to understand how the Python interpreter works when
we declare a variable. 
• In Python, variables are a symbolic name that is a reference or pointer
to an object. The variables are used to denote objects by that name.
• a = 50   

• a = 50
• b = 100
• Object Identity
• In Python, every created object identifies uniquely in Python. Python provides the
guaranteed that no two objects will have the same identifier. The built-in id() function, is
used to identify the object identifier. Consider the following example.
a = 50  
b = a  
print(id(a))  
print(id(b))  
# Reassigned variable a  
a = 500  
print(id(a))  
o/p
140734982691168
140734982691168
2822056960944
• The multi-word keywords can be created by the following method.
• Camel Case - In the camel case, each word or abbreviation in the
middle of begins with a capital letter. There is no intervention of
whitespace. For example - nameOfStudent, valueOfVariable, etc.
• Pascal Case - It is the same as the Camel Case, but here the first word
is also capital. For example - NameOfStudent, etc.
• Snake Case - In the snake case, Words are separated by the
underscore. For example - name_of_student, etc.
• Multiple Assignment
• Python allows us to assign a value to multiple variables in a single
statement, which is also known as multiple assignments.
• We can apply multiple assignments in two ways, either by assigning a
single value to multiple variables or assigning multiple values to
multiple variables. Consider the following example.
• 1. Assigning single value to multiple variables
• Eg:
x=y=z=50    
print(x)    
print(y)    
print(z)   
• Assigning multiple values to multiple variables:
• Eg:
1.a,b,c=5,10,15    
2.print a    
3.print b    
4.print c    
• Python Variable Types
• There are two types of variables in Python - Local variable and Global variable
• Local Variable
• Local variables are the variables that declared inside the function and have scope within the
function.
# Declaring a function  
def add():  
    # Defining local variables. They has scope only within a function  
    a = 20  
    b = 30  
    c = a + b  
    print("The sum is:", c)  
  
# Calling a function  
add()  
• 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.
# Declare a variable and initialize it  
x = 101    
# Global variable in function  
def mainFunction():  
    # printing a global variable  
    global x  
    print(x)  
    # modifying a global variable  
    x = 'Welcome'  
    print(x)    
mainFunction()  
print(x)  
• Delete a variable
• We can delete the variable using the del keyword.
# Assigning a value to x  
x = 6  
print(x)  
# deleting a variable.   
del x  
print(x)  
• Python Data Types
• Variables can hold values, and every value has a data-type. Python is a
dynamically typed language; hence we do not need to define the type of the
variable while declaring it. The interpreter implicitly binds the value with its type.
a=10  
b="Hi Python"  
c = 10.5  
print(type(a))  
print(type(b))  
print(type(c))  
<type 'int'>
<type 'str'>
<type 'float'>
• Python supports three types of numeric data.
• Int - Integer value can be any length such as integers 10, 2, 29, -20, -
150 etc. Python has no restriction on the length of an integer. Its value
belongs to int
• Float - Float is used to store floating-point numbers like 1.9, 9.902,
15.2, etc. It is accurate upto 15 decimal points.
• complex - A complex number contains an ordered pair, i.e., x + iy
where x and y denote the real and imaginary parts, respectively. The
complex numbers like 2.14j, 2.0 + 2.3j, etc.
• Sequence Type
• String
• The string can be defined as the sequence of characters represented in the quotation marks.
In Python, we can use single, double, or triple quotes to define a string.
• String handling in Python is a straightforward task since Python provides built-in functions and
operators to perform operations in the string.
• List
• Python Lists are similar to arrays in C. However, the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].
• Tuple
• A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().
• A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.
• Dictionary
• Dictionary is an unordered set of a key-value pair of items.
• Key can hold any primitive data type, whereas value is an arbitrary Python
object.
• Boolean
• Boolean type provides two built-in values, True and False. These values are used
to determine the given statement true or false. It denotes by the class bool.
• Set
• Python Set is the unordered collection of the data type. It is iterable,
mutable(can modify after creation), and has unique elements. 
• Python Operators
• The operator can be defined as a symbol which is responsible for a
particular operation between two operands. Operators are the pillars of
a program on which the logic is built in a specific programming language.
Python provides a variety of operators, which are described as follows.
• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
• Arithmetic Operators
• Arithmetic operators are used to perform arithmetic operations between
two operands. It includes + (addition), - (subtraction), *(multiplication),
/(divide), %(reminder), //(floor division), and exponent (**) operators.
• Comparison operator
• Comparison operators are used to comparing the value of the two
operands and returns Boolean true or false accordingly. 
• Assignment Operators
• The assignment operators are used to assign the value of the right
expression to the left operand.
• Bitwise Operators
• The bitwise operators perform bit by bit operation on the values of the
two operands. 
• Logical Operators
• The logical operators are used primarily in the expression evaluation
to make a decision.
• Membership Operators
• Python membership operators are used to check the membership of
value inside a Python data structure.
• Operator Precedence
• The precedence of the operators is essential to find out since it
enables us to know which operator should be evaluated first.
• The precedence table of the operators in Python is given below.
Python if-else statements
• Decision making is the most important aspect of almost all the
programming languages. As the name implies, decision making allows
us to run a particular block of code for a particular decision. 
• Indentation in Python
• For the ease of programming and to achieve simplicity, python
doesn't allow the use of parentheses for the block level code. In
Python, indentation is used to declare a block. If two statements are
at the same indentation level, then they are the part of the same
block.
• The if statement
• The if statement is used to test a particular condition and if the condition is true,
it executes a block of code known as if-block. The condition of if statement can be
any valid logical expression which can be either evaluated to true or false.
• The syntax of the if-statement is given below.
• if expression:  
•     statement  
• Eg:
num = int(input("enter the number?"))  
if num%2 == 0:  
    print("Number is even")  
• Eg2:
a = int(input("Enter a? "));  
b = int(input("Enter b? "));  
c = int(input("Enter c? "));  
if a>b and a>c:  
    print("a is largest");  
if b>a and b>c:  
    print("b is largest");  
if c>a and c>b:  
    print("c is largest");  
• The if-else statement
• The if-else statement provides an else block combined with the if
statement which is executed in the false case of the condition.
• If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
• The syntax of the if-else statement is given below.
• if condition:  
•     #block of statements   
• else:   
•     #another block of statements (else-block)   
• Eg1:
age = int (input("Enter your age? "))  
if age>=18:  
    print("You are eligible to vote !!");  
else:  
    print("Sorry! you have to wait !!");  
• Eg2:
num = int(input("enter the number?"))  
if num%2 == 0:  
    print("Number is even...")  
else:  
    print("Number is odd...")  
• The elif statement
• The elif statement enables us to check multiple conditions and execute the specific block of statements
depending upon the true condition among them. We can have any number of elif statements in our program
depending upon our need. However, using elif is optional.
• The elif statement works like an if-else-if ladder statement
• The syntax of the elif statement is given below.
• if expression 1:   
•     # block of statements   
•   
• elif expression 2:   
•     # block of statements   
•   
• elif expression 3:   
•     # block of statements   
•   
• else:   
•     # block of statements  
• Eg1:
number = int(input("Enter the number?"))  
if number==10:  
    print("number is equals to 10")  
elif number==50:  
    print("number is equal to 50");  
elif number==100:  
    print("number is equal to 100");  
else:  
    print("number is not equal to 10, 50 or 100");  
• Eg2:
marks = int(input("Enter the marks? "))  
if marks > 85 and marks <= 100:  
   print("Congrats ! you scored grade A ...")  
elif marks > 60 and marks <= 85:  
   print("You scored grade B + ...")  
elif marks > 40 and marks <= 60:  
   print("You scored grade B ...")  
elif (marks > 30 and marks <= 40):  
   print("You scored grade C ...")  
else:  
   print("Sorry you are fail ?")  
• Python Loops
• The following loops are available in Python to fulfil the looping needs. Python
offers 3 choices for running the loops. The basic functionality of all the techniques
is the same, although the syntax and the amount of time required for checking
the condition differ.
• We can run a single statement or set of statements repeatedly using a loop
command.
• The following sorts of loops are available in the Python programming language.
• Loop Control Statements
• Statements used to control loops and change the course of iteration
are called control statements.
• The while Loop
• With the while loop we can execute a set of statements as long as a
condition is true.
• Example
• Print i as long as i is less than 6:
i = 1
while i < 6:
  print(i)
  i += 1
• Using the break statement
while(i<6):
print("The value of i is ",i)
if(i==3):
break
i+=1
• The print() function prints the specified message to the screen, or
other standard output device.
• The message can be a string, or any other object, the object will be
converted into a string before written to the screen.
• Syntax:
• print(object(s), sep=separator, end=end, file=file,
flush=flush)
print("Welcome to Python World")  
 a = 10  
# Two objects are passed in print() function  
print("a =", a)  
b = a  
# Three objects are passed in print function  
print('a =', a, '= b')  
• How to take input from the user?

You might also like