0% found this document useful (0 votes)
11 views20 pages

Introduction to Python Programming

The document provides an introduction to Python programming, explaining its definition, features, and execution modes. It covers essential concepts such as keywords, variables, comments, data types, sequences, mappings, and operators. Additionally, it details how to write and run Python programs using an interpreter.

Uploaded by

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

Introduction to Python Programming

The document provides an introduction to Python programming, explaining its definition, features, and execution modes. It covers essential concepts such as keywords, variables, comments, data types, sequences, mappings, and operators. Additionally, it details how to write and run Python programs using an interpreter.

Uploaded by

hiyanshiff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO PYTHON

An ordered set of instructions to be executed by a computer


to carry out a specific task is called a program, and the
language used to specify this set of instructions to the
computer is called a programming language.

A program written in a high-level language is called


source code. Language translators like compilers and
interpreters are needed to translate the source code into
machine language. Python uses an interpreter to convert its
instructions into machine language, so that it can be
understood by the computer. An interpreter processes the
program statements one by one, first translating and then
executing.

FEATURES OF PYTHON

1. Python is a high level language. It is a free and


open source language.
2. It is an interpreted language, as Python
programs are executed by an interpreter.
3. Python programs are easy to understand as
they have a clearly defined syntax and relatively
simple structure.
4. Python is case-sensitive. For example,
NUMBER and number are not same in Python.
5. Python is portable and platform independent,
means it can run on various operating systems
and hardware platforms.
6. Python has a rich library of predefined functions.
7. Python is also helpful in web development. Many
popular web services and applications are built
using Python.
8. Python uses indentation for blocks and
nested blocks.

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.
Execution Modes
There are two ways to use the Python interpreter:
a) Interactive mode
b) Script mode
a) Interactive mode allows execution of
individual statement instantaneously.
b) Script Mode : In the script mode,
we can write a Python program in a file,
save it and then use the interpreter to
execute it. Python scripts are saved as
files where file name has extension
“.py”.

PYTHON KEYWORDS

Keywords are reserved words. Each keyword has a


specific meaning to the Python interpreter, and we
can use a keyword in our program only for the
purpose for which it has been defined. As Python is
case sensitive.
False class finally is return
None continue for lambda try

VARIABLES
A variable in a program is uniquely identified by a
name (identifier). In Python we can use an assignment
statement to create new variables and assign specific
values to them.
In programming languages, identifiers are names used
to identify a variable, function, or other entities in a
program. The rules for naming an identifier in
Python are as follows:
1. The name should begin with an uppercase or a
lowercase alphabet or an underscore sign (_). This
may be followed by any combination of characters
a–z, A–Z, 0–9 or underscore (_). Thus, an
identifier cannot start with a digit.
2. It should not be a keyword or reserved word.
3. We cannot use special symbols like !, @, #, $,
%, etc., in identifiers.
4. The variable message holds string type value and so
its content is assigned within double quotes (" "),
single quotes (' '), triple quotes (‘’’ ‘’’).

COMMENTs
Comments are used to add a remark or a note in the
source code. Comments are not executed by interpreter.
In Python, a comment starts with # (hash sign).
Everything following the # till the end of that line is
treated as a comment and the interpreter simply ignores it
while executing the statement.

DATA TYPES
Every value belongs to a specific data type in Python. Data
type identifies the type of data values a variable can hold
and the operations that can be performed on that data.
Number
Number data type stores numerical values only. It is
further classified into three different types: int, float and
complex.

Type/ Class Description Examples


int integer numbers –12, –3, 0, 125,
2
float real or floating –2.04, 4.0,
point numbers 14.23
complex complex numbers 3 + 4j, 2 – 2j
>>> num1 = 10
>>> type(num1)
<class 'int'>

>>> num2 = -1210


>>> type(num2)
<class 'int'>

>>> var1 = True


>>> type(var1)
<class 'bool'>

>>> float1 = -1921.9


>>> type(float1)
<class 'float'>

Sequence
A Python sequence is an ordered collection of
items, where each item is indexed by an integer.
The three types of sequence data types available
in Python are Strings, Lists and Tuples. We will
learn about each of them in detail in later
chapters. A brief introduction to these data types
is as follows:
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
For example,
>>> str1 = 'Hello Friend'
>>> str2 = "452"
b) List
List is a sequence of items separated by commas
and the items are enclosed in square brackets [ ].
For example,
#To create a list
>>> 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 ( ).
>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
d) Set:
Set is an unordered collection of items separated by
commas and the items are enclosed in curly
brackets { }. A set is similar to list, except that it
cannot have duplicate entries. Once created,
elements of a set cannot be changed.
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))

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. Items in a dictionary 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. The keys are usually strings and their
values can be any data type. In order to access any
value in the dictionary, we have to specify its key in
square brackets [ ].
>>> dict1 = {'Fruit':'Apple', 'Climate':'Cold',
'Price(kg)':120}
>>> print(dict1)
OPERATORS
An operator is used to perform specific
mathematical or logical operation on values. The
values that the operators work on are called
operands.
Arithmetic Operators
O Ope Description Example (Try
pe ratio in Lab)
ra n
to
r
+ Addi Adds the two >>> num1 = 5
tion numeric values >>> num2 = 6
on either side of >>> num1 + num2
the operator 11
>>> str1 = "Hello"
This operator can >>> str2 = "India"
also be used to >>> str1 + str2
concatenate two 'HelloIndia'
strings on either
side of the
operator
- Subt Subtracts the > num1 = 5
racti operand on the >
on right >
from the operand > num2 = 6
on the left >
>
> num1 - num2
>
>
-
1
* Mult Multiplies the two >>> num1 = 5
iplic values on both >>> num2 = 6
ation side of the >>>
operator num1 *
num230
Repeats the item >>> str1 = 'India'
on left of the
o i f o i a >>> str1 * 2
p f i p s
e r e
r s r
a t a
t n
o d
r
string and 'IndiaIndia'
second operand
is an
integer value
/ Divi Divides the > num1 = 8
sion operand on the >
left >
by the operand > num2 = 4
on the right and >
>
returns the > num2 / num1
quotient >
>
0
.
5
% Mod Divides the > num1 = 13
ulus operand on the >
left >
by the operand > num2 = 5
on the right and >
>
returns the > num1 % num2
remainder >
>
3
// Floo Divides the > num1 = 13
r operand on the >
Divi left >
sion
by the operand > num2 = 4
on the right and >
>
returns the > num1 // num2
quotient by >
removing the > num2 // num1
decimal part. It is 3
sometimes also >
>
called integer >
division.
0
** Exp Performs > num1 = 3
onen exponential >
t (power) >
calculation on > num2 = 4
operands. That >
is, >
raise the operand > num1 ** num2
on the left to the >
power of the >
operand on the 8
right 1

Relational Operators

O Ope Descriptio Example (Try


p rati n in Lab)
er on
at
or
= Equ If the values of two >>> num1 ==
= als operands are equal, num2
to then the condition False
is True, otherwise >> str1 ==
it is False str2False
!= Not If values of two >>> num1 !=
equ operands are not num2
al equal, then True
to condition is True, >>> str1 != str2
otherwise it is True
False >>> num1 !=
num3
False
> Gre If the value of the >>> num1 > num2
ater left-side operand is True
tha greater than the >>> str1 >
n value of the right- str2True
side operand, then
condition is True,
otherwise it is
False
< Les If the value of the >>> num1 < num3
s left-side operand is False
tha less than the value >>> str2 <
n of the right- side str1True
operand, then
condition is True,
otherwise it is
False
> Gre If the value of the >>> num1 >=
= ater left-side operand is num2
tha greater than or True
n or equal to the value >>> num2 >=
equ of the right-side num3
al operand, then False
to condition is True, >>> str1 >=
otherwise it is str2True
False
< Les If the value of the >>> num1 <=
= s left operand is less num2
tha than or equal to the False
n or value of the right >>> num2 <=
equ operand, then is num3
al True otherwise it is True
to False >>> str1 <=
str2False
Assignment Operators

O Description Example (Try in


pe Lab)
ra
to
r
= Assigns value from right- >>> num1 = 2
side operand to left-
side operand >>> num2 = num1
>>> num2
2
>>> country = 'India'
>>> country
'India'
+= It adds the value of right- >>> num1 = 10
side operand to the
left-side operand and assigns >>> num2 = 2
the result to the
left-side operand >>> num1 += num2
Note: x += y is same as x = x >>> num1
+y
12
>>> num2
2
>>> str1 = 'Hello'
>>> str2 = 'India'
>>> str1 += str2
>>> str1
'HelloIndia'

-= It subtracts the value of >>> n =


right-side operand from u 10
m
1
the left-side operand and >>> n =2
assigns the result to u
m
2
left-side operand >>> n -=
Note: x -= y is same as x >>> u num
=x-y m 2
1

n
u
m
1
8
*= It multiplies the value of >>> num1 = 2
right-side operand with >>> num2 = 3
the value of left-side >>> num1 *= 3
operand and assigns the
result to left-side operand
Note: x *= y is same as x
=x*y
>
>
>
n
u
m
1
6
>>> a = 'India'
>>> a *= 3
>>> a
'IndiaIndiaIndia'
/= It divides the value of >>> n =6
left-side operand by the u
m
1
value of right-side >>> n =3
operand and assigns the u
m
2
result to left-side operand >>> n /=
Note: x /= y is same as x >>> u num
=x/y m 2
1

n
u
m
1
2.0
% It performs modulus >>> n =7
= operation using two u
m
1
operands and assigns >>> n =3
the result to left-side u
m
2
operand >>> n %=
Note: x %= y is same as >>> u num
x=x%y m 2
1

n
u
m
1
1
// It performs floor division >>> n =7
= using two operands u
m
1
and assigns the result to >>> n =3
left-side operand u
m
2
Note: x //= y is same as x >>> n //=
= x // y u num
m 2
1
>>> n
u
m
1
2
** It performs exponential >>> n =2
= (power) calculation on u
m
1
operators and assigns >>> n =3
value to the left-side u
m
2
operand >>> n **=
Note: x **= y is same as >>> u num
x = x ** y m 2
1

n
u
m
1
8

Logical Operators

O Oper Description Example (Try in


pe ation Lab)
ra
to
r
an Logic If both the >>> True and True
d al operands are True
AND True, then >>> num1 = 10
condition >>> num2 = -20
becomes >>> bool(num1 and
True num2)
True
>>> True and False
False
>>> num3 = 0
>>> bool(num1 and
num3)
False
>>> False and False
False

or Logic If any of the >>> True


al OR two or True
operands are True
True, then >>> True
condition or False
becomes True
True >>> bool(num1 or
num3)
True
>>> False
or False
False
not Logic Used to >>> num1 = 10
al reverse the >>> bool(num1)
NOT logical state True
of its >>> not num1
operand >>> bool(num1)
False

Identity Operators
Op Description Example (Try in
era Lab)
tor
is Evaluates True if the >>> num1 = 5
variables on either side >>> type(num1) is int
of the operator point True
towards the same >>> num2 = num1
memory location and >>>
False otherwise. var1 is id(nu
var2 results to True if
m1)
id(var1) is equal to
id(var2) 14339
20576
>>>
id(nu
m2)
14339
20576
>>> num1 is num2
True
is Evaluates to False if >>> num1 is not num2
the variables on either
not side of the operator False
point to the same
memory location and
True otherwise. var1 is
not var2 results to True if
id(var1) is not equal to
id(var2)

INPUT AND OUTPUT

In Python, we have the input() function for taking the


user input. The input() function prompts the user to
enter data. It accepts all user input as string. The user
may enter a number or a string but the input() function
treats them as strings only. The syntax for input()is:
input ([Prompt])
Prompt is the string we may like to display on the screen
prior to taking the input, and it is optional.
>>> fname = input("Enter your first name: ")Enter your first
name: Arnab
Conditional Statements in Python
Decision-making is as important in any programming
language as it is in life. Decision-making in a programming
language is automated using conditional statements.
Python has four If Statement
The If statement is the most fundamental decision-making statement, in
which the code is executed based on whether it meets the specified
condition.

conditional statements that are used in decision-making:-


1. If the statement

2. If else statement

3. Nested if statement

4. If…Elif ladder

1. If Statement
The If statement is the most fundamental decision-making statement, in
which the code is executed based on whether it meets the specified
condition.

num = 5
if num > 0:
print(num, "is a positive number.")
print("This statement is true.")
output: 5 is a positive number.
This statement is true.

2. If Else Statement

This statement is used when both the true and false parts of a given
condition are specified to be executed. When the condition is true, the
statement inside the if block is executed; if the condition is false, the
statement outside the if block is executed.

num = 5
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
output : Positive or Zero

3. If…Elif..else Statement

In this case, the If condition is evaluated first. If it is false, the Elif


statement will be executed; if it also comes false, the Else statement will
be executed.

num = 7
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
output: Positive number

4. Nested IF Statement

A Nested IF statement is one in which an If statement is nestled inside


another If statement. This is used when a variable must be processed
more than once.

num = 8
if num >= 0:
if num == 0:
print("zero")
else:
print("Positive number")
else:
print("Negative number")
output: Positive number

Python Loops

Python has two primitive loop commands:

1. While loop
2. for loop
While Loop:
In python, while loop is used to execute a block of statements
repeatedly until a given a condition is satisfied. And when the
condition becomes false, the line immediately after the loop in
program is executed.
Syntax :
while expression:
statement(s)
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")

For loop:

A for loop is used for iterating over a sequence (that is either a


list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages,
and works more like an iterator method as found in other object-
orientated programming languages.
With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Example
Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)

You might also like