Ganganagar, Bangalore
SUBJECT COMPUTER SCIENCE
CLASS Chapter- 05
I PUC
Topic : Getting started with Python
Topics - » Introduction to python
» Python keywords
» Identifiers
» comments
» Data types
» Operators
» Expressions.
» statement
» Input and output
» Type conversion
» Debugging
An order set of instructions to be executed by a computer to carry out a specific task is called a program.
The language used to specify this set of instructions to the computer is called a programming language.
1. Mentions the features of python?
1. Python is high level programming language. It is a free and open source language.
2. It is interpreted language, as python programs are executed by an interpreter.
3. Python programs is case sensitive.
4. Python is portable and plat form independent.
5. Python uses indentation for blocks and nested blocks.
6. Python has rich library of predefined function.
2. Explain different execution mode of a python program.
To execute a python program python interpreter required on computer system. It is also possible to use
any online python interpreter. The interpreter is also called python shell.
There are two ways to use the python interpreter.
a) Interactive mode – type a python statement on the >>> prompt directly, as soon as we press Enter key,
the interpreter executes the statement and display result. It is not possible to save statements for future
use.
b) Script mode- in the script mode, we can write a Python program in a file, save it and then use the
interpreter to execute it.
5. GETTING STARTED WITH PYTHON 1
3. Explain structure of a python program? With example.
Python structure refers to the way code is organized and conventions followed to ensure clarity and
efficiency. Python composed of various programming elements such as
1. Comments – Python interpreter does not executes this but it explains statements. There are two types of
comments
a) Single line comment – start with # symbol. Ex- #python program
b) Multiline comment - starts and ends with “””/’ ‘ ‘ (double or single quotation marks)
2. Statements – Python interpreter executes this statement, each statement is on its own line and end of the
statement is marked by new line character.
3. White space – python uses white space to define blocks or sub blocks of code.
4. Line continuation ( / ) – sometimes statements can be too long for a single line. Python allows for both
implicit /explicit line continuation. Implicit continuation is used with parenthesis/
bracket/brace. While explicit continuation uses a backslash at the end of the line.
Ex- #addition of two number.
A=5
B=3
C=A+B
print (“sum=”,C)
4. What is a python keywords?
Keywords are reserved words. Each keyword has a special meaning to the python interpreter.
Ex- false, def , for , return, if, int ect.
5. What is an identifier? Mention its rules for naming identifier.
Identifiers are names used to identify a variable, function or other entities in a program.
Rules for naming Identifier as follows
1. Name should be begin with an upper case or lower case alphabets or _ (underscore)
Ex- valid - num1 invalid - +num
2. It can be of any length
Ex- valid – number
3. It should not be a keyword or reserve word.
Valid – Int invalid – int
4. We cannot use special symbols
Valid - num_1 invalid - num-1
5. Space is not allowed in identifier
Valid num_1 invalid - num 1
5. What is a variable?
Name given to memory where an item or element is stored. Python considers variable as an object. In
python we can use an assignment operator to create new variables and assign specific value to them.
5. GETTING STARTED WITH PYTHON 2
6. What is comment in python?
Comments are used in python to add a remark or a note in the source code. Comments are not executed by
interpreter. 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 symbol). Everything following the #
till the end of that line is treated as comment and the interpreter simply ignores it while executing the
statement. Multi line comment is not there in python.
7. Write a note on python 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 the object. This ID is
akin to memory t of the object. The function id ( ) returns the identity of an object.
8. Explain data type in python.
Data types identifies the type of data values a variable can hold and the operations that can be performed
on the data.
9. Explain number data type in python.
Numbers – Number data types stores numerical values only. it holds only single value. It is further classified
into three different type.
1. int - it stores integer numbers, it can either positive or negative numbers. Ex - -12,0,25
a) bool – Boolean is a subtype of integer. It consist only two constants True and False.
2. float – it stores real or floating point numbers. Number with fraction, ex- -2.05, 4.0
3. complex - stores complex numbers. ex 3+4j, 2-2j
10. Explain sequences data type in python.
In python sequence is an ordered collection of items, where each element is indexed by an integer. There are 3
type
i) string – it is a group of characters. These characters may be alphabets, digits or special characters
Including spaces. String values are enclosed either in single or double quotation marks. Where
5. GETTING STARTED WITH PYTHON 3
Quotation marks are not part of string, it just indicates beginning and end of the string for the
interpreter. Numerical operation on string is not possible although string consist number.
Ex- ‘reva’ , “reva”, “23”
ii) list - list is a sequence of items separated by commas and items are enclosed in square bracket [ ]
value of list can be changed ( mutable)
ex- list1=[ 5, 3.5 ,”reva”, ‘56’ ]
iii) tuple – it is sequence of items separated by commas and items are enclosed in parenthesis( ). Values of
tuple cannot be changed (immutable).
Ex- tuple1=( 5, 5.3, ”reva”, ‘56’ )
11. Explain set data type in python.
Set is an unordered collection of items separated by commas and the items are enclosed in curly brackets{ }.
A set cannot have duplicate items and once created, item of a set cannot be changed.
Ex- set1={10,20,3.14, “BENGALORE”}
12. What is None data type in python.
None is a special data type with a single value. It is used to signify the absence of value. None does not
support any operations. It is neither same as False nor 0.
13. Explain data type mapping in python.
Mapping is an unordered data type in python. One standard mapping data type in python called dictionary.
Dictionary data type in python holds data items in key-value pairs. Item in a dictionary are enclosed in curly
bracket { }. Every key is separated from its value using a colon( : ). Any value of a dictionary can be accessed by
specify its key in square brackets.
Ex- dict1={ ‘fr’: “apple”, 2:”number”, ‘m’:”male”, ‘f’:”female”}
print(dict1[2]) = number
print(dict1[‘m’]) = male
14. What is mutable and immutable data type? Give example.
Variable whose values can be changed after they are created and assigned are called mutable.
Ex- lists, sets, dictionary
Variable whose value cannot be changed after they are created and assigned are called immutable.
Ex- integers, float, Boolean, complex, strings, tuples
15. How do you choose data type in python.
List is needed when we need a collection of data that may go for frequent modifications.
Ex – storing student names of a class.
Tuple is needed when we need a collection of data that do not need any changes.
Ex- names of a month in a year.
Set is needed when we need a collection of data which should not have any duplicated data.
Ex- list of artefacts in a museum.
5. GETTING STARTED WITH PYTHON 4
Dictionary is needed a collection of data which constantly modified or we need fast lookup based on key or
if we need key: value pair of data.
16. What is an operator? Given an example.
Operator is a character, is used to perform mathematical or logical operation on values. The values that the
operators work on are called operands.
Ex- num1 =10 + num2. Where + and = are operator , num1,num2,10 are operands.
There are 7 types of operators they are Arithmetic operators, Relational operators, Assignment operators,
Logical operators, Identity operators, Membership operators and Bitwise operator.
17. Explain arithmetic operator with example.
Operator Operation Description Example
+ Addition It add 2 number on either side of the operator 5 + 6 is 11
and also concatenate two strings “re”+”va” is
“reva”
- Subtraction Subtracts operand on the right from the operand on left 5 – 6 is -1
* Multiplication Multiply both the operand and repeat first operand 2nd 3 * 2 is 6
operand time when first operand is string. “pu”*2 is “pupu”
/ Division Divide left operand by right operand and returns quotients 5/2 is 2.5
% Modulus Divide left operand by right operand and returns remainder 5/2 is 1
// Floor division Divide left operand by right operand and returns integer quotient 5/2 is 2
** Exponent Performs exponential calculation on operands 2**3 is 8
18. Explain Relational operator with example.
It compares the value of the operands and determines the relationship among them.
Operator Operation Description Example
== Equals to If the values of two operands are equal, then the condition is True, 5==6 is False
otherwise it is False 8==8 is True
!= Not equal to If the values of two operands are not equal, then condition is True, 5!=6 is True
otherwise it is False. 8!=8 is False
> Greater than If the value of the left-side operand is greater than right-sider 8>5 is True
operand, then condition is True, otherwise it is False. 5>8 is False
< Less than If the value of the left-side operand is less than right-sider operand, 5<8 is True
then condition is True, otherwise it is False. 8<5 is False
>= Greater than If the value of the left-side operand is greater than or equal to right- 8>=8 is True
or equal to sider operand, then condition is True, otherwise it is False. 5>=8 is False
<= Greater than If the value of the left-side operand is less than or equal to right- 8<=8 is True
or equal to sider operand, then condition is True, otherwise it is False. 8<=5 is False
19. Explain assignment operators with example.
Assignment operator assigns or changes the values of the variable on its left. Ex - a=5
5. GETTING STARTED WITH PYTHON 5
20. Explain logical operators with examples.
Logical operators evaluates to either True or False, it is always written in lower case only. Every value logically
either True or False. By default all values are True except False, None, 0(zero)
Operator Operation Description Example
and Logical AND If both the operands are Ture, then condition True and True is True
become True. True and False is False
or Logical OR If any operands are Ture, then condition become True or False is True
True. False or False is False
not Logical NOT Used to reverse the logical state of its operand. A=10, A is True. Not A is False
21. Explain Identity operator with example?
Identity operators are used to determine whether the value of a variable is of a certain type or not. It can also
be used to determine whether two variables are referring to the same object or not.
Operator Description Example
is Evaluates True if the variables on either side of the operator point Num1=5, Num2=Num1
towards the same memory location and False otherwise. Num1 is Num2 is True .
is not Evaluates True if the variables on either side of the operator do not Num1 is not Num2 is
point towards the same memory location and False otherwise. False.
22. Explain Membership operator with example.
These operators are used check if a value is a member of the given sequence or not.
Operator Description Example
in Returns True if the variable/value is found in the specified A= [1,2,3,4] 2 in A is True
sequence and False otherwise. 5 in A is False
not in Returns True if the variable/value is not found in the specified A= [1,2, 3,4] 12 not in A is True
sequence and False otherwise. 4 not in A is False
23. Explain bitwise operator with example.
Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted
into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise
operators. The result is then returned in decimal format.
Operator Operation Description Example
& Bitwise AND Result bit 1, if both operand bits are 1; otherwise results bit 0. 2&3 is 2
| Bitwise OR Result bit 1, if any of the operand bit is 1; otherwise results bit 0. 2|3 is 3
^ Bitwise XOR Result bit 1, if any of the operand bit is 1 but not both, otherwise results bit 0. 2^3 is 1
~ Bitwise NOT Inverts individual bits. ~2 is -3
>> Bitwise right The left operand’s value is moved toward right by the number of bits 4>>2 is 1
shift Specified by the right operand.
>> Bitwise left The left operand’s value is moved toward left by the number of bits 4<<2 is 6
shift Specified by the right operand
5. GETTING STARTED WITH PYTHON 6
23. Explain expression in python?
An expression is defined as a combination of constants, variables and operators. An expression always
evaluates to a value. A value of a standalone variable is also consider as an expression but a standalone operator
is not an expression. Ex- 100, num, num=100.
24. Explain precedence of operator.
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.
Precedence Operator Description
1 ** Exponential
2 ~+- Compliment, unary addition, Unary subtraction
3 * / % // Multiply, division, modulus and floor division
4 + - Addition and subtraction
5 < <= > Relational and comparison operator
>= == !=
6 = %= /= //=
-= += *=
Assignment operator
7 is , is not Identity operators
8 in , not in Membership operators
9 not
10 and Logical operator
11 or
Parenthesis can be used to override the precedence of operators. The expression within ( ) is evaluated first.
Ex= (2+4)*2 +5 = 8 *2 +5
=16+5
= 21
25) What is a statement?
A statement is a unit of code that the python interpreter can executes.
Ex- x=y+2
25) Explain input and output operator in python?
Input function – In python input () function is used to enter data. It accepts all user input as a string. The user
may enter a number or a string but the input ( ) function treats them as strings only.
Syntax - input ( Prompt )
Prompt is the string we may like to display on the screen prior to taking the input, and its optional.
Ex- name = input(“enter your name “)
Output function – python uses print() function to output data to standard output device – the screen. The print
() function 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.
syntax - print( values, .., end=’\n’)
end is optional and it allows us to specify any string to be appended after the last value. The default is a newline.
Ex- print( “sum=”,5+3) gives sum=8
5. GETTING STARTED WITH PYTHON 7
26) Explain type conversion in python?
Type conversion is means we can change the data type of a variable in python from one type to another.
There are two type.
1. Explicit type conversion - it is also called as type casting. It takes place when the programmer specifies
for the interpreter to convert a data type to another type. With this conversion there a risk of information
of information science we are forcing an expression to be of a specific type.
The form is ( new data type) expression
Ex - x=2.5
int(x) This will discard fraction part .5 so result is 2
ord(65) returns the character associated with the ASCII code 65 is A
2. Implicit type conversion – it is also known as coercion, happens when data type conversion is
automatically by python and it’s not instructed by the programmer.
Ex- A=5 # A is an integer
B=5.5 # B is an float
C= A+B # C is float , python converts A to float
print ( C ) is 10.5
27) Explain types of errors in python?
Mistakes in a python program is called bug or error. The process or identifying and removing such mistakes
from a program is called debugging. There are 3 types of error in python program
1. Syntax Errors –Python has its own rules or grammar that determine its syntax. Syntax errors occur
when the Python interpreter encounters invalid syntax that does not conform to the python grammatical
rules. If any syntax error is present, the interpreter shows error messages and stops the execution there.
Ex - a=(7+5 here syntax error is absence of right parentheses.
2. Logical Errors – it is also called as semantics error (error of meaning), a logical error produces an
undesired output but without abrupt termination of the execution of the program. Since the program
interprets successfully even when logical errors are present in it, it is sometimes difficult to identify these
errors.
Ex – calculating average of 10 and 12 if we write the code as 10+12/6, it gives result 16, but the correct
result is 11. The correct code is (10+12)/2
3. Runtime error - A runtime error in a program is an error that occurs while the program is running after
being successfully compiled. A runtime error causes abnormal termination of while it is executing.
Ex- a=5 b=0 c=a/b this will give runtime error like “division by zero”
MCQ
1. What is a program in computer science?
a) A set of machine language instructions error messages
b) A collection of hardware components
c) An ordered set of instructions to be executed by a computer
d) A high-level language
5. GETTING STARTED WITH PYTHON 8
2. Which language is called machine language?
a) Python b) C++
c) Assembly d) 0s and 1s
3. What is source code?
a) Machine language code b) High-level language code
c) Assembly language code d) Hardware description
4. Which of the following uses an interpreter?
a) C++ b) Assembly c) Python d) Machine language
5. Which quote is attributed to Donald Knuth in the textbook?
a) "Programming is fun." b) "Computer programming is an art."
c) "Machines are powerful." d) "High-level languages are easy."
6. Which of the following is NOT a feature of Python?
a) High-level language b) Case-sensitive
c) Platform-dependent d) Rich library of predefined functions
7. What is the symbol for the Python prompt in interactive mode?
a) $ b) % c) & d) >>>
8. What is the extension of Python source code files?
a) .java b) .py c) .exe d) .txt
9. Which mode in Python allows the execution of individual statements instantaneously?
a) Script mode b) Interactive mode c) Batch mode d) Compiled mode
10. Which of the following is a Python keyword?
a) print b) import c) function d) main
11. Which of the following is a valid identifier in Python?
a) 123abc b) abc123 c) a!bc d) None of these
12. What is a variable in Python?
a) A reserved word b) A function
c) An object uniquely identified by a name d) A type of operator
13. Which symbol is used for comments in Python?
a) // b) # c) @ d) &
14. In Python, everything is treated as an
a) Variable b) Function c) Object d) Keyword
5. GETTING STARTED WITH PYTHON 9
15. Which function returns the identity of an object in Python?
a) id() b) identity() c) object_id() d) get_id()
16. What are the two execution modes in Python?
a) Compiled and Interpreted b) Interactive and Script
c) Synchronous and Asynchronous d) Batch and Real-time
17. Which of the following is NOT a feature of Python?
a) Free and open-source b) Case-sensitive
c) Platform-independent d) requires a compiler
18. Which of the following is NOT a keyword in Python?
a) while b) assert c) print d) pass
19. What is the output of the following Python code: `print("Hello, World!")`?
a) Hello, World! b) "Hello, World!" c) print("Hello, World!") d) Syntax Error
20. Which of the following statements is true about Python?
a) Python is a low-level language. b) Python is case-sensitive.
c) Python cannot be used for web development. d) Python uses a compiler for execution.
21. What is the correct syntax for a single-line comment in Python?
a) // This is a comment b) /* This is a comment */
c) # This is a comment d) < This is a comment >
22. Which of the following is NOT a Python data type?
a) Integer b) String c) Boolean d) Character
23. How do you create a variable in Python?
a) Using the var keyword b) By simply assigning a value to it
c) Using the let keyword d) By declaring it first
24. Which of the following is used for indentation in Python?
a) Curly braces b) Parentheses c) Tabs or spaces d) Semicolons
25. What will be the output of the following code: `print(2 + 3 * 4)`?
a) 20 b) 14 c) 24 d) 12
26. The python shell prompt is
a) >>> b) >> c)# d)>
27. In python object can have
a) Only data b) only function c) both data and variable d) all of these
5. GETTING STARTED WITH PYTHON
10
28. Logical operator are written in
a) Lower case b) Upper case c) either lower or upper d) all of these
26. Which Python function is used to get input from the user?
a) input() b) read() c) scanf() d) get_input()
27. What does the following Python code do: `name = input("Enter your name: ")`?
a) ) Generates a syntax error b) Assigns the string "Enter your name: " to the variable name
c) Prompts the user to enter their name and stores it in the variable name d prints "Enter your name”
28. Which of the following is an invalid variable name in Python?
a) var1 b) _var c) 1var d) var_1
29. What is the output of the following code: `print(10 / 3).`?
a) 3.3333333333333335 b) 3 c) 3.0 d) 10
30. Which of the following is NOT an arithmetic operator in Python?
a) + b) - c) * d) &&
31. What is the correct way to create a string in Python?
a) string s = "Hello" b) s = 'Hello' c) s = Hello d) string s = 'Hello'
32. Which of the following methods can be used to convert a string to a list in Python?
a) list() b) split() c) convert() d) str()
33. Which of the following is NOT a valid Python data type?
a) List b) Tuple c) Dictionary d) Array
34. What is the output of the following code: `print("Hello" + " " + "World")`?
a) Hello World b) HelloWorld c) "Hello World" d) Hello + World
35. Which operator is used for exponentiation in Python?
a) ^ b) ** c) exp() d) pow()
36. Which of the following is a mutable data type in Python?
a) String b) Tuple c) List d) Integer
37. What is the output of the following code: `print(2**3)`?
a) 5 b) 6 c) 8 d) 9
5. GETTING STARTED WITH PYTHON
11
38. Which function is used to read input from the user in Python 3.x?
a) input() b) raw_input() c) scan() d) read()
39. Which of the following statements will create a tuple in Python?
a) t = [1, 2, 3] b) t = {1, 2, 3} c) t = (1, 2, 3) d) t = 1, 2, 3
40. What is the output of the following code: `print(type([]))`?
a) tuple b) string c) list d)none of these
41. Which of the following operators is used for string concatenation in Python?
a) + b) & c) . d) concat()
42. What is the correct way to declare a variable in Python?
a) var x = 5 b) x := 5 c) int x = 5 d) x = 5
43. What will be the output of the following code: `print(10 % 3)`?
a) 1 b) 3 c) 10 d) 0.3
44. Which method is used to remove an item from a list in Python by its value?
a) remove() b) pop() c) delete() d) discard()
45. What is the output of the following code: `print(5 == 5)`?
a) True b) False c) Syntax Error d) 5
46. Which method can be used to convert a list into a tuple in Python
a) tuple() b) list_to_tuple() c) to_tuple() d) convert()
47. Which of the following is used to define a block of code in Python?
a) Indentation b) Curly braces c) Parentheses d) Square .
48. Which function is used to get the type of an object in Python?
a) type() b) isinstance() c) id() d) obj_type()
49. Which of these is not an expression.
a) num=100 b)num c)100 d) all of these
5. GETTING STARTED WITH PYTHON
12