CHAPTER 5 GETTING STARTED WITH
PYTHON
CHAPTER BLUEPRINT PLAN FOR FINAL EXAM
VSA 1 MARK SA 2 MARKS LA 3 MARKS ESSAY 5 MARKS TOTAL
2 MCQ, 1‘ FIB 1 1 2 ( 1HOT) 18 MARKS
CHAPTER SYNOPSIS
Introduction to Python
Before learning about Python programming language, let us understand what is a programming language and
how it works.
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, called machine language or low-level language. High-level
programming languages like Python, C++, Visual Basic, PHP, Java are easier for humans to manage.
Python uses an interpreter to convert its instructions into machine language. An interpreter processes the pro-
gram statements one by one, translating and executing them until an error is encountered or the whole program
is executed successfully.
Features of Python
• Python is a high-level, free, and open-source language.
• It is an interpreted language, executed by an interpreter.
• Python programs are easy to understand with a clearly defined syntax.
• Python is case-sensitive.
• Python is portable and platform-independent.
• Python has a rich library of predefined functions.
143
August 24, 2024
• Python is helpful in web development.
• Python uses indentation for blocks and nested blocks.
Working with Python
To write and run (execute) a Python program, we need to have a Python interpreter installed on our computer
or use any online Python interpreter. (This content is applicable when we work in Python IDLE)
Downloading Python
The latest version of Python 3 is available on the official website: [Link]
Execution Modes
There are two ways to use the Python interpreter: 1. Interactive mode 2. Script mode
Interactive Mode
To work in the interactive mode, type a Python statement on the >>> prompt directly. The interpreter executes
the statement and displays the results.
Script Mode
In the script mode, write a Python program in a file, save it, and then use the interpreter to execute it. Python
scripts are saved as files with the .py extension.
Python Keywords
Keywords are reserved words with specific meanings to the Python interpreter. Python is case-sensitive, so
keywords must be written exactly as defined.
False class finally is return
None continue for lambda try
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raise
August 24, 2024
Identifiers
Identifiers are names used to identify a variable, function, or other entities in a program. Rules for naming an
identifier in Python are:
• The name should begin with an uppercase or a lowercase alphabet or an underscore _.
• It can be of any length.
• It should not be a keyword or reserved word.
• Special symbols like !, @, #, $, %, etc., are not allowed.
Example:
# Valid identifiers
marks1, marks2, marks3, avg
# Invalid identifiers
1marks, mark$2, avg#
Variables
A variable in Python refers to an object that is stored in memory. Variable declaration is implicit, meaning
variables are automatically declared when assigned a value.
Example:
# Variable assignment
length = 10
breadth = 20
area = length * breadth
print(area) # Output: 200
Comments
Comments are used to add a remark or a note in the source code. They are not executed by the interpreter. In
Python, a comment starts with #.
Example:
# This is a comment
amount = 3400 # Variable amount is the total spending on grocery
August 24, 2024
Everything is an Object
Python treats every value or data item as an object, meaning it can be assigned to some variable or passed to a
function as an argument.
Example:
num1 = 20
print(id(num1)) # Identity of num1
num2 = 30 - 10
print(id(num2)) # Identity of num2 and num1 are the same as both refer to object 20
Data Types
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable can
hold and the operations that can be performed.
Numeric Data Types
Type/Class Description Examples
int Integer numbers –12, –3, 0, 125, 2
float Real or floating point numbers –2.04, 4.0, 14.23
complex Complex numbers 3 + 4j, 2 – 2j
Boolean Data Type
Boolean data type consists of two constants: True and False. Boolean True value is non-zero, non-null, and
non-empty. Boolean False is the value zero.
Example:
num1 = 10
print(type(num1)) # <class 'int'>
var1 = True
print(type(var1)) # <class 'bool'>
float1 = -1921.9
print(type(float1)) # <class 'float'>
August 24, 2024
var2 = -3+7.2j
print(type(var2)) # <class 'complex'>
Sequence Data Types
A Python sequence is an ordered collection of items, where each item is indexed by an integer.
• String: A group of characters enclosed in single or double quotation marks.
str1 = 'Hello Friend'
str2 = "452"
• List: A sequence of items separated by commas and enclosed in square brackets [].
list1 = [5, 3.4, "New Delhi", "20C", 45]
print(list1)
• Tuple: A sequence of items separated by commas and enclosed in parentheses ().
tuple1 = (10, 20, "Apple", 3.4, 'a')
Set Data Type
Set is an unordered collection of items separated by commas and enclosed in curly brackets {}.
set1 = {10, 20, 3.14, "New Delhi"}
Dictionary
Dictionary in Python 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. 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 [
].
dict1 = {'Fruit':'Apple','Climate':'Cold', 'Price(kg)':120}
print(dict1['Price(kg)'])
August 24, 2024
Operators
Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the
operator operates on is called the operand.
Arithmetic Operators
Operator Description Example
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus x%y
** Exponentiation x ** y
// Floor division x // y
Example:
x = 15
y = 4
print(x + y) # 19
print(x - y) # 11
print(x * y) # 60
print(x / y) # 3.75
print(x % y) # 3
print(x ** y) # 50625
print(x // y) # 3
19
11
60
3.75
3
50625
3
Comparison Operators
August 24, 2024
Operator Description Example
== Equal to x == y
!= Not equal to x != y
> Greater than x>y
< Less than x<y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Example:
x = 10
y = 12
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
False
True
False
True
False
True
Logical Operators
Operator Description Example
and True if both operands are true x and y
or True if either operand is true x or y
not True if operand is false not x
Example:
August 24, 2024
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
Assignment Operators
Operator Description Example
= Assigns value of right side to left side x=5
+= Adds right side to left side and assigns to x += 5
left
-= Subtracts right side from left side and x -= 5
assigns to left
*= Multiplies left side by right side and x *= 5
assigns to left
/= Divides left side by right side and assigns x /= 5
to left
%= Takes modulus using two operands and x %= 5
assigns to left
//= Floor division on operands and assigns to x //= 5
left
**= Exponent on operands and assigns to left x **= 5
Example:
x = 5
x += 3 # x = x + 3
print(x) #8
x -= 2 # x = x - 2
print(x) #6
x *= 4 # x = x * 4
print(x) # 24
x /= 3 # x = x / 3
August 24, 2024
print(x) # 8.0
\x %= 5 # x = x % 5
print(x) # 3.0
Identity Operators
Operator Description Example
is Evaluates True if the variables on either num1 is num2
side of the operator point towards the
same memory location and False
otherwise.var1 is var2 results to True if
id(var1) is equal to id(var2)
is not Evaluates to False if the variables on num1 is not num2
either side of the operator point to the
same emory location and True
otherwise. var1 is not var2 results to
True if id(var1) is not equal to id(var2)
Example:
num1 = 10
print(id(num1))
num2 = num1
print(id(num2))
print(num1 is num2)
print(num1 is not num2)
Membership Operator
Operator Description Example
in Returns True if the variable/value is found lst = [1,2,3,4], 1 in lst
in the specified sequence and False
otherwise
not in Returns True if the variable/value is not 2 not in lst
found in the specified sequence and False
otherwise
Example:
August 24, 2024
lst = [1,2,3,4]
print( 1 in lst)
print(2 not in lst)
Expressions
Expressions are combinations of values, variables, operators, and function calls that are interpreted and evalu-
ated by the Python interpreter to produce a result.
Example:
x = 5
y = 10
if x < y:
print("x is less than y")
else:
print("x is not less than y")
Statements
A statement is an instruction that the Python interpreter can execute. We have already seen the assignment
statement. Some other types of statements that we’ll see include if statements, while statements, and for
statements.
Example:
x = 5
y = 10
if x < y:
print("x is less than y")
else:
print("x is not less than y")
Input and Output
Interacting with the end use to get input to produce desired result with input statement. In python, We have
input() function to get input from the user. This function always returns a string value. To print output, we use
print() function.
Example:
August 24, 2024
your_name = input("Enter your name")
your_age = int(input("Enter your age"))
print("Hi! ",your_name," and your age is ", your_age)
Type Conversion
Type conversion refers to the conversion of one data type to another. There are two types of type conversion:
implicit and explicit.
Example:
# Implicit type conversion
x = 10
y = 2.5
z = x + y
print(z) # 12.5
# Explicit type conversion
x = 5
y = "10"
z = x + int(y)
print(z) # 15(z) # 15
Debugging
Debugging is the process of finding and fixing errors in the code.
Example:
# Syntax error
10 = x
print(x)
# runtime error
x = 10
y = 0
print(x/y)
# logical error
x = 10
y = 20
if x>y:
print("x is less than y")
August 24, 2024
else:
print("y is less than x")
Multiple Choice Questions
1. What is a program in computer science?
- a) A set of machine language instructions
- b) A collection of hardware components
- c) An ordered set of instructions to be executed by a computer
- d) A high-level language
- Answer: c) An ordered set of instructions to be executed by a computer
2. Which language is called machine language?
- a) Python
- b) C++
- c) Assembly
- d) 0s and 1s
- Answer: 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
- Answer: b) High-level language code
4. Which of the following uses an interpreter?
- a) C++
- b) Assembly
- c) Python
- d) Machine language
- Answer: c) Python
5. Which quote is attributed to Donald Knuth in the textbook?
- a) “Programming is fun.”
August 24, 2024
- b) “Computer programming is an art.”
- c) “Machines are powerful.”
- d) “High-level languages are easy.”
- Answer: b) “Computer programming is an art.”
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
- Answer: c) Platform-dependent
7. What is the symbol for the Python prompt in interactive mode?
- a) $
- b) %
- c) &
- d) »>
- Answer: d) »>
8. What is the extension of Python source code files?
- a) .java
- b) .py
- c) .exe
- d) .txt
- Answer: b) .py
9. Which mode in Python allows the execution of individual statements instantaneously?
- a) Script mode
- b) Interactive mode
- c) Batch mode
- d) Compiled mode
- Answer: b) Interactive mode
10. Which of the following is a Python keyword?
August 24, 2024
- a) print
- b) import
- c) function
- d) main
- Answer: b) import
11. Which of the following is a valid identifier in Python?
- a) 123abc
- b) abc123
- c) a!bc
- d) None of these
- Answer: b) abc123
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
- Answer: c) An object uniquely identified by a name
13. Which symbol is used for comments in Python?
- a) //
- b) #
**- c) @**
- d) &
- Answer: b) #
14. In Python, everything is treated as a(n):
- a) Variable
- b) Function
- c) Object
- d) Keyword
- Answer: c) Object
August 24, 2024
15. Which function returns the identity of an object in Python?
- a) id()
- b) identity()
- c) object_id()
- d) get_id()
- Answer: a) 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
- Answer: b) Interactive and Script
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
- Answer: d) Requires a compiler
18. Which of the following is NOT a keyword in Python?
- a) while
- b) assert
- c) print
- d) pass
- Answer: c) print
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
August 24, 2024
- Answer: a) Hello, World!
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.
- Answer: b) Python is case-sensitive.
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 >
- Answer: c) # This is a comment
22. Which of the following is NOT a Python data type?
- a) Integer
- b) String
- c) Boolean
- d) Character
- Answer: 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
- Answer: b) By simply assigning a value to it
24. Which of the following is used for indentation in Python?
- a) Curly braces
- b) Parentheses
- c) Tabs or spaces
August 24, 2024
- d) Semicolons
- Answer: c) Tabs or spaces
25. What will be the output of the following code: ‘print(2 + 3 * 4)‘?
- a) 20
- b) 14
- c) 24
- d) 12
- Answer: b) 14
26. Which Python function is used to get input from the user?
- a) input()
- b) read()
- c) scanf()
- d) get_input()
- Answer: a) input()
27. What does the following Python code do: ‘name = input(“Enter your name:”)‘?
- a) Prints “Enter your name:”
- 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) Generates a syntax error
- Answer: c) Prompts the user to enter their name and stores it in the variable name
28. Which of the following is an invalid variable name in Python?
- a) var1
- b) _var
- c) 1var
- d) var_1
- Answer: c) 1var
29. What is the output of the following code: ‘print(10 / 3)‘?
- a) 3.3333333333333335
- b) 3
August 24, 2024
- c) 3.0
- d) 10
- Answer: a) 3.3333333333333335
30. Which of the following is NOT an arithmetic operator in Python?
- a) +
- b) -
- c) *
- d) &&
- Answer: 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’‘
- Answer: b) ‘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()
- Answer: b) split()
33. Which of the following is NOT a valid Python data type?
- a) List
- b) Tuple
- c) Dictionary
- d) Array
- Answer: d) Array
34. What is the output of the following code: ‘print(“Hello” + ” ” + “World”)‘?
- a) Hello World
August 24, 2024
- b) HelloWorld
- c) “Hello World”
- d) Hello + World
- Answer: a) Hello World
35. Which operator is used for exponentiation in Python?
- a) ^
- b) **
- c) exp()
- d) pow()
- Answer: b)
36. Which of the following is a mutable data type in Python?
- a) String
- b) Tuple
- c) List
- d) Integer
- Answer: c) List
37. What is the output of the following code: ‘print(2**3)‘?
- a) 5
- b) 6
- c) 8
- d) 9
- Answer: c) 8
38. Which function is used to read input from the user in Python 3.x?
- a) input()
- b) raw_input()
- c) scan()
- d) read()
- Answer: a) input()
39. Which of the following statements will create a tuple in Python?
August 24, 2024
- a) t = [1, 2, 3]
- b) t = {1, 2, 3}
- c) t = (1, 2, 3)
- d) t = 1, 2, 3
- Answer: c) t = (1, 2, 3)
40. What is the output of the following code: ‘print(type([]))‘?
- a) <class ‘tuple’>
- b) <class ‘list’>
- c) <class ‘set’>
- d) <class ‘dict’>
- Answer: b) <class ‘list’>
41. Which of the following operators is used for string concatenation in Python?
- a) +
- b) &
- c) .
- d) concat()
- Answer: a) +
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
- Answer: 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
- Answer: a) 1
August 24, 2024
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()
- Answer: a) remove()
45. What is the output of the following code: ‘print(5 == 5)‘?
- a) True
- b) False
- c) Syntax Error
- d) 5
- Answer: a) True
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()
- Answer: a) tuple()
47. Which of the following is used to define a block of code in Python?
- a) Indentation
- b) Curly braces
- c) Parentheses
- d) Square brackets
- Answer: a) Indentation
48. Which function is used to get the type of an object in Python?
- a) type()
- b) isinstance()
- c) id()
- d) obj_type()
- Answer: a) type()
August 24, 2024
FILL-IN THE BLANK (SAMPLE).**
1. Python is an example of a -level programming language. (high)
2. In Python, strings are enclosed in or . (single, double)
3. Python’s core data types include , , and . (integers, floats, strings)
4. are used to document Python functions and modules. (docstrings)
5. Python uses to indicate a block of code. (indentation)
6. are objects in Python that cannot be changed after assignment. (tuples)
2 Marks Questions and Answers
1. What is a programming language? A programming language is a language used to specify a set of
instructions to a computer to carry out a specific task.
2. Define a program. A program is an ordered set of instructions to be executed by a computer to carry out
a specific task.
3. What is machine language? Machine language, also known as low-level language, is the language of
0s and 1s that is directly understood by the computer.
4. What is the difference between high-level language and machine language? High-level languages
are easier for humans to write and understand, whereas machine language is composed of binary code (0s
and 1s) and is directly understood by the computer.
5. Name any two high-level programming languages. Python and Java.
6. What is source code? Source code is a program written in a high-level language.
7. What is the role of a compiler? A compiler translates the entire source code into machine language as
a whole and generates error messages if any.
8. What is the role of an interpreter? An interpreter processes program statements one by one, translating
and executing them until an error is encountered or the program is successfully executed.
9. Define Python as a high-level language. Python is a high-level, interpreted, and case-sensitive program-
ming language known for its readability and simplicity.
10. What does it mean that Python is an interpreted language? Python being an interpreted language
means that its programs are executed by an interpreter, which processes each statement one by one.
11. How does Python handle case sensitivity? Python is case-sensitive, meaning identifiers like NUMBER
and number would be considered different.
12. Mention any two features of Python. Python is portable and platform-independent, and it has a rich
library of predefined functions.