Ch-4 Notes and Questions
Ch-4 Notes and Questions
INTRODUCTION:
TOKENS IN PYTHON:
1. Keywords
2. Identifiers
3. Literals
4. Operators
5. Punctuators
1. Keywords
2. Identifiers
c) Except for the initial letter, any digit from 0 to 9 can be part of the
identification.
d) It shouldn’t be used as a keyword
special characters.
f) Identifiers can be as long as you want them to be.
Literals, tokens in Python, are data elements with a fixed value. Literals
return a value for an object of the specified type. Python supports a
variety of literals:
String Literals
Numeric Literals. These are further of three types, integer, float, and
complex literals.
Boolean Literals
Literal Collection
4. Operators
Arithmetic Operators
Python arithmetic operators are used to perform mathematical
operations on numerical values. These operations are Addition,
Subtraction, Multiplication, Division, Modulus, Exponents and Floor
Division.
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
Assignment Operators
Python assignment operators are used to assign values to variables.
These operators include simple assignment operator, addition
assign, subtraction assign, multiplication assign, division and assign
operators etc.
= Assignment Operator a = 10
Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation.
Assume if a = 60; and b = 13; Now in the binary format their values will
be 0011 1100 and 0000 1101 respectively. Following table lists out the
bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands
−
a = 0011 1100
b = 0000 1101
--------------------------
Logical Operators
There are following logical operators supported by Python language.
not Logical Used to reverse the logical state of its Not(a and
NOT operand. b) is false.
Membership Operators
Python’s membership operators test for membership in a sequence,
such as strings, lists, or tuples. There are two membership operators
as explained below-
Identity Operators
Identity operators compare the memory locations of two objects.
There are two Identity operators explained below −
Operators Precedence
The following table lists all operators from highest precedence to
lowest.
1 **
2 ~+-
3 * / % //
4 +-
6 &
Bitwise 'AND'
7 ^|
Comparison operators
9 <> == !=
Equality operators
10 = %= /= //= -= += *= **=
Assignment operators
11 Is, is not
Identity operators
12 In, not in
Membership operators
Logical operators
5. Punctuators
Python provides various standard data types that define the storage
method on each of them. The data types defined in Python are given
below:
Numbers
Sequence Type
Boolean
Set
Dictionary
Number stores numeric values. The integer, float, and complex values
belong to a Python Numbers data-type. Python provides
the type() function to know the data-type of the variable.
1. Int - Integer value can be any length such as integers 10, 2, 29, -
20, -150 etc. Python has no restriction on the length of an integer. Its
value belongs to int.
2. Float - Float is used to store floating-point numbers like 1.9,
9.902, 15.2, etc. It is accurate upto 15 decimal points.
1. String
Example - 1
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
2. List
The List can contain data of different types. The items stored in the list
are separated with a comma (,) and enclosed within square brackets
[].
We can use slice [:] operators to access the data of the list. The
concatenation operator (+) and repetition operator (*) works with the
list in the same way as they were working with the strings.
Example -
# List slicing
print (list1[3:])
# List slicing
print (list1[0:2])
Output:
[List]
[1, 'hi', 'Python', 2]
[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
4. Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain
the collection of the items of different data types. The items of the
tuple are separated with a comma (,) and enclosed in parentheses
().
Example –
# Tuple slicing
print (tup[1:])
print (tup[0:1])
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
TypeError: 'tuple' object does not support item assignment
Dictionary
The items in the dictionary are separated with the comma (,) and
enclosed in the curly braces {}.
Example –
# Printing dictionary
print (d)
print (d.keys())
print (d.values())
Output:
Boolean
Boolean type provides two built-in values, True and False. These
values are used to determine the given statement true or false. It
denotes by the class bool. True can be represented by any non-zero
value or 'T' whereas false can be represented by the 0 or 'F'.
Example -
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
Example -
set2.add(10)
print(set2)
Output:
Mutable Immutable
The objects can be modified after Objects can not be modified after
the creation as well. the creation of the objects.
Classes that are mutable are not Classes that are immutable are
considered final. considered final.
Classes are not made final for the Classes are made final for the
mutable objects. immutable objects.
Example: Lists, Dicts, Sets, User- Example: int, float, bool, string,
Defined Classes, Dictionaries, etc. Unicode, tuple, Numbers, etc.
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
1. int(a, base): This function converts any data type to integer. ‘Base’
specifies the base in which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-
point number.
Example-
s = "10010"
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
e = float(s)
print ("After converting to float : ", end="")
print (e)
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
Example-
txt = input("Type something to test this out: ")
print( "This is output of input line: " txt)
FUNCTION IN PYTHON
Python comes preloaded with many that you can use as per your needs.
You can even create new functions. Broadly, Python functions can belong
to one of the following three categories:
In this chapter, you will learn to write your own Python functions and use
them in your programs.
DEFINING FUNCTION IN PYTHON
def function_name(arguments):
# function body
return
Here,
Or
def sum(x,y):
s = x+y
return s
Here,
we have created a function named test(). It simply prints the text
Hello World!.
Structure of a Python Program using Functions
Example:
def hello():
name = str(input("Enter your name: "))
if name:
print ("Hello " + str(name))
else:
print("Hello World")
return
hello()
Here,
This code defines a function called hello().
When the function is called, it prompts the user to enter their name
using the input() function and stores the input as a string in the
variable name.
The code then checks if name is not an empty string using the if
statement.
If name is not empty, the function prints "Hello" followed by the value
of name.
If name is empty, the function prints "Hello World".
Finally, the function returns None as there is no explicit return value
specified.
When the code is run, the hello() function is called, prompting the
user to enter their name and printing the appropriate greeting based
on the input.
Indentation in Python
Example-
site = 'prepbytes'
if site == 'prepbytes':
print('Logging on to prepbytes...')
else:
print('retype the URL.')
print('All set !')
Output
Logging on to prepbytes...
All set !
Rules and Tips in Python
There are certain rules that the programmer must follow when
programming. If you break any rule, you will get a so-called compilation
error, in other words, the compiler does not understand how to translate
the code, and then the computer does not know what to do. The program
will then crash.
As with syntax, rules are something you learn gradually, but it is still
important to start thinking about how to structure and write your programs.
Some basic rules in Python are:
Example:
print("Hello World!") # This is the comment
--> ignored by the compiler
Output:
Hello World!
DEBUGGING
Syntax Error
Runtime Error
This type of error does not appear until program is executed. In this,
program is executed successfully without syntax or logical error and this
type of error occurs at runtime i.e. while accepting values from user.
Runtime errors are also called as exceptions or interruptions in program.
a=2
b=3
c=4
d=input("enter a number")
sum=a+b+c+d
print(sum)
Output
enter a number5
Traceback (most recent call last):
File "C:/Python34/runtime error.py", line 5, in
sum=a+b+c+d
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In this program will be executed without any error on prompt but will not
give desired output. Such type of error is called Semantic error. Semantic
errors are also called as logical errors. It is difficult to track such errors as it
requires to go backward to look for output and find errors causing incorrect
output.
num1=int(input("Enter first number"))
num2=int(input("Enter second number"))
add = num1 - num2
print("sum of two nums is ", add )
Output
Enter first number200
Enter second number57
sum of two nums is 143
MEMORY BYTES
> APython program can contain various components like expressions, statements, comments, functions, blocks and
indentation.
An expression is a legal combination of symbols that represents a value.
>Astatement is a programming instruction.
> Comments are non-executable, additional information added in a program for readability.
} In Python, comments begin with the hash (#) symbol/character.
> Avariable in Python is defined only when some value is assigned to it.
» Python supports dynamic typing, i.e., a variable can hold values of different types at different times.
function is a named block of statements that can be invoked by its name.
A
> The input() function evaluates the data input and takes the result as numeric type.
º Output is generated through print statement.
> An expression is a valid combination of operators and operands. Operands are the objects on which operators ara
applied.
> Arithmetic, relational and logical operators are used for performing computations in aprogram.
> Astring is a sequence of characters. To specify a string, we may use single, double or triple quotes.
> The operator +(addition) appliedon two string operands is used for concatenating them. Similarly, the operator
* (multiplication) is used to repeat a string a specific number of times.
When relational operators are applied in strings, strings are compared left to right, character by character.
according to their ASCIl values.
While evaluating aBoolean expression involving 'and' operator, the second sub-expression is evaluated only if the
first sub-expression yields True.
> While evaluating an expression involving 'or operator, the second sub-expression is evaluated only if the first
sub-expression yields False.
Avariable is a name that refers to a value. We may also say that a variable associates a name with a data object
such as number, character, string or Boolean.
º Values are assigned to variables using assignment statement. The syntax for assignment statements is as follows:
variable = expression
where variable is called I-value and expression is called r-value.
> In an assignment statement, the expression on the right-hand side of the equal to (=) operator is evaluated and
the value so obtained is assignedto the variable on the left-hand side of the equal to (=) operator.
º A variable name must begin with a letter or_(underscore character). It may contain any number of letters, digits
or underscore characters. No other character apart from these is allowed.
> Python is case-sensitive. Thus, marks and Marks are different variables.
> The shorthand notion for a = a <operator> b is
a<operator>=b
> In Python, multiple assignment statements can be specified in a single line as follows:
<name1>, <name2>, ... = <expression1>, <expression2>, ...
A keyword is a reserved word that is already defined by Python for a specific use. Keywords cannot be used for
any other purpose.
Trving to use a variable that has not been assigned a value gives an error.
º Run-time errors occur during the execution of a program.
> Irregular unexpected situations occurring during run-time are called exceptions.
error does not stop execution but the program behaves incorrectly and produces
undesired/wrong output.
(n) Trying to access a variable or file that doesn't exist is a kind of error.
SOLVED QUESTIONS
1. What are tokens in Python? How many types of tokens are allowed in Python? Exemplify your answer.
Ans. Token is the smallest individual unit in a program.
Types of tokens:
keywords: False, True, for, while
identifiers: a, A, Ist, dict1
literal: "python", 5, 9, class11'
operator: +, - /, *, **, %, 1/
punctuators: &, ^, ?, #, @, !
2. What are the different components of a variable?
Ans. Avariable has three main components:
(a) ldentity (memory address) of the variable.
(b) Type (data type) of the variable.
(c) Value of the variable.
3. Consider the following statements in Python interpreter and describe the output/statement required:
(a) Print a message "Hello World".
(b) a = 10
b= 12
C= a + b
print (c)
(c) To retrieve the data type of the inputted string "Hello" stored inside the variable a'.
(d) To describe the data type of variable 'b'.
(e) To retrieve the address of variables a and b.
(f) State the output:
>>> b= 12
>>> d = b
>>> d
>>> id (d)
>>>id (b)
(g) >>> a = " Hel lo"
>>> a * 10
() >>>a, b= 10, 12
>>> a, b=b, a
>>> a
12
>>> b
10
4. Which of the following identifier names are invalid and why? (NCERT)
(i) Serial no. (ii) 1st Room
(iii) Hundred$ (iv) Total Marks
(v) Total Marks (vi) total-Marks
(vii) Percentage (viii) True
Ans. Following identifier names are invalid:
S.No. Invalid Identifier Reason
Serial no. ldentifier cannot contain special symbol
()
(ii) 1st ROom Identifier name cannot begin with number
(ii) Hundred$ Identifier cannot contain special symbol
(iv) Total Marks ldentifier cannot contain space
(vi) total-Marks ldentifier cannot contain special symbol
(viil) True ldentifier cannot be a keyword
5. What is the difference between a keyword and a variable?
Ans. Keyword is a special word that has a specific purpose and meaning to the Python interpreter. Keyworas
defined.
reserved words that can be used in our program only for the purpose for which they have been
For example, for, if, elif, else, def, True, False, etc. fixed/
Variable is the user-defined name given to a value that is stored in the memory. Variables are not They
reserved. These are defined bythe user but they can have letters, digits and the symbol underscore.
must begin with either a letter or underscore. For example, _age, name, result_1, etc.
6. What is a function? How is it useful?
Ans. Afunction in Python is a named block of statements within a program that performs a specific task
Forexample, the following program has a function within it, namely greet_msg().
# progl.py
def greet msg():
print ("Hello there!!")
name =
input ("Your name: ")
print (name, greet msg())
Functions are useful as they can be reused anywhere through their function call statements. So, for the
same functionality, one need not rewrite the code every time it is needed; rather, through functions it can
be used again and again.
7. Find the error.
def minus (total, decrement)
output = total decrement
return output
Ans. The function header has colon missing at the end and the following two statements are not indented. So, we
need to add colon (:) at the end of the header line and indent the two lines following the function header.
Thus, the corrected code will be:
def minus (total, decrement):
Output = total decrement
return output
8. Differentiate between mutable and immutable objects.
Ans. Mutable object: Objects whose values can be changed after they are created arnd assigned values are called
mutable objects. For example, list, dictionary, etc.
Immutable object: Objects whose values cannot be changed after they are created and assigned values are
called immutable objects. For example, int, float, string, tuple, etc.
9. Ritu is confused between 3*2 and 3**2. Help her to know the difference between the two expressions.
Ans. The statement 3*2 multiplies 3 by 2 and produces the result 6 while 3**2 calculates 3 raised to the
power 2 and produces the result 9.
10. How many types of strings are supported in Python?
Ans. Python allows two string types:
(1) Single line StringS-Strings that are terminated in a single line enclosed within single and double quotes.
(2) Multiline Strings-Strings storing multiple lines of text enclosed within three single or double quotes.
11. Differentiate between explicit and implicit type conversion.
Ans. An implicit type conversion is a conversion performed by the compiler without programmer's intervention.
An implicit conversion is applied generally whenever multiple data types are intermixed in an expression
(mixed mode expression), so as not to lose information.
An explicit tvpe conversion is user-defined conversion that forces an expression to a specific type. The
explicit type conversion is also known as Type Casting.
12. What are variable-naming conventions?
Ans. (i) Avariable must start with a letter or underscore followed by any number of digitsand/or letters.
(iü) No reserved word or standard should be used as the variable name.
(iii) No special character (other than underscore) should be included in the variable name.
(iv) Case sensitivityshould be taken care of.
13. What is None in Python?
Ans. Python has one special data type called None. The None type is used to indicate something that has not yet
been created. It is a non-null, unidentified value.
14. ldentify the types of the following literals:
"False", None, [100.200 20o
23.789, 23789, True, {4: "four",5: "five"}, True', "True", (1,2,3), False,
Ans. 23.789 Floating point
23789 integer
True Boolean
y=x
25. Write the Python code to accept time in minutes and convert it into hours and minutes.
Ans. min=int (input ("Enter time in minutes") )
h=min//60
m=min%60
print ("Hours=",h)
print ("Minutes=", m)
26. Evaluate (to true or false) each of the following expressions:
(i) 14 <= 14
(ii) 14 < 14
(ii) -14 > -15
(iv) -15 >=15
Ans. (i) True
(ii) False
(iii) True
(iv) False
27. Write logical expressions corresponding to the following statements in Python and evaluate the expressions
(assuming values of variables as num1, num2, num3, first, middle, last: (NCERT)
(a) The sum of 20 and -10 is less than 12.
(b) num3 is not more than 24.
(c) 6.75 is between the values of integers num1 and num2.
(d) The string 'middle' is larger than the string 'first' and smaller than the string last'.
(e) List Stationery is empty.
Ans. Expressions:
(a) 20+ (-10) < 12
(b) not (num3 > 24)
(c) (6.75 > numl) and (6.75 < num2 )
(d) (middle > first) and (middle < last)
(e) Stationery == | )OR len(Stationery) == 0
28. Ayear is a leap year if it is divisible by 4,except that years divisible by 100 are not leap years unless theyare
also divisible by 400. Write a program that asks the user for a year and print whether it is a leap year or not.
Ans. year = int (input ("Please Enter the Year Number you wish: ") )
if year%400 == 0or year%4 == 0 and year%100 != 0 :
print (year, "is a Leap Year")
else:
35. Write a program to swap two numbers using a third variable. (NCERT)
Ans. a = int (input ("Enter First Number"))
b= int(input ("Enter Second Number"))
print ("Before Swapping Values are")
print ("Value of First Variable a is", a)
print ("Value of Second Variable b is", b)
C= a
a = b
b = C