0% found this document useful (0 votes)
13 views14 pages

Introduction to Python Programming

Chapter 5 introduces Python as a high-level programming language that is interpreted and easy to understand. It covers key concepts such as programming languages, features of Python, execution modes, data types, and operators. Additionally, it explains identifiers, variables, comments, and the distinction between mutable and immutable data types.

Uploaded by

Thanuja.K Thanu
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)
13 views14 pages

Introduction to Python Programming

Chapter 5 introduces Python as a high-level programming language that is interpreted and easy to understand. It covers key concepts such as programming languages, features of Python, execution modes, data types, and operators. Additionally, it explains identifiers, variables, comments, and the distinction between mutable and immutable data types.

Uploaded by

Thanuja.K Thanu
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

Chapter-5 Getting Started with Python

1. What is programming language?


 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.
 High-level programming languages like Python, C++, Visual Basic,
PHP, Java are easier for humans to manage.
 Python uses an interpreter to convert its instructions into machine
language. An interpreter processes the program statements one by one,
translating and executing them until an error is encountered or the
whole program is executed.
 Computers understand the language of 0s and 1s, called machine
language or low-level language.
2. Explain the Features of Python?
 Python is a high-level language. It is a free and open-source language.
 It is an interpreted language, as Python programs are executed by an
interpreter.
 Python programs are easy to understand as they have a clearly defined
syntax and relatively simple structure.
 Python is case-sensitive. For example, NUMBER and number are not
same.
 Python is portable and platform independent, means it can run on various
operating systems and hardware platforms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development.
 Python uses Execute for blocks and nested blocks.

3. Explain the Working modes with Python


To write and execute a Python program, we need to have a Python
interpreter installed on our computer. We can use any online Python interpreter.
The interpreter is also called Python shell.

Figure: Python interpreter or shell


Execution Modes
There are two types to use the Python interpreter:
a) Interactive mode
b) Script mode
Interactive mode:
Definition: Interactive mode is used to user can execute one single line or one
block of code.
Example:

Figure: Python interpreter in interactive mode

Script mode:
. In the script mode, write a Python program in a file, save it, and then use the
interpreter to execute it.
. Python scripts are saved as files with the .py extension.
Example: Write a program to show print statement in script mode.

Figure: Python source code file


PYTHON KEYWORDS
Definition: Keywords are reserved words. Each keyword has a specific
meaning to the Python interpreter.
Table: Python keywords
IDENTIFIERS
Definition: identifiers are names used to identify a variable, function, or other
entities in a program.

Rules of identifiers
• 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 (_).
• An identifier cannot be start with a digit.
• It can be of any length.
• We cannot use special symbols like! @, #, $, %.

VARIABLES
Define: A variable in a program is uniquely identified by a name and value can
be stored in the variable memory location.
Example: 1) message = "I’m going to indu college kottur"
2) SI = “P*T*R/100”
1) Write a program to display values of variables in Python.
message = " I’m going to indu college kottur "
print(message)
Name= “Renuprakash”
Print(Name)
OUTPUT
I’m going to indu college kottur
Renuprakash
2) Write a Python program to find simple interest.
P=10000
T=3
R=2
SI = P*T*R/100
Print(SI)
OUTPUT
600

COMMENTS
Definition: Comments are used to write a remark for user understand or a note
in the source code. Comments are not executed by interpreter.
• In Python, a comment starts with # (hash sign).
Example:
1) Write a Python program to find simple interest.
# To find simple interest.
P=10000 # P means principle amount
T=3 # T means time
R=2 # R means rate
SI = P*T*R/100
Print(SI)
2) Write a Python program to find the sum of two numbers.
#To find the sum of two numbers
num1 = 10
num2 = 20
result = num1 + num2
print(result)
Output:
30
Everything is an Object
Definition: Python treats every value as an object, its meaning the value can be
assigned to some variable.
Example:
>>> num1 = 20
>>> id(num1)
1433920576 # identity of num1
>>> num2 = 30 - 10
>>> id(num2) # Identity of num2 and num1 are same as
1433920576 the Same as both refer to object 20
Data Types
Definition: Data type is an identifies the type of data values a variable can hold
and the operations that can be performed.
TYPES OF DATATYPES IN PYTHON

Figure: Different data types in Python


Number Datatype: Number data type stores numerical values only.

Type/ class Description Examples

int integer numbers –12, –3, 0, 125, 2

Float floating point numbers –2.04, 4.0, 14.23

complex complex numbers 3 + 4j, 2 – 2j


Table: Numeric data types
Integer: The INTEGER data type stores whole numbers it may be positive or
negative numbers.
Examples: –12, –3, 0, 125, 2

Float: The float data types are used to store decimal point number it may be
positive and negative numbers.
Examples: –2.04, 4.0, 14.23

Complex: Complex data types are used to store nested complex number storage
and arithmetic as a built-in data type.
Examples: 3 + 4j, 2 – 2j

Boolean data type


Definition: Boolean data type (bool) is a subtype of integer It is a unique data
type, consisting of two values, True and False.
. Boolean True value is non-zero, non-null and non-empty.
. Boolean False value is zero.
Examples: >>> var1 = True
>>> type(var1)
<class 'bool'>

Sequence
Definition: Sequence is an ordered collection of items, where each item is
indexed by an integer.
3 - types of sequence data types
1) String
2) List
3) Tuple
String: String is a group of characters and enclosed with in single quotation is
called string.
. These characters may be alphabets, digits or special characters including
spaces.
Examples: How to create string
>>> str1 = ‘Renuprakash'
>>>print(str1)
Output:
Renuprakash
List: List is a sequence of items collection separated by commas and the items
are enclosed in square brackets [ ].
Example: How to create list
>>> list1 = [5, 3.4, "20C", 45]
>>> print(list1)
Output:
[5, 3.4, '20C', 45]
Tuple: Tuple is a sequence of items collection separated by commas and items
are enclosed in parenthesis ( ).
Example: How to create tuple.
>>> tuple1 = (10, 20, 3.4, 'a')
>>>print(tuple1)
Output:
(10, 20, 3.4, 'a')
Set: Set is an unordered collection of items separated by commas
and the items are enclosed in curly brackets { }.
Example: How to create Set.
>>> set1 = {10,20,3.14,15,20}
>>>print(set1)
Output:
{10, 20, 3.14, 15,20}
None: None is a special data type it accepts a single value only.
Example: >>> myVar = None
>>>print(myVar)
Output:
None
Dictionary: Dictionary in Python holds data items in key-value pairs.
Items in a dictionary are enclosed in curly brackets { }. Every key is
separated from its value using a colon (:).
Example: >>> dict1 = {'Fruit’: ‘Apple', 'Animal’: ‘Tiger', 'Amount':120}
>>> print(dict1)
Output:
{'Fruit’: ‘Apple', 'Animal’: ‘Tiger', 'Amount':120}
>>> print(dict1['Animal'])
Output:
Tiger

Mutable and Immutable Data Types


Mutable Dtata type: Variables values can be changed after they are created
and assigned are called mutable.
Example:

Immutable Data Types: Variables values cannot be changed after they are
created and assigned are called immutable.
Example:
OPERATORS
Definition: operator is used to perform specific mathematical or logical
operation on values.
Types of operators:
1) Arithmetic operators
2) Relational operators
3) Logical operators
4) Assignment operators
5) Identity operators
6) Membership operators

Arithmetic operators: Arithmetic operators in python refer to symbols that


perform mathematical operations such as addition, subtraction, multiplication,
division, and exponentiation.

Operators Operation Description Examples


+ Addition Adds the two numeric a=3, b=2
values on either side of >>>a+b
the operator >>>3+2
5
-- Subtraction Subtracts the operand >>>a-b
on the right from the >>>3-2
operand on the left 1
* Multiplication Multiplies the two >>>a*b
values on both side of >>>3*2
the operator 6
/ Division Divides the operand on a=2, b=4
the left by the operand >>>a/b
on the right and returns >>>2/4
the quotient 0.5
Modulus Divides the operand on a=3, b=2
% the left by the operand >>>a%b
on the right and returns >>>3%2
the remainder 1
// Floor division Divides the operand on a=13, b=4
the left by the operand >>>a//b
on the right and returns >>>13//4
the quotient by moving 3
the decimal part.
Performs exponential a=2, b=3
Exponential (power) calculation on >>>a**b
** operands. That is, raise >>>2**3
the operand on the left 8
to the power of the
operand on the right

Relational Operators
Relational operator compares the values of the operands on its two side.

Operators Operation Description Examples


If the values of two operands a=2, b=3
== Equals to are equal, then the condition >>>a= =b
is True, otherwise it is False >>>2= =3
False
>>>2= =2
True
!= Not equals to If values of two operands are >>>2! =3
not equal, then condition is True
True, otherwise it is False >>>2! =2
False
If the value of the left-side a=3, b=2
> Greater than operand is greater than the >>>a>b
value of the right-side >>>3>2
operand, then condition is True
True, otherwise it is False >>>2>3
False
If the value of the left-side a=2, b=3
< Less than operand is less than the value >>>a<b
of the right side operand, then >>>2<3
condition is True, otherwise it True
is False >>>3<2
False
If the value of the left-side a=3, b=2
>= Greater than operand is greater than or >>>a>=b
or equal to equal to the value of the right- >>>3>=2
side operand, then condition True
is True, otherwise it is False >>>2>=3
False
If the value of the left operand a=2, b=3
<= Less than or is less than or equal to the >>>a<=b
equal to value of the right operand, >>>2<=3
then is True otherwise it is True
False >>>2>=3
False

Assignment Operators: Assignment operator assigns or changes the value of


the variable on its left.
Operators Description Examples
= Assigns value from right-side operand >>>a=10
to left side operand >>>print(a)
10
+= It adds the value of right-side operand a=3, b=2
to the left-side operand and assigns >>>a=a+b
the result to the left-side operand >>>a=3+2
Note: a +=b is same as a = a + b a=5
-= It subtracts the value of right-side a=3, b=2
operand from the left-side operand >>>a=a-b
and assigns result to left-side operand >>>a=3-2
Note: a -= b is same as a = a - b a=1
*= It multiplies the value of right-side a=2, b=3
operand with the value of left-side >>>a=a*b
operand and assigns the result to left- >>>2*3
side operand 6
Note: a *= b is same as a = a * b
/= It divides the value of left-side a=4, b=2
operand by the value of right-side >>>a=a/b
operand and assigns the result to left- >>>4/2
side operand 2
Note: a /= b is same as a = a / b
%= It performs modulus operation using a=3, b=2
two operands and assigns the result to >>>a=a%b
left-side operand >>>3/2
Note: a %= b is same as a = a % b 1
//= It performs floor division using two a=7, b=3
operands and assigns the result to left- >>>a=a//b
side operand >>>a=7//3
Note: a //= b is same as a = a // b 2
**= It performs exponential (power) a=2, b=3
calculation on operators and assigns >>>a=a**b
value to the left-side operand >>>a=2**3
Note: x **= y is same as x = x ** y 8
Logical Operators
. There are three logical operators supported by Python. These operators (and,
or, not) are to be written in lower case only.
. The logical operator evaluates to either True or False.
Operators Operation Description Examples
and Logical AND If both the operands are >>>True and True
True, then condition True
becomes True >>>True and False
False
or Logical OR If any of the two operands >>>True or True
are True, then condition True
becomes True >>>True or False
False
not Logical not Used to reverse the logical a=0 a=1
state of its operand True False

Identity Operators
Identity operators are used to determine whether the value of a variable is of a
certain type or not.
Operators Description Examples
Is Evaluates True if the variables on either >>> num1 is num2
side of the operator point towards the same True
memory location and False otherwise. var1 is
var2 results to True if id(var1) is equal to
id(var2)
is not Evaluates to False if the variables on >>> num1 is not
either side of the operator point to the same num2
memory location and True otherwise. var1 False
is not var2 results to True if id(var1) is not
equal to id(var2)
Membership Operators: Membership operators are used to check if a value is
a member or not.
Operator Description Examples
Returns True if the variable/value is found >>> a = [1,2,3]
In in the specified sequence and otherwise >>> 2 in a
False True
>>> 5 in a
False

Returns True if the variable/value is not >>> a = [1,2,3]


not in found in the specified sequence and >>> 10 not in a
otherwise False True
>>> 1 not in a
False
EXPRESSIONS

Expressions are combinations of values, variables, operators, and function calls


that are interpreted and evaluated by the Python interpreter to produce a result.

Example: x=5
y = 10
if x < y:
print ("x is less than y")
else:
print ("x is not less than y")
Output:
x is less than y

Precedence of Operators

The precedence operator is in which operator is highest value for that operator
determine the first.

Order of Operators Description


Precedence
1 ** Exponentiation (raise to the power)
2 ~ ,+, - Complement, unary plus and
unary minus
3 * ,/, %, // Multiply, divide, modulo and floor
division
4 +, - Addition and subtraction
5 <= , < , > , >=, == , != Relational and Comparison
operators
6 =, %=, /=, //=, -=, +=, Assignment operators
*=, **=
7 is, is not Identity operators
8 in, not in
9 not
10 and Logical operators
11 or
Example1: How will Python evaluate the following expression?
1) 20 + 30 * 40
Solution: = 20 + (30 * 40) #precedence of * is more than that of +.
= 20 + 1200
= 1220
Example2: How will Python evaluate the following expression?
2) 20 - 30 + 40
Solution: = (20 – 30) + 40 # two operators (–) and (+) have equal
= -10 + 40 precedence
= 30
Example3: How will Python evaluate the following expression?
3) (20 + 30) * 40
Solution: = (20 + 30) * 40 # using parenthesis (), is more precedence
= 50 * 40 Than o + & *.
= 2000
STATEMENT
Definition: statement is an instruction that instruction can be execute by Python
interpreter.
Example: To find power of a number?
>>> x = 4 #assignment statement
>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
Output:
4 64
Input and Output
a program needs to interact with the users to get some input data or information
from the end user and process it to give the desired output.

. input ( ) function for taking the user input.


. print ( ) function to output data to standard output device on the screen.
Example:1
#function int () to convert string to integer
>>> age = int (input ("Enter your age:"))
>>>print(age)
Output:
Enter your age: 19
Example:2
your_name = input("Enter your name:")
your_age = int(input("Enter your age:"))
print("Hi! ",your_name," and your age is ", your_age)
Output:
Enter your name: Renuprakash
Enter your age: 34
Hi! Renuprakash and your age is: 34
TYPE CONVERSION
Type conversion is used to refers the conversion from one data type to another
data type.
Two types of type conversion
1) Implicit conversion
2) Explicit conversion
Implicit conversion
In certain situations, Python automatically converts one data type to another.
This is known as implicit type conversion.
Example:1
integer_number = 123
float_number = 1.23
new_number = integer_number + float_number
# display new value and resulting data type
print("Value:",new_number)
print("Data Type:",type(new_number))
Output:
Value: 124.23
Data Type: <class 'float'>

Explicit conversion
In Explicit Type Conversion, users convert the data type of an object to required
data type.
Example:1
num_string = '12'
num_integer = 23
num_string = int(num_string) #string value converted into integer
num_sum = num_integer + num_string
print("Sum of two numbers is:",num_sum)
Output:
Sum of two numbers is: 35

DEBUGGING
Debugging is the process of identifying and removing such mistakes in the
program is called debugging.
Types of Errors
1) Syntax errors
2) Logical errors
3) Runtime errors
Syntax Errors
syntax error in python interpreter shows error messages and stops the
execution there. Errors such as missing the spelling, (, “, {, [.
Example:
10 = x
print(x)
Logical Errors
Logical errors in python when the code runs without any syntax error, but error
occur at the run time produce an incorrect result. Errors such as missing the
operators like + , - , >.
Examples:
x = 10
y = 20
if x>y:
print("x is less than y")
else:
print("y is less than x")
Runtime Error

Runtime error occurs when your syntax is correct but the Python interpreter is
still not able to run the code due to an error. runtime error like “division by
zero”.
Examples:
x = 10
y=0
print(x/y)

You might also like