Chapter No 5 - Getting Started With Python
Chapter No 5 - Getting Started With Python
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.
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 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
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
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:
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'>
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.
For example, in the expression 10 + num, the value 10, and the
variable num are operands and the + (plus) sign is an
operator.
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
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
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.
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.
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.”
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---