0% found this document useful (0 votes)
2 views17 pages

Chapter 5 Getting Started With Python_compressed

This document introduces Python programming, covering its features, execution modes, character set, tokens, data types, and operators. It explains concepts such as variables, dynamic typing, and the distinction between mutable and immutable data types. Additionally, it provides examples of various data types including numbers, sequences, sets, and mappings, along with operators used in Python.

Uploaded by

littlechef482
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)
2 views17 pages

Chapter 5 Getting Started With Python_compressed

This document introduces Python programming, covering its features, execution modes, character set, tokens, data types, and operators. It explains concepts such as variables, dynamic typing, and the distinction between mutable and immutable data types. Additionally, it provides examples of various data types including numbers, sequences, sets, and mappings, along with operators used in Python.

Uploaded by

littlechef482
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
You are on page 1/ 17

CLASS XI – COMPUTER SCIENCE

Chapter -5 GETTING STARTED WITH PYTHON

Introduction to Python

Program: An ordered set of instructions to be executed by a computer to carry out a specific task is
called a program.

Programming Language: The language used to specify the set of instructions to the computer is called
a programming language.

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 ex: NUMBER and number are not same in Python.
 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. Many popular web services and applications are built
using Python.
 Python uses indentation for blocks and nested blocks.

Execution Modes:

 Interactive Mode : It allows execution of individual statement instantaneously


 Script Mode : It allows to write more than one instruction in a file called Python source code
file. Python scripts are saved as files where the file name has extension ―.py‖.

Executing “Hello World” Program in Interactive Mode:

Working in the interactive mode is convenient for testing a single line code for instant execution.

Executing “Hello World” Program in Script Mode:


Python Character Set:
Character set is a set of valid characters that a language can recognize. A character represents any letter,
digit or any other symbol.

 Letters A – Z, a – z
 Digits 0 – 9
 Special Symbols ‖ ' l ; : ! ~ @ # $ % ^ ` & * ( ) _ + – = { } [ ] \ ./ < >
 White spaces Blank space, tabs, carriage return, newline, formfeed
 Other characters Python can process all ASCII and Unicode characters

Python Tokens:
The smallest individual unit in a program is known as a Token. Python has following Tokens:

(i) Keywords (ii) Identifiers (iii) Literals (iv) Operators (v) Punctuators

(i) Keywords: Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter.

(ii) Identifiers : Identifiers are names used to identify a variable, function or other entities
Rules for Naming Python Identifiers:
 It cannot be a reserved Python keyword.
 It should not contain white space.
 It can be a combination of A-Z, a-z, 0-9, or underscore.
 It should start with an alphabet character or an underscore ( _ ).
 It should not contain any special character other than an underscore ( _ ).
 It can be of any length, however, it is preferred to keep it short and meaningful.

 Book Ex : Page No.115. Q.No.1:

Valid Identifiers Invalid Identifiers & Reason


Total_Marks Serial_no. (Having a special character)
st
_Percentage 1 _Room (Started with digit)
Hundred$ (Having a special character)
Total Marks (Having a special character)
Total-marks (Having a special character)
True (Keyword)
(iii) Literals: Literals are data items that have a fixed value. Python allows several kind of literals.

(a) String literals (b) Numeric literals (c) Boolean literals (d) Special literal None
(e) Literal collections

(a) String literals : The text enclosed in quotes forms a string literal.
Ex: ―Apple‖, ‗12345‘, ‘‘‘ Hi‘‘‘

(b) Numeric Literals: It is a notation representing a fixed numeric value in the code. It has integer
literals, floating point literals and complex literals.
(c) Boolean Literals: It is used to represent one of the two Boolean values i.e., True or False
(d) Special Literal None: It is used to indicate absence of value.
(e) Literal collections : It is used to represent collections of values of the same or different data
types.

(iv) Operators: These are the tokens that trigger some computation / action when applied to variables
and other objects in an expression.
 Unary Operator : It is an operator that acts on a single operand. Ex : +a
 Binary Operator: It require two operands to operate upon. Ex: a + b
Python divides the operators in the following groups:
 Arithmetic operators
 Relational operators
 Assignment operators
 Logical operators
 Identity operators
 Membership operators
(v) Punctuators : These are the symbols that used in Python to organize the structures, statements, and
expressions. Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = ,

Variables : Named labels, whose values can be used and processed during program run are called
variables. Variables in Python refer to an object – an item or element that is stored in the memory. Ex:
name = ‗Davis‘ # string
age = 16 # integer
mark = 87.5 # float
Variable declaration is implicit in Python, means variables are automatically declared and defined when
they are assigned a value for the first time.

Dynamic Typing : A variable pointing to a value of a certain type, can be made to point to a value/object
of different type. Ex:
x = 100
print (x)
x = "Happy Day"
print (x)
Above code will yield the output as :

100
Happy Day

lvalue : expressions that can come on the lhs (left hand side) of an assignment.
rvalue : expressions that can come on the rhs (right hand side) of an assignment.

We can say: A = 20 , but we cannot say: 20 = A, which is wrong

Comments:
 Comments are the additional readable information, which is read by the programmers but ignore
by Python interpreter.
 Comments begin with symbol ― # ‖ and end with the end of physical line.
 Multi-line comments are triple-quoted : triple apostrophe (‘‘‘) or triple-quotes (‖‖‖)

Ex: #Program to display welcome msg


print ( ― Welcome to the world of Python ― )

Above code will yield the output as :


Welcome to the world of Python

DATA TYPES

Every value belongs to a specific data type in Python. Data type identifies the type of data which a
variable can hold and the operations that can be performed on those data.
Python has five data types –
1. Numbers
2. Sequences
3. Sets
4. None
5. Mapping

1. 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, 123, 2
float floating point numbers -2.04, 4.0, 14.23
complex complex numbers 3 + 4i, 2 - 2i
 Integer numbers are whole numbers with no decimal places. They can be positive or negative
numbers. For example, 0, 1, 2, 3, -1, -2, and -3 are all integers. Usually, we‘ll use positive integer
numbers to count things. In Python, the integer data type is represented by the int class:

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

 Floating-point numbers, or just float, are numbers with a decimal place. For
example, 1.0 and 3.14 are floating-point numbers. We can also have negative float numbers, such as -
2.75. In Python, the name of the float class represents floating-point numbers:

>>> type(1.0)
<class 'float'>OLEAN

 Complex Numbers - Python has a built-in type for complex numbers. Complex numbers are
composed of real and imaginary parts. They have the form a + bi, where a and b are real numbers,
and i is the imaginary unit. In Python, we‘ll use a j instead of an i. For example:

>>> type(2 + 3j)


<class 'complex'>

In this example, the argument to type() may look like an expression. However, it‘s a literal of a complex
number in Python. If you pass the literal to the type() function, then you‘ll get the complex type back.

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.

EXAMPLES :-
>>>bool(0
) False
>>>bool(1
) True
>>>bool(‗
‗) False
>>>bool(-
25) True
>>>bool(25)
True
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, etc. For this, Python provides sequence data types like
Strings, Lists, Tuples, and mapping data type Dictionaries.
2. SEQUENCE - An ordered group of things, each of which is identified by an integer index, is referred
to as a Python sequence. Strings, Lists, and Tuples are the three different forms of sequence data types
that are available in Python.

 String - A string is a collection of characters. These characters could be letters, numbers, or other
special characters like spaces. Single or double quotation marks are used to surround string values
for example, 'Hello' or "Hello".

>>> str1 = 'Hello Friend'


>>> str2 = "452"

 List - List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ]. example list1 = [5, 3.4, "New Delhi", "20C", 45]

#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]

 Tuple - A tuple is a list of elements enclosed in parenthesis and separated by commas ().
Compared to a list, where values are denoted by brackets [], this does not. We cannot alter the
tuple once it has been formed. example tuple1 = (10, 20, "Apple", 3.4, 'a')

#create a tuple tuple1


>>> tuple1 = (10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print(tuple1)
(10, 20, "Apple", 3.4, 'a')
3. SET - A set is a group of elements that are not necessarily in any particular order and are enclosed in
curly brackets. The difference between a set and a list is that a set cannot include duplicate entries. A
set's components are fixed once it is constructed.
Example: set1 = {10,20,3.14,"New Delhi"}

4. NONE - A unique data type with only one value is called None. It is employed to denote a situation's
lack of worth. None is neither True nor False, and it does not support any special operations (zero).
Example: myVar = None

5. MAPPING - Python has an unordered data type called mapping. Python currently only supports the
dictionary data type as a standard mapping data type.
 Dictionary - Python's dictionary stores data elements as key-value pairs. Curly brackets are used to
surround words in dictionaries. Dictionary use enables quicker data access.

Ex: dict1 = {'Fruit':'Apple', 'Climate': 'Cold', 'Price(kg)':120}


#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 DATA TYPES


Once a variable of a certain data type has been created and given values, Python does not enable us to
modify its values. Mutable variables are those whose values can be modified after they have been created
and assigned. Immutable variables are those whose values cannot be modified once they have been
created and assigned.
PYTHON OPERATORS Types of Operators in Python

In Python programming, Operators in general are used to perform 1. Arithmetic Operators


2. Relational Operators
operations on values and variables. These are standard symbols 3. Logical Operators
used for logical and arithmetic operations. 4. Assignment & Augmented
 OPERATORS: These are the special symbols. Eg- + , * , /, etc. Assignment Operators
5. Identity Operators
 OPERAND: It is the value on which the operator is applied.
6. Membership Operators

1. ARITHMETIC OPERATORS- Python Arithmetic


operators are used to perform basic mathematical operations like addition, subtraction,
multiplication and division. In Python 3.x, the result of division is a floating-point. To obtain an
integer result in Python 3.x, floor division (//) is used.

Operator Description
+ Addition operator- Add operands on either side of the operator.
– Subtraction operator – Subtract right hand operand from left hand operand.
* Multiplication operator – Multiply operands on either side of the operator.
/ Division operator – Divide left hand operand by right hand operand.
% Modulus operator – Divide left hand operand by right hand operand and return remainder.
** Exponent operator – Perform exponential (power) calculation on operands.
Floor Division operator – The division of operands where the result is the quotient in which
//
the digits after the decimal point are removed.

Example of Arithmetic Operators in Python:


# Variables
Output
a = 15
b=4 Addition: 19
Subtraction: 11
print("Addition:", a + b) # Addition Multiplication: 60
print("Subtraction:", a - b) # Subtraction Division: 3.75
print("Multiplication:", a * b) # Multiplication Floor Division: 3
Modulus: 3
print("Division:", a / b) # Division
Exponentiation: 50625
print("Floor Division:", a // b) # Floor Division
print("Modulus:", a % b) # Modulus
print("Exponentiation:", a ** b) # Exponentiation
2. RELATIONAL OPERATORS
In Python, Relational operators compares the values. It either returns True or False according to the
condition.

Operator Description
== Check if the values of two operands are equal.
!= Check if the values of two operands are not equal.
<> Check if the value of two operands are not equal (same as != operator).
> Check if the value of left operand is greater than the value of right operand.
< Check if the value of left operand is less than the value of right operand.
>= Check if the value of left operand is greater than or equal to the value of right operand.
<= Check if the value of left operand is less than or equal to the value of right operand.

Ex: a = 13
b = 33 Output
print(a > b) False
print(a < b) True
print(a = = b) False
True
print(a != b)
False
print(a >= b) True
print(a <= b)

3. LOGICAL OPERATORS - Python Logical operators perform Logical AND, Logical


OR and Logical NOT operations. It is used to combine conditional statements.

Operator Description
Logical AND operator- If both the operands are true (or non-zero), then condition
and
becomes true.
Logical OR operator- If any of the two operands is true (or non-zero), then condition
or
becomes true.
Logical NOT operator- The result is reverse of the logical state of its operand. If the
not
operand is true (or non-zero), then condition becomes false.

Example of Logical Operators in Python:


Output
a = True False
b = False True
print(a and b) False
print(a or b)
print(not a
4. ASSIGNMENT & AUGMENTED ASSIGNMENT OPERATORS
Python Assignment operators are used to assign values to the variables. This operator is used to assign
the value of the right side of the expression to the left side operand. Augmented assignment is the
combination, in a single statement, of a binary operation and an assignment statement. An augmented
assignment expression like x+=l can be rewritten as x=x+1.

Operator Description

= Assignment operator- Assigns values from right side operand to left side operand.
Augmented assignment operator- It adds right side operand to the left side operand and
+=
assign the result to left side operand.
Augmented assignment operator- It subtracts right side operand from the left side operand
-=
and assign the result to left side operand.
Augmented assignment operator- It multiplies right side operand with the left side operand
*=
and assign the result to left side operand.
Augmented assignment operator- It divides left side operand with the right side operand
/=
and assign the result to left side operand.
Augmented assignment operator- It takes modulus using two operands and assign the
%=
result to left side operand.
Augmented assignment operator- Performs exponential (power) calculation on operands
**=
and assigns value to the left side operand.
Augmented assignment operator- Performs floor division on operators and assigns value to
//=
the left side operand.

Example of Assignment Operators in Python:

a = 10 Output
b=a
print(b) 10
b += a 20
print(b) 10
b -= a 100
print(b) 102400
b *= a
print(b)
b <<= a
print(b)

5. IDENTITY OPERATORS IN PYTHON - In Python, is and is not are the identity operators both
are used to check if two values are located on the same part of the memory. Two variables that are
equal do not imply that they are identical.

is True if the operands are identical


is not True if the operands are not identical
Example of Identity Operators in Python:
a = 10 Output
b = 20 True
c=a True
print(a is not b)
print(a is c)

6. MEMBERSHIP OPERATORS - In Python, in and not in are the membership operators that are
used to test whether a value or variable is in a sequence.

in True if value is found in the sequence


not in True if value is not found in the sequence

Example of Membership Operators in Python:


x = 24 Output
y = 20
x is NOT present in given list
list = [10, 20, 30, 40, 50]
y is present in given list
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")

EXPRESSIONS

An expression is defined as a combination of constants, variables and operators. An expression always


evaluates to a value. A value or a standalone variable is also considered as an expression but a standalone
operator is not an expression. Some examples of valid expressions are given below.
(i) num – 20.4
(ii) 23/3 -5 * 7(14 -2)
(iii) 3.0 + 3.14
(iv) "Global"+"Citizen"

PRECEDENCE OF OPERATORS IN PYTHON

In Python, Operator precedence determine the priorities of the operator. Operator Precedence in
Python is used in an expression with more than one operator with different precedence to determine
which operation to perform first.
 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.

Example 1:
expr = 10 + 20 * 30 Output
print(expr)
name = "Alex" 610
age = 0 Hello! Welcome.
if name == "Alex" or name == "John" and age >= 2:
print("Hello! Welcome.")
else:
print("Good Bye!!")

Example 2: Output
print(100 / 10 * 10) 100.0
print(5 - 2 + 3) 6
print(5 - (2 + 3)) 0
print(2 ** 3 ** 2) 512

 Code to implement basic arithmetic operations on integers


num1 = 5
num2 = 2
sum = num1 + num2 Output
difference = num1 - num2 Sum: 7
product = num1 * num2 Difference: 3
quotient = num1 / num2 Product: 10
remainder = num1 % num2 Quotient: 2.5
print("Sum:", sum) Remainder: 1
print("Difference:", difference)
print("Product:", product)
print("Quotient:", quotient)
print("Remainder:", remainder)
Q1. EVALUATE THE FOLLOWING EXPRESSIONS.

a) 20 + 30 * 40

Solution:
#precedence of * is more than that of +
= 20 + 1200 #Step 1
= 1220 #Step 2

b) (20 + 30) * 40

Solution:
= (20 + 30) * 40 # Step 1
#using parenthesis(), we have forced precedence of + to be more than that of *
= 50 * 40 # Step 2
= 2000 # Step 3

c) 15.0 / 4.0 + (8 + 3.0)

Solution:
= 15.0 / 4.0 + (8.0 + 3.0) #Step 1
= 15.0 / 4.0 + 11.0 #Step 2
= 3.75 + 11.0 #Step 3
= 14.75 #Step 4

Q2. Find the python expression for the following.

STATEMENT
In Python, a statement is a unit of code that the Python interpreter can execute.
Example :
>> x = 4 #assignment statement
>> cube = x ** 3 #assignment statement
>>print (x, cube) #print statement
4 64
INPUT AND OUTPUT

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. It accepts all user input (whether alphabets, numbers or
special character) as string. The syntax for input() is:
variable = input([Prompt])

Prompt is the string we may like to display on the screen prior to taking the input, but it is optional.

Example:
>>> name = input("Enter your first name: ")
Enter your first name: Arnab
>>> age = input("Enter your age: ")
Enter your age: 19

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)
Example Output
print("Hello") Hello
print(10*2.5)
25.0

TYPE CONVERSION

In Python, the process of converting a data type value, be it an integer, string, float, etc, into another data
type is known as type conversion. This type-conversion is of two types, which are:
 EXPLICIT CONVERSION
 IMPLICIT CONVERSION

EXPLICIT CONVERSION:
 Explicit conversion done explicitly by programmer.
 It is forced Or Enforced by programmer.
 Explicit conversion, also called as type casting.
Example: Explicit type conversion from int to float
num1 = 10 Output:
num2 = 20
30
num3 = num1 + num2
print(num3) int
print(type(num3)) 30.0
num4 = float(num1 + num2)
Float
print(num4)
print(type(num4))
IMPLICIT CONVERSION:
 Conversion done by Python interpreter.
 It is not instructed by the programmer.

Example:#Implicit conversion from integer to float


Output:
num1 = 10 #num1 is an integer
30.0
num2 = 20.0 #num2 is a float
sum1 = num1 + num2 #sum1 is float float
print(sum1)
print(type(sum1)) #sum1 will be in float
Note: Here, the float value is not converted to an integer, due to type promotion that allows
performing operations by converting data into a wider-sized datatype without any loss of information.

ERRORS

Debugging - 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.
Due to errors, a program may not execute or may generate wrong output.

1. SYNTAX ERRORS
2. LOGICAL ERRORS
3. RUN TIME ERRORS

SYNTAX ERRORS:
 Occurs when rules of a programming language are misused.

 That is when a grammatical rule of python is violated. 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. If any syntax error is present, the interpreter shows error message(s) and stops the
execution there. Such errors need to be removed before execution of the program.
Example:
print (―Welcome to python‖
This is syntax error, where ) is missing.

LOGICAL ERRORS:
 Bug, also called semantic error.
 Occur due to programmer‘s mistake in logic.
 A logical error produces an undesired output or Wrong output.
Example:
#Average of two numbers
Num1=10
Num2=12
Avg=Num1+Num2/2
print(Avg)

This program will produce wrong output as 16.


#Average of two numbers
Num1=10
Num2=12
Avg=(Num1+Num2)/2 #Wrong logic corrected here
print(Avg)

RUN TIME ERRORS:

 Occurs during the Execution (Runtime) of the programs. Runtime error is when the statement is
correct syntactically, but the interpreter cannot execute it. A runtime error causes abnormal
termination and do not appear until the run time. Runtime error won‘t have syntax errors.

 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‖.

Example
#Division of two numbers
num1 = 10.0
num2 = int(input("Enter the number2 "))
print(num1/num2)
#if user inputs a string or a zero, it leads to runtime error
Error:
Zero Division Error: float division by zero

Q. Find and correct the syntax errors: Correction:


a=10 a=10
b= 20 b=20
if (a==b); if (a==b):
print(―Both the numbers are equal‖) print(―Both the numbers are equal‖)
else else
print(―Both the numbers are equal‖) print(―Both the numbers are equal‖)

Error : missing colon (:)

You might also like