0% found this document useful (0 votes)
3 views81 pages

Python

This document provides an introduction to Python, covering its definition as a programming language, its applications, and how to write and run Python programs using different execution modes. It explains key concepts such as keywords, identifiers, variables, constants, operators, data types, and statements, along with examples for each. Additionally, it discusses the differences between mutable and immutable data types, and the use of comments in Python code.

Uploaded by

ahamedsipad2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views81 pages

Python

This document provides an introduction to Python, covering its definition as a programming language, its applications, and how to write and run Python programs using different execution modes. It explains key concepts such as keywords, identifiers, variables, constants, operators, data types, and statements, along with examples for each. Additionally, it discusses the differences between mutable and immutable data types, and the use of comments in Python code.

Uploaded by

ahamedsipad2000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 81

INTRODUCTION

TO PYTHON
What is program and programming
language
Ordered set of instructions or commands to be
executed by a computer is called a program.

The language used to specify those set of


instructions to the computer is called a
programming language.
for example Python, C, C++, Java, etc.
Python
● Python is a very popular and easy to learn

programming language, created by Guido

van Rossum in 1991.

● It is used in a variety of fields, including

software development, web development,

scientific computing, big data and Artificial

Intelligence.
Working with Python

● To write and run (execute) a Python program, we need to have a Python


interpreter installed on our computer or we can use any online Python
interpreter.
● The interpreter is also called Python shell.

Python prompt
Execution Modes

There are two ways to run a program using the Python

interpreter:

● Interactive mode
Interactive Mode
● In the interactive mode, we can type a Python statement on the
>>> prompt directly.
● As soon as we press enter, the interpreter executes the statement
and displays the result(s).
● Working in the interactive mode is convenient for testing a single
line code for instant execution.
● But in the interactive mode, we cannot save the statements for
future use and we have to retype the statements to run them
Script Mode
● In the script mode, we can write a Python program in a file, save it and then use
the interpreter to execute the program from the file. Such program files have
a .py extension and they are also known as scripts.
● Python scripts can be created using any editor. Python has a built-in editor
called IDLE which can be used to create programs. After opening the IDLE, we
can click File>New File to create a new file, then write our program on that file
and save it with a desired name.

● IDLE : Integrated Development and Learning Environment


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.


Python
Keywords
Example:
and – A logical operator
not – A logical operator
or – A logical operator
break – to break out of a loop
continue – to continue to the next iteration of
a loop
else – conditional statement
elif – same as the conditional statement
else-if
for – to create a for loop
while – to create a whileloop
Identifiers

● Python Identifier is the name we give to


identify a variable, function, class, module
or other object.
Identifiers
● The rules for naming an identifier in Python are as follows:

● The name should begin with an uppercase(A-Z) or a lowercase(a-z)

alphabet or an underscore sign (_). Thus, an identifier cannot start with a

digit.

● It can be of any length. (However, it is preferred to keep it short and

meaningful).
Identifiers

● For example, to find the average of marks obtained by a student

in three subjects namely Maths, English, Informatics Practices (IP).

● We can choose the identifiers as marksMaths, marksEnglish,

marksIP and avg

● avg = (marksMaths + marksEnglish + marksIP)/3


Variables
● Variables are containers for storing data values.
● Variable is an identifier whose value can change. For example
variable age can have different value for different person.
● In Python, we can use an assignment statement to create new
variables and assign specific values to them.
● gender = 'M'
● message = "Keep Smiling"
● price = 987.9
Constants
● Constants are types of variables whose values cannot be altered
or changed after initialization.
● Programmers has adopted a naming convention for
constants : use uppercase letters.
● Example :
● PI=3.14
Operators

● An operator is used to perform specific mathematical or

logical operation on values.

● The values that the operator works on are called

operands.

● For example, in the expression 10 + num, the value 10,


Types of Operators
Arithmetic Operators

● Python supports arithmetic operators to perform the four

basic arithmetic operations(addition, subtraction,

multiplication, division) as well as modular division, floor

division and exponentiation.


Types of Operators
Addition - Operator (+)

● Adds two numeric values on either side of the operator.

● Example :
>>> num1 = 5
>>> num2 = 6
>>> num1 + num2
11
Types of Operators
Subtraction - Operator
(-)
● Subtracts the operand on the right from the operand on
the left .

● Example :
>>> num1 = 5
>>> num2 = 6
>>> num1 - num2
Types of Operators
Multiplication -
Operator (*)
● Multiplies the two values on both sides of the operator.

● Example :
>>> num1 = 5
>>> num2 = 6
>>> num1 * num2
Types of Operators
Division - Operator (/)
● Divides the operand on the left by the operand on the
right of the operator and returns the quotient.

● Example :
>>> num1 = 5
>>> num2 = 2
>>> num1 / num2
2.5
Types of Operators
Modulus - Operator (%)
● Divides the operand on the left by the operand on the
right and returns the remainder .

● Example :
>>> num1 = 13
>>> num2 = 5
>>> num1 % num2
3
Types of Operators
Floor Division -
● Operator (//)
Divides the operand on the left by the operand on the right and
returns the quotient by removing the decimal part. It is
sometimes also called integer division.
● Example :
>>> num1 = 5
>>> num2 = 2
>>> num1 // num2
2
>>> num2 // num1
0
Types of Operators
Exponent - Operator (**)
● Raise the base to the power of the exponent.
● Example :
>>> num1 = 3
>>> num2 = 4
>>> num1 ** num2
81
Types of Operators
Relational Operators

● Relational operator compares the values of the operands

on its either side and determines the relationship among

them.
Types of Operators
Equals to - Operator
(==)
● If values of two operands are equal, then the condition is True,
otherwise it is False.
● Example :
>>>num1=10
>>>num2=0
>>> num1 == num2
False
Types of Operators
Not equal to - Operator
● (!=)
If values of two operands are not equal, then condition is True,
otherwise it is False.
● Example :
>>>num1=10
>>>num2=0
>>> num1 != num2
True
Types of Operators
Greater than - Operator
● If the value of the left(>)
operand is greater than the value of the
right operand, then condition is True, otherwise it is False.

● Example :
>>>num1=10
>>>num2=0
>>> num1 > num2
True
Types of Operators
Less than - Operator (<)
● If the value of the left operand is less than the value of the
right operand, the condition is true otherwise it is False

● Example :
>>>num1=10
>>>num2=0
>>> num1 < num2
False
Types of Operators

● Similarly, there are other relational


operators like <= and >=
Types of Operators
Assignment Operators

● Assignment operator assigns or changes the value of the


variable on its left .
Types of Operators
Assigns value from right side
operand to left side operand (=)

● If the value of the left oerand is less than the value of the right
operand, the condition is true otherwise it is False
● Example :
>>> num1 = 2
>>> num2 = num1
>>> num2
2
Types of Operators

● It adds the value of right side operand to the left side operand and assigns the
result to the left side operand.
● Note: x+ =y is same as x= x+y

● Example :
>>> num1 = 10
>>> num2 = 2
>>> num1 += num2
>>> num1
12
>>> num2
2
Types of Operators

● It subtracts the value of right side operand from the left side operand and
assigns the result to left side operand.
● Note: x− =y is same as x=x-y

● Example :
>>> num1 = 10
>>> num2 = 2
>>> num1 -= num2
>>> num1
8
Types of Operators
Logical Operators

● There are three logical operators in Python.

● These operators are and, or, not are to be written in

lower case only.

● The logical operator evaluates to either True or False

based on the logical operands on its either side.


Types of Operators
Logical AND – Operator(and)

● If both operands are True, then condition becomes True

● Example :
>>> num1 = 10
>>> num2 = -20
>>> num1 == 10 and num2 == -20
True
>>> num1 == 10 and num2 == 10
False
Types of Operators
Logical OR – Operator(or)
● If any of the two operands are True, then condition becomes
True .
● Example :
>>> num1 = 10
>>> num2 = 2
>>> num1 >= 10 or num2 >= 10
True
>>> num1 <= 5 or num2 >= 10
Types of Operators
Logical NOT – Operator(not)
● Used to reverse the logical state of its operand.
● Example :

>>> num1 = 10
>>> not (num1 == 20)
True
Types of Operators
Membership Operators

● Membership operator is used to check if a value is a


member of the given sequence or not.
Types of Operators
in - Operator

● Returns True if the variable or value is found in the specified


sequence and False otherwise .
● Example :
>>> numSeq = [1,2,3]
>>> 2 in numSeq
True
>>>100 in numSeq
False
Types of Operators
not in - Operator

● Returns True if the variable/value is not found in the specified


sequence and False otherwise.
● Example :
>>> numSeq = [1,2,3]
>>> 10 not in numSeq
True
>>> 1 not in numSeq
False
Expressions

● An expression is defined as a combination of constants,


variables and operators.
● Example :
(i) num – 20.4
(ii) 3.0 + 3.14
(iii) 23/3 -5 * 7(14 -2)
(iv) "Global"+"Citizen"
Precedence of Operators

● When an expression contains more than one operator, their precedence


(order or hierarchy) determines which operator should be applied first.
● '*' and '/' have higher precedence than '+' and '-'.
● Note:
● Parenthesis can be used to override the precedence of operators. The
expression within () is evaluated first.
● For operators with equal precedence, the expression is evaluated from
left to right.
Examples
Examples
Examples
Indentation

● Indentation refers to the spaces at the beginning of a code

line.

● Leaving whitespace (spaces and tabs) at the beginning of a

statement is called indentation.

● It is a common practice to use a single tab or four spaces


Data Types
● Data type identifies the type of data which a variable can
hold and the operations that can be performed on those
data.
Number
● Number data type stores numerical values only. It is further classified into
three different types: int, float and complex.

● Boolean data type (bool) is a subtype of integer. It is a unique data type,


consisting of two constants, True and False. Boolean True value is non-
zero. Boolean False is the value zero.
type()
● type() function is used to determine the data type of the variable.
● Example,
>>> quantity = 10
>>> type(quantity)
<class 'int'>
>>> price = -1921.9
>>> type(price)
<class 'float'>
● Variables of simple data types like integer, float, boolean etc. hold single

value. But such variables are not useful to hold multiple data values, for

example, names of the months in a year, names of students in a class,

names and numbers in a phone book or the list of artefacts in a

museum.

● For this, Python provides sequence data types like Strings, Lists, Tuples,

and mapping data type Dictionaries.


Sequence

● A Python sequence is an ordered collection of items, where each

item is indexed by an integer value. Three types of sequence

data types available in Python are Strings, Lists and Tuples.


(A) String
● String is a group of characters. These characters may be alphabets,
digits or special characters including spaces.
● String values are enclosed either in single quotation marks (for
example ‘Hello’) or in double quotation marks (for example “Hello”).
● The quotes are not a part of the string, they are used to mark the
beginning and end of the string for the interpreter.
● For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
(B) List
● List is a sequence of items separated by commas and items are
enclosed in square brackets [ ]. Items may be of different date types.
● Example,
● #To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> list1
[5, 3.4, 'New Delhi', '20C', 45]
(C) Tuple
● Tuple is a sequence of items separated by commas and items are
enclosed in parenthesis ( ). Once created, we cannot change items in
the tuple.
● Similar to List, items may be of different data types.
● Example,
#create a tuple tuple1
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
Mapping

● Mapping is an unordered data type in Python.


● Currently, there is only one standard mapping data type in Python
called Dictionary.
(A) Dictionary

● Dictionary in Python holds data items in key-value pairs and Items are
enclosed in curly brackets { }.
● Dictionaries permit faster access to data.
● Every key is separated from its value using a colon (:) sign.
● The key value pairs of a dictionary can be accessed using the key.
● Keys are usually of string type and their values can be of any data type.
● In order to access any value in the dictionary, we have to specify its key in
square brackets [ ].
Example

#create a dictionary
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold', 'Price(kg)':120}

>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold', 'Price(kg)': 120}

#getting value by specifying a key


>>> print(dict1['Price(kg)'])

120
mutable and immutable
datatypes
● Mutable objects in Python are those that can be changed after they are

created.

● Example : lists,dictionaries,sets

● Immutable objects in Python are those that cannot be changed after they

are created, Example : strings, integers, or tuples.


Statements

● Any instruction written in the source code and executed by the Python
interpreter is called a statement.
● There are mainly four types of statements in Python,
○ print statements
○ Assignment statements
○ Conditional statements
○ Looping statements.
Comments

● Comments are non-executable statements in a program.

● Comments are used to add a remark or a note in the source code. Comments

are not executed by interpreter.

● They are added with the purpose of making the source code easier for

humans to understand.
● In Python, a single line comment starts with # (hash sign).
Input and
Output
● Sometimes, we need to enter data or enter choices into a program.
● In Python, we have the input() function for taking values entered by input
device such as a keyboard. The input() function prompts user to enter data.
● Example,
>>> fname = input("Enter your first name: ")
Enter your first name: Arnab

>>> age = input("Enter your age: ")


Enter your age: 19
Input and
Output
● Python uses the print() function to output data to standard output device —
the screen. The function print() evaluates the expression before displaying it
on the screen. The syntax for print() is:
● print(value)
Input and
Output
● Write a Python program to calculate the amount payable if
money has been lent on simple interest. Principal or money lent
= P, Rate = R% per annum and Time = T years. Then Simple
Interest (SI) = (P x R x T)/ 100.
● Amount payable = Principal + SI.
● P, R and T are given as input to the program.
Debugging

● Due to errors, a program may not execute or may generate wrong output.
● There are mainly three types of errors. They are :

● Syntax errors
● Logical errors
● Runtime errors
Syntax Errors

● Python has rules that determine how a program is to be written. This is called

syntax.

● If there is any error in the syntax, it leads to syntax error.

● For example, parentheses must be in pairs, so the expression (10 + 12) is

syntactically correct, whereas (7 + 11 is not due to absence of right

parenthesis.
Logical Errors

● A logical error/bug (called semantic error) does not stop execution but the
program behaves incorrectly and produces undesired /wrong output.
● Since the program interprets successfully even when logical errors are
present in it, it is sometimes difficult to identify these errors.
● For example, if we wish to find the average of two numbers 10 and 12 and we
write the code as 10 + 12/2, it would run successfully and produce the result
16, which is wrong. The correct code to find the average should have been
(10 + 12) /2 to get the output as 11.
Runtime Error
● A runtime error causes abnormal termination of program while it is

executing. Runtime error is when the statement is correct

syntactically, but the interpreter can not execute it.

● For example, we have a statement having division operation in the

program. By mistake, if the denominator value is zero then it will

give a runtime error like “division by zero”.


● The process of identifying and removing logical errors and runtime

errors is called debugging.

● We need to debug a program so that is can run successfully and

generate the desired output.


Control Statements

if-else

if-elif-else

while loop

for loop
if..else
Statements
● The if..else statement, in which there are two possibilities and the
condition determines which one gets executed.
● Example : The user to enter their name and age, and then checks if
the entered age is greater than or equal to 18. If the age is greater
than or equal to 18, the program prints a message stating that the
person is eligible to vote.If the age is less than 18, the program
prints a message stating that the person is not eligible to vote.

age = int(input("Enter your age "))


if age >= 18: # use ‘:’ to indicate end of
condition.
if..else
Statements
● The if..else statement, in which there are two possibilities and the
condition determines which one gets executed.
● Example : The user to enter their name and age, and then checks if
the entered age is greater than or equal to 18. If the age is greater
than or equal to 18, the program prints a message stating that the
person is eligible to vote.If the age is less than 18, the program
prints a message stating that the person is not eligible to vote.

age = int(input("Enter your age "))


if age >= 18: # use ‘:’ to indicate end of
condition.
#Program to subtract smaller number from the
#larger number and display the difference.

num1 = int(input("Enter first number: "))


num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The difference of",num1,"and",num2, "is",diff)

Output:
Enter first number: 5
Enter second number: 6
The difference of 5 and 6 is 1
if..elif..else
Statements
● if...elif....else is used to check multiple conditions and execute statements

accordingly. Meaning of elif is elseif. We can also write elseif instead of elif for

more clarity.

● Number of elif is dependent on the number of conditions to be checked. If the

first condition is false, then the next condition is checked, and so on. If one of the

conditions is true, then the corresponding indented block executes, and the if

statement terminates. After that, the statements outside the if..else are
Check whether a number is positive,
negative, or zero.

number = int(input("Enter a number: ")


if number > 0:
print("Number is positive")
elif number < 0:
print("Number is negative")
else:
print("Number is zero")
For Loop

● Sometimes we need to repeat certain things for a particular number of


times.

● In programming, this kind of repetition is called looping or iteration, and it is


done using for statement. The for statement is used to iterate over a range
of values or a sequence.
● Syntax of the for Loop:
for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>
Program to print even numbers in a given sequence using
for loop.
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')

Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number
The range() Function

● The range() is a built-in function in Python.


● Syntax of range() function is:
range([start], stop[, step])
● It is used to create a list containing a sequence of integers from the given start
value upto stop value (excluding stop value), with a difference of the given
step value. If start value is not specified, by default the list starts from 0. If step
is also not specified, by default the value is incremented by 1 in each iteration.
All parameters of range() function must be integers. The step parameter can
be a positive or a negative integer excluding zero.
Examples:
● >>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
● #start value is given as 2
>>> list(range(2, 10))
[2, 3, 4, 5, 6, 7, 8, 9]
● #step value is 5 and start value is 0
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
● #step value is -1. Hence, decreasing #sequence is generated
>>> list(range(0, -9, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8]
Program to print the multiples of 10 for numbers in a given
range.

● #Print multiples of 10 for numbers in a range


for num in range(5):
if num > 0:
print(num * 10)
● Output:
10
20
30
40
Nested Loops

● A loop may contain another loop inside it. A loop inside another loop is

called a nested loop.


Control Statements:,,,

if-else if-elif-else while loop

for loop

You might also like