0% found this document useful (0 votes)
5 views10 pages

Chapter No 5 - Getting Started With Python

Uploaded by

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

Chapter No 5 - Getting Started With Python

Uploaded by

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

Computer Science – Class XI 2024 -25

Chapter – No: 05
Getting Started with Python

 Introduction:
“Computer programming is an art, because it applies accumulated knowledge to the world, because it
requires skill and ingenuity, and especially because it produces objects of beauty. A programmer who
subconsciously views himself as an artist will enjoy what he does and will do it better.”

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.

Computers understand the language of 0s and 1s which is called machine language or low level
language. It is difficult for humans to write or comprehend instructions using 0s and 1s. This led to the
advent of high-level programming languages like Python, C++, Visual Basic, PHP, Java that are easier
to manage by humans but are not directly understood by the computer.

A program written in a high-level language is called source code and code generated by compiler or
interpreter is called object code.

“Python is an object-oriented, high-level programming language with


dynamic semantics developed by Guido Van Rossum in 1991.”

 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 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.

 Working with Python:


 To write and run (execute) a Python program, programmer need to have a Python Interpreter
installed on their computer or they can use any Online Python Interpreter.
 The interpreter is also called Python shell.
 The symbol >>> is the Python prompt, which indicates that the interpreter is ready to take
instructions. Programmer can type commands or statements on this prompt to execute them using a
Python interpreter.
 Execution Modes

Presidency PU College, Kempapur, Hebbal, Bangalore Page 1


Computer Science – Class XI 2024 -25

There are two ways to use the Python interpreter:


a) Interactive mode
b) Script mode
 Interactive mode allows execution of individual statement instantaneously.
 Script mode allows us to write more than one instruction in a file called python source code
file that can be executed.
(A) Interactive Mode: To work in the interactive mode, we can simply type a python statement on the
>>> prompt directly. As soon as programmer presses 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 again.

(B) Script Mode: In the script mode, programmer 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”.
By default, the Python scripts are saved in the Python installation folder.
To execute a script, programmer can either:
a) Type the file name along with the path at the prompt. For example, if the
name of the file is prog5-1.py, we type prog5-1.py. Programmer can
otherwise open the program directly from IDLE.
b) While working in the script mode, after saving the file, click [Run]->[Run
Module] from the menu.

 Python Keywords:
Keywords are reserved words. Each keyword has a specific meaning to the Python
interpreter, and programmer can use a keyword in our program only for the purpose
for which it has been defined. As Python is case sensitive, keywords must be written
exactly as given in the below table.
Python keywords

False class finally is return break


None continue For lambda Try except
True def From nonlocal while in
and del global not with
as elif If or yield
assert else import pass raise

 Identifiers:
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:
• 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 start with a digit.
• It can be of any length. (However, it is preferred to keep it short and meaningful).
• keywords cannot be used as identifiers
• Programmer cannot use special symbols like !, @, #, $, %, etc., in identifiers.
For example, to find the average of marks obtained by a student in three subjects, we can choose the

Presidency PU College, Kempapur, Hebbal, Bangalore Page 2


Computer Science – Class XI 2024 -25

identifiers as marks1, marks2, marks3 and avg rather than a, b, c, or A, B, C.


avg = (marks1 + marks2 + marks3)/3
Similarly, to calculate the area of a rectangle, we can use identifier names, such as area, length, breadth
instead of single alphabets as identifiers for clarity and more readability.
area = length * breadth

 Variables:
A variable in a program is uniquely identified by a name (identifier). Variable in Python refers to an
object — an item or element that is stored in the memory. Value of a variable can be a string (e.g.,
‘b’, ‘Global Citizen’), numeric (e.g., 345) or any combination of alphanumeric characters (CD67).
In Python programmer can use an assignment statement to create new variables and assign specific
values to them.

Examples: regno=2501
gender = 'M'
name = "Vikram Gupta"
percentage = 98.76

 Comments:
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. They are used primarily to document the meaning and
purpose of source code and its input and output requirements.

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.

 Everything is an Object :
Python treats every value or data item whether numeric, string, or other type as an object in the sense
that it can be assigned to some variable or can be passed to a function as an argument.

Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of
that object.

This ID is similar to the memory address of the object. The function id() returns the identity of an
object.

Note:
In the context of Object Oriented Programming (OOP), objects are a representation of the real world,
such as employee, student, vehicle, box, book, etc. In any object oriented programming language like
C++, JAVA, etc., each object has two things associated with it: (i) data or attributes and (ii) behavior
or methods. Further there are concepts of class and class hierarchies from which objects can be
instantiated.

Python also comes under the category of object oriented programming. However, in Python, the
definition of object is loosely casted as some objects may not have attributes or others may not have
methods.

 Data Types:

Presidency PU College, Kempapur, Hebbal, Bangalore Page 3


Computer Science – Class XI 2024 -25

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.

1. Number: Number data type stores numerical values only. It is further classified into three
different types: int, float and complex.

Note: In Python programming to determine the data type of the variable programmer usees built-in
function type().

Example:
>>> num1 = 10
>>> type(num1)
<class 'int'>

2. 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.
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 marks
(e.g., ‘Hello’) or in double quotation marks (e.g.,“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.

Presidency PU College, Kempapur, Hebbal, Bangalore Page 4


Computer Science – Class XI 2024 -25

For Example:
>>> str1 = 'Hello Friend'
>>> str2 = "452"
We cannot perform numerical operations on strings, even
when the string contains a numeric value, as in str2.
(B) List - List is a sequence of items separated by commas and the items
are enclosed in square brackets [ ].
Example:
#To create a list
>>> list1 = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list list1
>>> print(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 ( ). This is unlike list, where
values are enclosed in brackets [ ].
Once created, we cannot change the tuple.
Example:
#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: 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.

4. None: None is a special data type with a single value. It is used to signify the absence of value in
a situation. None supports no special operations, and it is neither same as False nor 0 (zero).

5. 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 [ ].

 Mutable and Immutable Data Types:


Variables whose values can be changed after they are created and assigned are called mutable.
Variables whose values cannot be changed after they are created and assigned are called immutable.
When an attempt is made to update the value of an immutable variable, the old variable is destroyed and
a new variable is created by the same name in memory.
Python data types can be classified into mutable and immutable

Presidency PU College, Kempapur, Hebbal, Bangalore Page 5


Computer Science – Class XI 2024 -25

 Operators: An operator is used to perform specific mathematical or logical operation on values.


The values that the operators work on are called operands.

For example, in the expression 10 + num, the value 10, and the
variable num are operands and the + (plus) sign is an
operator.

Python supports several kinds of operators


1. Arithmetic Operators: Python supports arithmetic operators that are used to perform the four
basic arithmetic operations as well as modular division, floor division and exponentiation.
Operator Operation Description
+ Addition Adds the two numeric values on either side of the operator.
- Subtraction Subtracts the operand on the right from the operand on the left.
* Multiplication Multiplies the two values on both side of the operator.
Divides the operand on the left by the operand on the right and
/ Division
returns the quotient.
Divides the operand on the left by the operand on the right and
% Modulus
returns the remainder.
Divides the operand on the left by the operand on the right and
// Floor Division returns the quotient by removing the decimal part. It is sometimes
also called integer division.
Performs exponential (power) calculation on operands. That is,
** Exponent raise the operand on the left to the power of the operand on the
right.

2. Relational Operators: Relational operator compares the values of the operands on its either
side and determines the relationship among them.
Operator Operation Description
If the values of two operands are equal, then the condition is
== Equals to
True, otherwise it is False.
If values of two operands are not equal, then condition is True,
!= Not equal to
otherwise it is False.
If the value of the left-side operand is greater than the value of
> Greater than the right- side operand, then condition is True, otherwise it is
False.
If the value of the left-side operand is less than the value of the
< Less than
right-side operand, then condition is True, otherwise it is False.
Greater than If the value of the left-side operand is greater than or equal to
>= or the value of the right-side operand, then condition is True,
equal to otherwise it is False.
<= Less than If the value of the left operand is less than or equal to the value

Presidency PU College, Kempapur, Hebbal, Bangalore Page 6


Computer Science – Class XI 2024 -25

or equal to of the right operand, then is True otherwise it is False.


3. Assignment Operators: Assignment operator assigns or changes the value of the variable on its left.
Operator Description
= Assigns value from right-side operand to left-side operand.
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
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
It multiplies the value of right-side operand with the value of left-
*= side operand and assigns the result to left-side operand.
Note: x*=y is same as x = x * y
It divides the value of left-side operand by the value of right-side
/= operand and assigns the result to left-side operand.
Note: x/=y is same as x = x / y
It performs modulus operation using two operands and assigns the
%= result to left-side operand.
Note: x %= y is same as x = x % y
It performs floor division using two operands and assigns the result
//= to left-side operand.
Note: x//=y is same as x = x // y
It performs exponential (power) calculation on operators and
**= assigns value to the left-side operand.
Note: x**=y is same as x = x ** y

4. 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 based on the logical operands on either side.
Operator Operation Description
and Logical AND If both the operands are True, then condition becomes True
or Logical OR If any of the two operands are True, then condition becomes True
not Logical NOT Used to reverse the logical state of its operand

5. Identity Operators: Identity operators are used to determine whether the


value of a variable is of a certain type or not. Identity operators
can also be used to determine whether two variables are
referring to the same object or not.
There are two identity operators: is and is not
Operator Description
Evaluates True if the variables on either side of the operator point
is towards the same memory location and False otherwise. var1 is var2
results to True if id(var1) is equal to id(var2)
Evaluates to False if the variables on either side of the operator point
is not to the same memory location and True otherwise. var1 is not var2
results to True if id(var1) is not equal to id(var2)

6. Membership Operators: Membership operators are used to check if a value is a member of the
given sequence or not.
Operator Description
in Returns True if the variable/value is found in the specified
sequence and False otherwise.
not in Returns True if the variable/value is not found in the specified
sequence and False otherwise.

Presidency PU College, Kempapur, Hebbal, Bangalore Page 7


Computer Science – Class XI 2024 -25

Note: Refer Textbook for the examples for each operator.


 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) 100 (iv) 3.0 + 3.14
(ii) num (v) 23/3 -5 * 7(14 -2)
(iii) num – 20.4 (vi) "Global" + "Citizen"

 Precedence of Operators: Evaluation of the expression is based on precedence of operators.


When an expression contains different kinds of operators, precedence
determines which operator should be applied first. Higher precedence
operator is evaluated before the lower precedence operator.

The following table lists precedence of all operators from highest to lowest.

 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: Sometimes, a program needs to interact with the user’s to get some input data
or information from the end user and process it to give the desired output.

In Python, programmers use input () function and print () function to perform input and output
operations.

 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 user may like to display on the screen prior to taking the
input, and it is optional.
Presidency PU College, Kempapur, Hebbal, Bangalore Page 8
Computer Science – Class XI 2024 -25

The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it to
the variable on left-hand side of the assignment operator (=). Entering data for the input function is
terminated by pressing the enter key.

 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 print () outputs a complete
line and then moves to the next line for subsequent output.
The syntax for print () is:
print(value [, ..., sep = ' ', end = '\n'])

sep: The optional parameter sep is a separator between the output values. Programmer can use a
character, integer or a string as a separator. The default separator is space.

end: This is also optional and it allows programmer to specify any string to be appended after the
last value. The default is a new line.

 Type Conversion: The process of converting one data type to another data type is called as Type
Conversion.
In Python, Type conversion can happen in two ways: either explicitly (forced) when
the programmer specifies for the interpreter to convert a data type to another type; or
implicitly when the interpreter understands such a need by itself and does the type
conversion automatically.

 Explicit conversion, also called type casting happens when data type conversion takes place because
the programmer forced it in the program.
The general form of an explicit data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are forcing an
expression to be of a specific type. For example, converting a floating value of x = 2 0.67 into an
integer type, i.e., int(x) will discard the fractional part .67.

Following are some of the functions in Python that are used for explicitly converting an expression
or a variable to a different type.

Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number
str(x) Converts x to a string representation
chr(x) Converts ASCII value of x to character
ord(x) returns the character associated with the ASCII code x

 Implicit conversion, also known as coercion, happens when data type conversion is done
automatically by Python and is not instructed by the programmer.

 Debugging: A programmer can make mistakes while writing a program, and hence, the program may
not execute or may generate wrong output.
“The process of identifying and removing bugs or errors, from a program is called debugging.”

Presidency PU College, Kempapur, Hebbal, Bangalore Page 9


Computer Science – Class XI 2024 -25

Errors occurring in programs can be categorized as:


i) Syntax errors: A syntax error occurs when a programmer writes an invalid statement or when the
proper syntax of the language is not followed.

Python has its own rules that determine its syntax. The interpreter interprets the statements
only if it is syntactically (as per the rules of Python) correct.

If any syntax error is present, the interpreter shows error message(s) and stops the execution
there. 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. Such errors need to be
removed before the execution of the program

ii) Logical errors: A logical error is a bug in the program that causes it to behave incorrectly.

A logical error produces an undesired output but without abrupt termination of the
execution of the program.

Logical errors are also called semantic errors as they occur when the meaning of
the program (its semantics) is not correct.

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.
Surely, 16 is not the average of 10 and 12. The correct code to find the average should
have been (10 + 12)/2to give the correct output as 11.

iii) Runtime errors: A runtime error causes abnormal termination of program while it is executing.

Runtime error is when the statement is correct syntactically, but the interpreter
cannot execute it. Runtime errors do not appear until after the program starts running
or executing.

For example,
>>>num1 = 25
>>>num2 = 7
>>>print(num1 / num2)
we have a statement having division operation in the program. By mistake, if the
denominator entered is zero then it will give a runtime error like
“division by zero”.

---x---x---

Presidency PU College, Kempapur, Hebbal, Bangalore Page 10

You might also like