COMPUTER SCIENCE
Getting Started with Python
Introduction to Programming language
• An ordered set of instructions to be executed by a computer to carry out a specific task
is called as a program
• 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
• A program written in a high-level language is called source code
Eg: Python, C++, Visual Basic, PHP, Java
• Python uses an interpreter to convert source code into machine language
Interpreter and Compiler
• An interpreter processes the program statements one by one, first translating and then
executing. This process is continued until an error is encountered or the whole program
is executed successfully.
The Python interpreter is also called as Python shell
• A compiler translates the entire source code, as a whole, into the object code.
After scanning the whole program, it generates error messages, if any.
Introduction to Python
• It is widely used general purpose, high level programming language
• Developed by Guido van Rossum in 1991.
Features of Python
• It is a high level language.
• It is a free and open source language.
software that is distributed with its source code, making it available for use, modification, and
distribution with its original rights
• It is an interpreted language, as Python programs are executed by an interpreter.
• It is easy to understand as they have a clearly defined syntax and relatively simple
structure.
• It is case-sensitive.
Eg:NUMBER and number are not same.
• It is portable and platform independent
It can run on various operating systems and hardware platforms.
• It has a rich library of predefined functions.
• It is also helpful in web development(scripting language).
• It uses indentation for blocks and nested blocks.
1
COMPUTER SCIENCE
Python character set
Character set is a set of valid characters that the language can recognize
• Letters : a-z
• Digits : 0 to 9
• Special Symbols : space + - / ( ) * + = ! = < > , ‘ “ $ # ; : ? &
• White Spaces : Blank Space , Horizontal Tab, Vertical tab, Carriage Return.
• Other Characters : Python can process all 256 ASCII and Unicode Characters.
Tokens
The smallest individual unit in a program is called as a token or a lexical unit
• Keywords
• Identifiers
• Literals
• Operators
• Punctuators
Keywords
• Keywords are reserved words
• Each keyword has a specific meaning to the Python interpreter which can not be altered
• Eg: break, if, else, return
Identifiers
Identifiers are names used to identify a variable, function, or other entities in a program.
Rules for naming an identifier in Python
1. The name should begin with an alphabet or an underscore (_)
2. It is followed by any combination of characters a–z, A–Z, 0–9 or underscore (_). Thus, an
identifier cannot start with a digit.
3. It can be of any length.
4. It should not be a keyword
5. It is case sensitive (uppercase and lower case are treated differently)
6. We cannot use special symbols like !, @, #, $, %
Variables
A variable in a program is uniquely identified by a name which refers to an object ( an item or
element that is stored in the memory )
Eg: gender = 'M‘
gender is a variable and M is the value
Everything is an Object
• Python treats every value or data item whether numeric, string, or other type as an
object
• Every object in Python is assigned a unique identity (ID) which remains the same for the
lifetime of that object.
• The function id() returns the identity of an object.
2
COMPUTER SCIENCE
Eg : num1 = 20
id(num1)
1433920576 # identity of num1
Literals
Literals are constants that have a fixed value
Types of Literal
String literal
Boolean literal : False,True
Numeric literal : Integer, Float, Complex
Collection literal : List, Tuple, Set, Dictionary
Special literal : None
String literal
The text enclosed in quotes(single or double) form string literal
Eg: ‘a’, “xyz”, ‘xyz’, ‘x1’, ‘123’, ”123”
Strings can have non graphic characters
Eg: double quote“ single quote‘ enter/return
Non graphic characters can be represented using Escape sequences
Eg: \” \’ \n
Types :Single line string - ‘Hi how are you’
Multiline string - ‘’’Hi
how are you’’’
Numeric Literals
• int or integers are positive or negative whole numbers without decimal point
Eg: -2, +30, 2000 (by default +ve whole number)
• float or real numbers written with a decimal point dividing integer and fractional parts
Eg: -2.5, 6.98
• complex or complex numbers are of the form a+bj (or J) .a is the real part, b is the
imaginary part
Eg: 3+4j, 3-2j
Boolean Literals
• True and False
• These are built-in constants
Special Literals
• The None literal is used to indicate absence of value
• None is a built-in constant
3
COMPUTER SCIENCE
Execution Modes
Interactive mode
It allows execution of individual statement instantaneously.
Python prompt >>> indicates that the interpreter is ready to take instructions or
commands.
Script mode
It allows to write more than one instruction in a file (python source code) that can be
executed
Python scripts are saved as files where file name has extension “.py”
Input and Output
input()
It is a function for taking the user input from the keyboard. It accepts all user input as string
Syn : input (“string”)
Eg: fname = input("Enter your college name :")
print(fname)
print()
• It is a Function to output/print data on the screen
• The data will be converted into a string before written to the screen
• It outputs a complete line and then moves to the next line for subsequent output
Syn:print(values, *sep = ' ', end = ‘\n’,…+)
Separator : allows to specify any character between two values. The default separator is space.
end : allows to specify any character at the end of the [Link] default end is a new line.
* Separator and end are optional
Eg : print(“Hi”,”How are you?”,sep=“.....”, end=“***”)
O/P: Hi…..How are you?***
print(“Jain college”)
O/P: Jain college
Comments
Used to document the meaning and purpose of source code and its input and output
requirements, so that we can remember later how it functions and how to use it.
Comments are not executed by interpreter
o Single line comments starts with #
Eg : # To find the sum of two numbers
o Multiline comments are enclosed by triple quotes (”””)
Eg : """Multiple
line of comments”””
Eg : ‘’’ Multiple
line of comments’’’
4
COMPUTER SCIENCE
Data types
Data type identifies the type of data values a variable can hold and the operations that can be
performed on that data.
Number/Numeric datatype
Number data type stores numerical values only
Boolean:
(bool) is a subtype of integer consisting of two constants, True and False.
Boolean True value is non-zero, non-null and non-empty.
Boolean False is the value zero.
Variables of simple data types like integers, float, Boolean, etc., hold single values
type() function
type() function returns the data type of the variable.
Eg: n = 10
print(type(n))
<class 'int'>
v = -1921.9
print(type(v))
<class 'float'>
5
COMPUTER SCIENCE
Sequence
Sequence is an ordered collection of items, where each item is indexed by an integer.
Strings
String is a group of characters enclosed either in single quotation marks or in double
quotation marks
Eg:str=’Hello’ str= “Hello” str= ”abc12” str= ’a12?/’ str=“user name”
List
List is a sequence of items separated by commas and the items are enclosed in square
brackets [ ].It is a mutable datatype.
Eg: list1 = [5, 3.4, "New Delhi", "20C", 45]
Tuple
Tuple is a sequence of items separated by commas and the items are enclosed in common
brackets ()
Eg: tuple1 = (5, 3.4, "New Delhi", "20C", 45)
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.
Eg: set1 = {5, 3.4, "New Delhi", "20C", 45}
None
• None is a special data type with a single value to signify the absence of value
• None supports no special operations, and it is neither False nor 0 (zero)
>>> n = None
>>> print(n,type(n))
None <class 'NoneType‘>
Mapping
• Mapping is an unordered mutable data type in Python
Eg: Dictionary
• It 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.
• Dictionary = { key : value,
key : value,
key : value
}
6
COMPUTER SCIENCE
• Example: dict1 = { 'Fruit’ : 'Apple',
'Climate’ : 'Cold',
'Price(kg)’ : 120
}
• 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 [ ].
print(dict1['Price(kg)'])
120
Mutable and Immutable Data Types
• Variables whose values can be changed after they are created and assigned are called
mutable.
Eg: List,Dictionary,set
• Variables whose values cannot be changed after they are created and assigned are
called immutable.
Eg: int, float, bool, complex, string, tuple
Note: 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
Operators and operands
• An operator is a symbol used to perform specific mathematical or logical operation on
values
• The values that the operators work on are called operands
Eg: 10 + num
Operands: 10, num
Operator : + (plus)
Python Operators
Arithmetic Operators : + - * / % // **
Relational Operators : == > < >= <= !=
Assignment Operators : = += -= *= /= %= //= **=
Logical Operators : and or not
Identity Operators : is is not
Membership Operators : in not in
7
COMPUTER SCIENCE
Arithmetic Operators
Arithmetic Operators are used to perform arithmetic operations like addition, multiplication,
division etc.
Operator Operation Description Example Result
a = 13 b=
4
+ Addition To find sum of two number c=a+b 16
- Subtraction To find difference between d=a–b 8
two number
* Multiplication To find product of two p=a*b 48
number
/ Division To find quotient of two q=a/b 3.25
number
% Modulus To find reminder of two r=a%b 1
number
// Floor division To find the quotient by f = a // b 3
removing the digits after
decimal point
** Exponent To find a raise to the power e = a**b 28561
b
Relational Operators
Relational operator compares the values of the operands on its either side and determines the
relationship among them.
Operator Operation Description Example Output
a=10 b=15
c=10
< Less than It returns True only if a is less a<b; True (1)
than b
> Greater than It returns True only if a is a>b; False
greater than b (0)
<= Less than or It returns true if b is less than b<=c; False
equal to c or b is equal to c (0)
>= Greater than It returns True if b is greater b>=c; True (1)
or equal to than c or if b is equal to c
!= Not equal to It returns true only if a is not a!=c; False
equal to c (0)
== Equal to It returns true only if a is a==c; True (1)
equal to c
8
COMPUTER SCIENCE
Assignment Operators
Assignment operator assigns or changes the value of the variable on its left
Operat Operation Syntax Is Examp
or equivalen le a=10
t to b=2
= Assigns the value from right side operand a=b a=b a=2
to left side operand
+= It adds the value of right-side op to left a+=b a=a+b a=12
side op and assigns the result to left side
op
-= It subtracts the value of right-side op to a-=b a=a-b a=8
left side op and assigns the result to left
side op
*= It multiplies the value of right-side op to a*=b a=a*b a=20
left side op and assigns the result to left
side op
/= It divides the value of right-side op to left a/=b a=a/b a=5
side op and assigns the result to left side
op
%= It performs modulus operation on the a % = b a=a%b a=0
value of right-side op to left side op and
assigns the result to left side op
//= It performs floor division on the value of a //= b a=a//b a=5
right-side op to left side op and assigns
the result to left side op
**= It performs exponential calculation on the a **= b a=a**b a=100
value operands and assigns the result to
left side op
Logical Operators
The logical operator evaluates to either True or False based on the logical operands on either
side.
Operator Description Example Result
a=10 b=15 c=25
And Returns true if both the (a<b) and (c<a) False
expressions A and B are true.
Or Returns true if either expression (a<b) or (c<a) True
A or B is true.
not Returns true if A is false. not(a<b) False
A B A and B A or B
F F F F
F T F T
T F F T
T T T T
9
COMPUTER SCIENCE
Note: By default, all values are True except 0(Zero), None, False, empty collections "", (), [], {}
Identity Operators
It is used to determine whether the value of a variable is of a certain type or not
Identity operators can be used to determine whether two variables are referring to the
same object or not
operator Description Example Result
is var1 is var2 results num1 = 5 True
to True if id(var1) is type(num1) is int
equal to id(var2)
num2 = num1
id(num1)
1433920576
id(num2)
1433920576 True
num1 is num2
is not var1 num1 is not num2 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 of the given sequence
or not.
operator Description Example Result
a =[1,2,3]
in Returns True if the 2 in a True
variable/value is found in the
specified sequence and False
otherwise '1' in a False
not in Returns True if the 10 not in a True
variable/value is not found in
the specified sequence and
False otherwise 1 not in a False
10
COMPUTER SCIENCE
Expressions
An expression is defined as a valid combination of constants, variables, and operators.
An expression always evaluates to a value.
Eg: 3.0 + 3.14
EVALUATION OF EXPRESSION
Hierarchy/Precedence Of OPERATORS
In case of multiple operators in an expression, order of operations to be carried out is called
precedence.
For operators with equal precedence, the expression is evaluated from left to right
Eg: 20 - 30 + 40
= (20 – 30) + 40
= -10 + 40
= 30
Order of Operator Description
Precedence
1 ** Exponentiation
2 ~ + - Complement, Unary plus, unary minus
3 / % // * Divide, modulo, floor division, multiply
4 + - Addition, subtraction
5 <= < > >= == != Relational operators
6 is , is not Identity operators
7 in , not in Membership operators
8 not
9 and Logical operators
10 or
11 = += -= *= /= //= **= Assignment operators
Classification of operator based on the number of operands
Unary operator – operates on one operand(not)
Binary operator – operates on two operands(+,-,==,<….)
Punctuators
These are the symbols that used in Python to organize the structures, statements, and
expressions.
Eg: [ ] { } ( ) @ -= += *= //= **== = , etc.
Type conversion
It is the process in which data type of a variable changes from one type to another.
There are 2 types of type conversion
1. Explicit Conversion (type casting)
2. Implicit Conversion (coercion)
Explicit Conversion(type casting)
Here data type conversion takes place because the programmer forced it in the
program.
(new_data_type) (expression)
11
COMPUTER SCIENCE
Eg: num1 = input("Enter a number :")
num1 = num1 * 2 Enter a number : 2
print(num1) 22
num1 = int(input("Enter a number"))
num1 = num1 * 2 Enter a number : 2
4
print(num1)
Explicit Conversion(type casting) functions in Python
Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number (int to float)
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(coercion)
Here data type conversion is done automatically by Python interpreter and is not instructed
by the programmer.
Eg: a=2 #integer value
b=2.5 #float value
sum=a+b #sum becomes float value(wider range) by interpreter
print(sum)
4.5
Debugging
• The process of identifying and removing errors( bugs ) from a program is called
debugging.
• Errors occurring in programs can be categorized as:
i) Syntax errors
ii) Logical errors/Semantic error
iii) Runtime errors
Syntax Errors
Errors due to the violation of grammatical/syntax rules of the programming language
Interpreter shows the Syntax errors and it stops the execution.
Eg: (a+b
print(HI’)
12
COMPUTER SCIENCE
Logical Error/Semantic Error
An error occurs due to the wrong use of logic, which produces undesired output but without
abrupt termination of the execution of the program
Eg : average=a+b+c/2
Runtime Error
An error causes abnormal termination of the program while it is executing
Eg:Q=a/b ,if b=0 “division by zero”
Q=a/b,if b=“string” “Invalid literal for int”
13