Chapter 5 Getting Started With Python_compressed
Chapter 5 Getting Started With Python_compressed
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:
Execution Modes:
Working in the interactive mode is convenient for testing a single line code for instant execution.
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.
(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.
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 (‖‖‖)
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(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:
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".
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]
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')
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.
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.
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)
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.
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.
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.
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.
EXPRESSIONS
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
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
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
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.
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)
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