UNIT 2
CHAPTER-2 : GETTING STARTED WITH PYTHON
Getting Started (Important Aspects)
Python was developed by Guido van Rossum at the National Research Institute for
Mathematics and Computer Science in the Netherlands.
Python is a widely used general-purpose, high-level programming language.
Python is free to use, even for commercial products, because of its OSI-approved open
source license.
Python is strongly object-oriented in the sense that everything is an object including
numbers, strings and functions.
Python has Interactive mode and script mode.
Python IDLE – Integreated development Learning Enviroment
IDLE (Integrated Development and Learning Environment) is an integrated development environment
(IDE) for Python.
Python Interactive vs Script Mode
The interactive mode of Python is also called REPL.
REPL stands for ‘Read-Eval-Print-Loop’
the interactive mode is a command-line shell that gives immediate feedback for each statement
Interactive mode is beneficial after you simply wish to execute basic Python commands
The >>> indicates that the Python shell is ready for execution in the interactive mode.
Code does not get saved in Interactive Mode
Script Mode
Preferred for writing long codes
Using Script mode is quite easy, you have to write your code in a text file and save the particular file
with a ‘.py’
In a standard Python shell, you can simply click “FILE” then choose “NEW” or press “ctrl+N” to
open a blank script where you can input your code.
Script Mode allows Interpreter to interpret the code
Points to Remember :
Python Supports interactive mode in which you can enter results from a terminal right to the
language, allowing interactive testing and debugging of snippets of code.
In script mode, we type the programs in a file and then use the interpreter to execute the
contents of the file.
2/1
PyScripter is a full-featured stand- alone Python IDE with Integrated Interpreter, debugger ,
Syntax Error Highlighting and many more features.
An identifier is a name used to identify a variable, function, class, module, or other object.
A variable in Python is defined through assignment.
The basic data types used in Python are-
[Link]
a)Integer Number
b)Long Integer Number
c)Floating Point Number
d)Complex Number
2. None
3. Sequence
a) Strings
b) Tuples
c) List
4. Sets
5. Mappings
a) Dictionary
A mutable variable is one whose value may change in place, whereas in an immutable
variable change of value will not happen in place.
Operators and Operands in Python (Arithmetic, relational and logical operators), operator
precedence, Expressions and statements (Assignment statement)
Taking input (using raw_input() and input ()) and displaying output (print statement); Putting
comments.
A hash sign (#) that is not inside a string literal begins a single line comment.
Multiline comments starts from ###.
Python provides the following operators – Arithmetic, Relational, Logical, Assignment and
other special operators
Arithmetic operators are used for various mathematical calculations. They include the
following :
OperatorDescription Example
Addition - Adds values on either side of a=10, b=20, a + b
+
the operator will give 30
Subtraction - Subtracts right hand a=10, b=20, a - b
-
operand from left hand operand will give -10
Multiplication - Multiplies values on a=10, b=20, a * b
*
either side of the operator will give 200
Division - Divides left hand operand by a=10, b=20, b / a
/
right hand operand will give 2
Modulus - Divides left hand operand by
a=10, b=20, b %
% right hand operand and returns the
a will give 0
remainder
a=10, b=20, a**b
Exponent - Performs exponential
** will give 10 to the
(power) calculation on operators
power 20
2/2
Floor Division - The division of
9//2 is equal to 4
operands where the result is the quotient
// and 9.0//2.0 is
in which the digits after the decimal
equal to 4.0
point are removed.
Relational Operator compares the value of any two operands and produce a result
TRUE or FALSE
OperatorDescription Example
Checks if the value of two operands a=10, b=20, a == b)
==
are equal or not, if yes it returns true. is not true.
Checks if the value of two operands
a=10, b=20, (a != b)
!= are equal or not, if values are not
is true.
equal then condition becomes true.
a=10, b=20, (a <>
Checks if the value of two operands
b) is true. This is
<> are equal or not, if values are not
similar to !=
equal then condition becomes true.
operator.
Checks if the value of left operand is
greater than the value of right a=10, b=20, (a > b)
>
operand, if yes then condition is not true.
becomes true.
Checks if the value of left operand is a=10, b=20, (a < b)
<
less than the value of right operand. is true.
Checks if the value of left operand is
>= greater than or equal to the value of (a >= b) is not true.
right operand,
Checks if the value of left operand is
less than or equal to the value of right
<= (a <= b) is true.
operand, if yes then condition
becomes true.
Logical operators connect two relational expressions and produce a truth value.
OperatorDescription Example
If both the operands are true then the a=10, b=20,
and
condition becomes true. (a and b) is true.
If any of the two operands are non zero a=10, b=20,
or
then the condition becomes true. (a or b) is true.
Use to reverses the logical state of its a=10, b=20,
not operand. If a condition is true then Logical not(a and b) is
NOT operator will make false. false.
Assignment operator and arithmetic assignment operators -
OperatorDescription Example
Simple assignment operator, Assigns
c = a + b will assign
= values from right side operands to left
value of a + b into c
side operand
c += a is equivalent
+= Add AND assignment operator
to c = c + a
2/3
c -= a is equivalent
-= Subtract AND assignment operator
to c = c - a
c *= a is equivalent
*= Multiply AND assignment operator
to c = c * a
c /= a is equivalent
/= Divide AND assignment operator
to c = c / a
c %= a is equivalent
%= Modulus AND assignment operator
to c = c % a
c **= a is equivalent
**= Exponent AND assignment operator
to c = c ** a
Floor Division and assigns a value c //= a is equivalent
//=
operand to c = c // a
Python has two key functions to deal with end-user input, one called raw_input() and one
called input().
input() works both with number and string data types but it returns the output in string type.
The input function allows the user to provide a prompt string. When the function is evaluated,
the prompt is shown. The user of the program can enter the name and press return. Input()
value returns a string value.
Python’s print statement, paired with the string format operator ( % ), supports string
substitution. For ex:
>>> print "%s is number %d!" % ("Python", 1)
Python is number 1!
%s substitute a string, %d indicates an integer substitution and %f for floating point
numbers.
The print function can print any number of values separated by commas.
Common Errors
While taking input for integer values, convert the data with int() in input function.
Keywords cannot use as an identifiers.
Use spacing properly while writing mathematical expressions.
MULTIPLE CHOICE QUESTIONS : (1 Mark)
1. Which of the following is an invalid variable?
a. my_string_1 b. 1st_string c. Foo
2. What is the return type of id() function?
a. Bool b. list c. int d. double
3. Predict the output:
a=str(6/4)
b="6/4"
print(a==b)
a. True b. False
2/4
4. What is the output of this expression, 3*1**3?
a. 27 b. 9 c. 3 d. 1
5. Select all options that can print
hello-how-are-you
a. print(‘hello’, ‘how’, ‘are’, ‘you’)
b. print(‘hello’, ‘how’, ‘are’, ‘you’ + ‘-‘ * 4)
c. print(‘hello-‘ + ‘how-are-you’)
d. print(‘hello’ + ‘-‘ + ‘how’ + ‘-‘ + ‘are’ + ‘you’)
6. Identify any false statement:
(i)Compile time errors are usually easier to detect and to correct than run-time errors.
(ii) Logical errors can usually be detected by the compiler.
a. (i) b. (ii) c. none
7. State True or False.
(i) Python shows an error whenever you assign a numeric value with comma in it.
(ii) Assignment of same value to multiple variables in a single statement is allowed in python.
(iii) In python ‘is’ and ‘is not’ are two membership operators.
(iv) If a = ‘Small’, b = ‘World’ then the expression a and not b will yield ‘Small’
a. (i) True (ii) False (iii) False (iv) True
b. (i) True (ii) False (iii) True (iv) False
c. (i) False (ii) True (iii) False (iv) True
d. (i) False (ii) False (iii) True (iv) True
8. The extension of Python file is given as –
a. .ppt b. .py c. .pdoc d. .ppp
9. Which of the following is an invalid statement ?
a. I=J=K=50
b. I,J,K=50,60,70
c. I J K =50 60 70
d. I_J_K=70
10. What will be the output of the following code ?
x,y=2,6
x,y=y,x+2
print(x,y)
a. 6 6 b. 4 4 c. 4 6 d. 6 4
11. The reserved words used by Python interpreter to recognize the structure of a program are
termed as
a. Keywords b. Identifiers c. Tokens d. Literals
2/5
12. Operators that act upon two operands are referred as …..
a. Unary operator b. Binary Operator c. Assignment Operator d. None
13. The Error that occurs during the execution of the program is known as ….
a. syntax error b. Semantic error c. Run time error d. none
14. Single Line comments in Python begin with …… symbol.
a. # b. % c. ; d. “ “
15. Which of the following operator is floor division ?
a. > b. / c. // d. %
ASSERTION and REASONING( 1 Mark)
16. Assertion : Data type in Python are bound to a variable at compile time
Reasoning : Python supports dynamic typing
a. Both Assertion and Reasoning are correct
b. Assertion is correct but explanation provided is incorrect
c. Assertion is incorrect but the reasoning is valid in Python
d. Both Assertion and Reasoning are incorrect
17. Assertion – type(0b1001) will return a string
Reasoning – a string is a combination of alpha numeric characters
a) Both Assertion and reasoning are correct
b) Assertion is correct but reasoning is not the reason for it
c) Both Assertion and Reasoning are incorrect
d) Assertion is not true but Reasoning is true in Python
18. Assertion: Data type in python are bound to the variable at compile time
Reason: Python supports dynamic typing
a) Both Assertion and reasoning are correct
b) Assertion is correct but reasoning is not the reason for it
c) Both Assertion and Reasoning are incorrect
d) Assertion is not true but Reasoning is true in Python
VERY SHORT ANSWER : (1 mark questions)
19. Write a statement to assign the value of (a*a) + (b*b) to a variable.
20. I want to divide 1 by 3 and get a result like: 0.333333333333. What is the exact command to do
this?
21. What will be the output of 15.0/3?
22. What does the modulus operator do?
23. Mention the use of following escape sequence
a. \n
b. \t
24. If a=70 and b=10 then determine the result of the following:
2/6
a. a/b
b. a% b
25. What is the purpose of using comments in a program?
26. What is an assignment statement?
27. What will be the output of the following:
a. i=30*15/3
b. i=30/15*3
28. What is the result of the following expression :
p>=q && (p+q) > p
a. P=3,q=0
b. P=5,q=5
29. Predict the output of :
a. print(type("17"))
b. print(type("3.2"))
30. How can you determine the type of a variable in python?
31. Is the following a legal variable name in Python : A_good_grade_is_A+
32. What is printed when the following statements execute?
n = input("Enter your age: ")
# user enters a value of 16
print ( type(n) )
33. What will be the output of :
a. print(2 ** 3 ** 2)
b. print((2 ** 3) ** 2)
34. What will be the value of variables a and b in the following code:
a=5
b=a
print(a,b)
a=3
print(a,b)
35. What does the >>> prompt indicates?
36. What is the order of the arithmetic operations in the following expression. Evaluate the
expression.
2 + (3 - 1) * 10 / 5 * (2 + 3)
37. Add parenthesis to the expression 6 * 1 - 2 to change its value from 4 to -6.
38. Take the sentence: All work and no play makes Jack a dull boy. Store each word in a
separate variable, then print out the sentence on one line using print.
SHORT ANSWER : (2 mark questions)
[Link] is a python IDLE?
2/7
40. What is a variable? What are the rules to name a variable.
[Link] is an expression? Explain with examples.
[Link] will be the type of the following result :
i. 3.14 * 7 * 7
ii. Hello * 26
43. If a car travels at a speed of 10 Km/hr, how much distance will it cover in 50 mins. If the driver
increases the speed to 15 Km/hr then how much distance can be covered.
44. What is the difference between = and == operators.
45. For any two given int values, return their sum. If the two values are the
same, then return double their sum.
46. What is an operator? Explain with the help of examples.
47. Write a program in script mode to add two numbers and print their sum and product.
48. Write Statements to calculate the following:
i. Area of circle with radius 12.
ii. Volume of a sphere of radius 7.
iii. Area of room whose length is 40.53 and breadth is 34.56
iv. A book has a price of 425 Rs and shopkeeper is offering a discount of 15%. Calculate its
price after discount.
49. What is a keyword in Python? In what colour is it displayed in code editor window?
50. Write a program to calculate volume and surface of a cylinder whose radius is given by the user.
51. What will be the output of the following statements if the value of variable str=”HelloWorld”
a. Print str b. Print str[0] c. Print str[2:5] d. Print str[2:] e. Print str *2
52. What will be the output of the following statements if the value of variable
list=[‘abcd’,786,’xyzw’,’892’]
a. print list[] b. print list[0] [Link] list[1:3] [Link] list[2:]
53. Can we convert a string data type to integer. If yes, how?
54. What is a statement? Explain by giving examples.
55. What is concatenation, and on what type of variables (integers/floats/strings) does it operate on?
56. Differentiate between the following with suitable examples :
Variable and constant
Number and string data type
57. What is printed when the following statements execute?
day = "Thursday"
day = 32.5
day = 19
print(day)
[Link] value is printed when the following statement executes?
a. print (18 / 4) b. print (18 % 4) c. print (18 // 4)
LONG ANSWER: (3 mark questions)
2/8
[Link] between the following:
i. Mutable and immutable variables
ii. A statement and an expression.
60. Explain the importance of data types.
61. Mention the rules for naming an identifier. Give appropriate examples.
62. Which of the following are invalid variable names and why?
a) MarksSecured
b) Mr_obt
c) 123subj
d) subj-sc
e) TOTAL
f) mark in math
g) perc%
h) $name
63. Why are comments placed in a C++ program? What are the various ways in which comments can
be added to a program?
64. Write codes to do the following :
a) Assign values 5,10,15 to variables x,y,z in a single statement.
b) Accept input from the user in three different variables in a single statement.
65. Write a program to convert Celsius temperature into Fahrenheit temperature.
66. Write a program to convert Fahrenheit temperature into Celsius temperature.
67. Write a program to find the larger of two numbers.
68. Evaluate the following expressions:
a) 3*(3*(3*len(“ab”)))
b) (60<110/0) and (15<150)
c) len(“helloworld”)==100/10
d) len(“helloworld”)==100/10 and 200/20
69. What will be the output of the following if my_age=29 and my_height=104
a. print “I am %s inches tall” % my_heigth
b. print “ My age is %d” % my_age
c. print “There are %d days in a week” %7
70. Write a program to find roots of a quadratic equation.
71. Write a program to find whether a number entered by the user is positive or negative.
72. Rohit gets a basic pay of Rs.8000. His dearness Allowance is 40% of basic salary and house rent
allowance is 20% of the basic salary. Calculate his gross salary.
73. Write a program to calculate simple interest.
74. Many people keep time using a 24 hour clock (11 is 11am and 23 is 11pm, 0 is midnight). If it is
currently 13 and you set your alarm to go off in 50 hours, it will be 15 (3pm). Write a Python
program to the above problem. Ask the user for the time now (in hours), and then ask for the
number of hours to wait for the alarm. Your program should output what the time will be on the
clock when the alarm goes off.
75. Write a program to calculate area of a triangle using hero’s formula.
76. Write a program to calculate volume and surface area of a cuboid whose length, breadth and
height are given.
2/9
77. Name the days of the week from 0-6 where day 0 is Sunday and day 6 is Saturday. If you go on a
holiday leaving on day number 3 (a Wednesday) and you return home after 10 nights. Write a
program which asks for the starting day number, and the length of your stay, and it will tell you
the number of day of the week you will return on.
78. Use IDLE to do the following:
i. Calculate total and average of marks scored in five subjects
ii. Find whether a number is even or odd.
iii. Find whether a number is divisible by 3 .
CASE BASED STUDY QUESTIONS(4 Marks)
79. (a) What are escape sequences? Name any one escape sequence.
(b) How do you print escape sequences as printable characters?
(c ) Based on your concepts in a) and b) what will be the output of the below statement?
print('c:\naveen\temp\a jpg'.'fi lc is opened',sep='\n')
80. Harshit has written a program to calculate in how many days a work will be completed by
three persons A, B and C together. A, B, C take x days, y days and z days respectively to do
the job alone. The formula to calculate the number of days if they work together is
xyz / (xy +yz +xz) days where x, y, and z are given as input to the program.
HOTS
81. The following statement produces no output when not run in the shell.
3.14 * 6 * 6
Modify it to produce output.
82. What's the difference between input() and raw_input() ?
83. The following statement produced an output of 13 and not 20. Explain the reason.
x=7+3*2
84. Why is Python called a strongly object oriented language.
85. Enter the following code on the prompt:
>>> 1 == 1
>>> "1" == "1"
2 / 10
>>> 1 == "1"
Why does the third line returns false, while the first 2 lines are true?
ANSWERS
MCQ
1. B 2. D 3. B 4. C 5. C, D 6. B 7. C 8. B 9. C
10. B 11. A 12. B 13. C 14. A 15. C
ASSERTION AND REASONING
16. C 17. C 18. D
2 / 11