CHAPTER 5
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.”
- 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?
- 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
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
- 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
- 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
- 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
- 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?
- 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
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()
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.
13. What is the extension
of a Python script file? The extension of a Python script file is .py.
14. Explain the interactive mode in Python.
In interactive mode, individual statements
can be executed instantaneously, and results are displayed immediately.
15. What is script mode in
Python? In script mode, a Python program is written
in a file, saved, and then executed as a whole.
16. What are Python keywords? Python
keywords are reserved words that have specific meanings to the interpreter and cannot be used as identifiers.
17. Define identifiers in Python. Identifiers are names used to identify
variables, functions, or other entities
in a program.
18. What are variables in Python? Variables in Python are names that refer to objects stored in memory.
19. How are comments added in Python?
Comments in Python are added using the # symbol;
everything following the # till the end of the line is treated as a comment.
20. What is an object
in Python? An object
in Python is an instance
of a data type that has a unique identity, attributes, and behavior.
21. What is implicit conversion? Implicit conversion is the automatic
conversion of one data type to another
by the interpreter.
22. What is explicit conversion? Explicit conversion is the manual conversion of one data type to another using functions like int(), float(),
str(), etc.
3 Marks Questions and Answers
1. Explain the process of program execution in Python using
an interpreter.
• Python uses an interpreter to execute programs. The interpreter
processes the program statements one
by one, translating and executing each statement sequentially until an error is
encountered or the entire program is
executed. If an error occurs, execution stops. This contrasts with a compiler, which translates the entire source code into object code before execution .
2. What is the significance of the Python
prompt »>?
• The »> prompt in Python indicates that the interpreter is ready
to accept instructions. This prompt is
displayed in the Python interactive mode, also known as the Python shell, where
users can type commands or statements to be executed
immediately .
3. Describe the use of indentation in Python.
• Indentation in Python is used to define the blocks of code. Unlike
other programming languages that use
braces or keywords, Python relies on indentation levels to group statements. Consistent indentation is crucial
because it directly
affects the program’s
structure and execution
.
4. Explain the concept of ‘interactive mode’ with an example.
• Interactive mode in Python allows users to type and execute Python
commands directly at the »> prompt. This mode is useful for testing and debugging code snippets. For example:
>>> print("Hello, World!") Hello, World!
This command
is executed immediately, and the result is displayed
on the screen .
5.
What are the rules for naming an identifier in Python?
• Identifiers in Python must follow
these rules:
1. Must start with a letter
(a-z, A-Z) or an underscore (_).
2. Can contain letters,
digits (0-9), and underscores.
3. Cannot start with a digit.
4. Python keywords cannot be used as identifiers.
5. Identifiers are case-sensitive .
6. Explain with an example
how variables are declared in Python.
• Variables in Python
are declared by assigning a value to a name. For example:
>>> x = 10
>>> name
= "Alice"
Here, x is an integer variable
with a value of 10, and name is a string variable
with a value of “Alice”
.
7. How does Python handle
data types?
• Python handles data types dynamically,
meaning variables do not need to be declared with a specific type. Python
supports various data types, including integers, floats, strings, lists,
tuples, dictionaries, and sets. The type of a variable
is determined at runtime based
on the value assigned to it .
8.
Describe the purpose
of comments in a Python
program.
• Comments in Python are used to document the code and make it easier
to understand. They are ignored by the interpreter and can be
single-line comments starting with # or multi-line comments enclosed in triple quotes (’’’ or “““). Comments help explain the logic and
purpose of the code, making it easier to maintain and collaborate with others .
9. Explain the significance of the id() function in Python.
• The id() function
in Python returns
the unique identity
(memory address) of an object.
This identity is guaranteed to be unique
and constant for the object
during its lifetime. The id() function
is useful for understanding the object’s behavior
and identity management in memory .
10.
Differentiate between None and False in Python
keywords.
• None is a special constant in Python representing the absence of a
value or a null value. It is often used
to signify that a variable has no value. False, on the other hand, is a Boolean
value indicating the logical false. It is used in logical operations
and comparisons. While None and False are distinct, both can be used in condition checks
where None evaluates to False in a Boolean
context .
11.
What is meant by ‘Python
is platform-independent’?
• Python is considered platform-independent because Python programs can run on various operating
systems without modification. This is possible
because Python code is interpreted, and the Python
interpreter abstracts the underlying platform
details. As long as the system has a compatible Python interpreter installed, the same Python code can run on Windows, macOS, Linux, and other platforms
.
12.
Describe how Python uses indentation for blocks and nested blocks.
• In Python, indentation is used to define the scope of loops,
functions, and other constructs. Con- sistent
indentation levels indicate a block of code. For nested blocks, each new block
is indented further, usually by four spaces. This
indentation helps Python understand the grouping of statements, replacing the need for braces or keywords used in other languages .
13.
Explain the term ‘portable’ in the context
of Python.
• The term ‘portable’ in the context
of Python refers
to the ability to write
Python code that can run on different operating systems and
environments without requiring changes. Python achieves portability through its interpreter, which
handles platform-specific details,
allowing the same code to execute on any system
with a compatible Python interpreter .
14.
What are Python libraries and why are they important?
• Python libraries are collections of modules and packages that
provide pre-written code to perform common tasks. They
are important because they save developers time and effort by offering reusable code for various functionalities, such as
data manipulation, web development, machine learning, and more. Popular Python libraries include NumPy, Pandas,
Matplotlib, and TensorFlow .
15.
Describe how to download and install Python.
•
To download and install
Python:
1. Visit the official
Python website (https://www.python.org/ ).
2. Download the installer for your operating
system.
3. Run the installer and follow the on-screen instructions.
4. Ensure
that the option to add Python to the system PATH is selected.
5. Verify the installation by opening a command prompt
or terminal and typing python
–version .
16. What is meant by ‘Python is free and open source’?
• Python being ‘free
and open source’
means that it is freely
available for anyone
to use, modify,
and distribute. The source code of Python
is openly accessible, allowing developers to contribute to its development and customize it as needed.
This openness fosters a large and active community that continually improves the language and its ecosystem .
5 Marks Questions and Answers
1. Discuss the differences between
a compiler and an interpreter.
• Translation Unit: A compiler translates the entire source code into machine code at once, while an interpreter translates one statement at a time.
• Execution Speed: Compiled
programs generally run faster because
the translation happens
before execution. Interpreted programs run slower as each instruction is translated during
execution.
• Error Detection: Compilers
detect errors in the entire
program during the compilation stage, while interpreters detect errors line by line, making it easier to debug incrementally.
• Intermediate Code: Compilers generate an intermediate object code that can be executed later,
while interpreters do not produce
an intermediate code.
• Usage: Interpreters are often used for scripting
and testing because of their immediate feedback,
whereas compilers are used for production software
due to their efficiency.
2. Discuss the various features
of Python that make it a preferred language for beginners.
• Simplicity: Python’s syntax
is clear and readable, making
it easy to learn and write code.
• Interpreted Language: Python’s
interactive mode allows
beginners to test code
snippets and see results immediately, facilitating learning.
• Extensive Libraries: Python has a rich set of libraries and frameworks that support various tasks such as web development, data analysis, and machine learning.
• Community Support: Python has a large and active community
that provides extensive resources, tutorials, and documentation, aiding
beginners in learning.
• Versatility: Python can be used for a wide range of applications, from simple scripting
to complex web applications, making
it a valuable skill for beginners.
3. Explain the concept of ‘everything is an object’
in Python with examples.
• Object-Oriented: In Python, every value is an object, and each object has a type, known as its class.
This applies to numbers, strings,
functions, classes, and even modules.
• Integers as Objects: For example,
when you create
an integer a = 5, a is an object
of type int.
• Strings as Objects: Similarly, when you create
a string s = “Hello”,
s is an object of type str.
• Functions as Objects: Functions in Python are objects too. For example,
def func(): pass defines a function func which is an object
of type function.
• Modules as Objects: Modules are objects as well. When you import a module like import math, the math module
is an object of type module.
4. Explain the different data types available in Python with examples.
• Integers: Whole numbers,
e.g., x = 10.
• Floats: Decimal numbers,
e.g., y = 10.5.
• Strings: Text data,
enclosed in quotes,
e.g., name = “Alice”.
• Lists: Ordered collections of items, e.g.,
my_list = [1, 2, 3, “apple”].
• Dictionaries: Collections of key-value pairs,
e.g., my_dict = {“key1”: “value1”, “key2”: “value2”}.
• Tuples: Immutable ordered
collections, e.g., my_tuple
= (1, 2, 3).
• Sets: Unordered collections of unique items,
e.g., my_set = {1, 2, 3}.
• Booleans: True or False values,
e.g., is_valid = True.
5.
Discuss the significance of Python in the context of modern programming and software develop-
ment.
• Versatility: Python’s ability
to handle various
domains such as web development, data science, artificial intelligence, and automation makes it highly
versatile.
• Productivity: Python’s
simple syntax and readability contribute to faster development and reduced maintenance costs.
• Community and Support: Python’s large community and extensive libraries provide robust sup- port and resources for developers.
• Adoption in Industry: Many leading companies and organizations use Python for their develop-
ment needs, enhancing
its credibility and demand in the job market.
• Educational Tool: Python’s simplicity and ease of learning make it an excellent language
for teach- ing programming in schools and universities.
6. Explain the use of comments in Python with examples and describe their importance.
• Single-line Comments: Use the # symbol, e.g., # This is a comment.
• Multi-line Comments: Use triple quotes, e.g., ’’’ This is a multi-line comment ’’’.
• Documentation: Comments
help in documenting the code, explaining what specific blocks or lines of code do.
• Debugging: Comments can be used to temporarily disable code for debugging purposes.
• Collaboration: Comments are essential for collaborative projects
as they help team members un- derstand
each other’s code.
7. Describe the rules for naming identifiers in Python and explain why these rules are important.
• Start with a Letter
or Underscore: Identifiers must begin with a letter
(a-z, A-Z) or an underscore (_).
• Contain Letters,
Digits, or Underscores: Subsequent characters can be letters, digits (0-9), or underscores.
• Case-sensitive: Identifiers are case-sensitive, meaning
Var and var are different.
• No Keywords: Keywords cannot be used as identifiers, e.g., def, class,
etc.
• Meaningful Names: Using meaningful names makes the code more readable and maintainable.
• Avoid Confusion: Following these rules
prevents errors and makes the code easier to understand and maintain.
8. Explain the concept of high-level and low-level programming languages and their differences.
• High-level Languages: These languages are closer to human languages and abstract away most of the hardware
details. Examples include
Python, Java, and C++.
• Low-level Languages: These languages are closer to machine code and provide little abstraction from the hardware.
Examples include Assembly
and Machine Code.
• Ease of Use: High-level languages
are easier to learn and use, while low-level languages
require more detailed
knowledge of the hardware.
• Portability: High-level languages are generally more portable across
different hardware platforms, whereas low-level languages
are specific to a particular type of hardware.
• Performance: Programs written in low-level
languages can be more efficient
and faster but are more complex to write and maintain compared
to high-level languages.
9.
Discuss the use of Python
in web development and provide
examples of popular
web services built with Python.
• Frameworks: Python has powerful web
frameworks like Django and Flask that simplify web de- velopment.
MOHAMMED
• Backend Development: Python
is widely used for server-side programming, handling requests,
and connecting to databases.
• APIs: Python is commonly used to develop RESTful APIs, facilitating communication between different parts of a web service.
• Popular Web Services: Examples of popular web services built with Python include Instagram, Pinterest, and Dropbox.
• Integration: Python can easily
integrate with other technologies and services, making
it a versatile choice for web development.
10.
THEEN
Explain with examples the different types of operators available in Python.
•
MA
Arithmetic Operators:
Used for mathematical operations, e.g., + (addition), - (subtraction), * (mul- tiplication), / (division).
• Comparison Operators: Used to compare
values, e.g., == (equal to), != (not equal to), > (greater
than).
• Logical Operators: Used to combine
conditional statements, e.g., and, or, not.
• Assignment Operators: Used to assign
values to variables, e.g., =, +=, -=.
11. Discuss the role of Python in education and why it is a good choice for learning
programming.
• Ease of Learning: Python’s simple
and readable syntax makes it an excellent
choice for beginners.
• Versatility: Python can be used for various
applications, from web development to data science,
providing a broad
learning experience.
• Active Community: Python’s large and active community offers extensive resources, tutorials, and support for learners.
• Immediate Feedback: Python’s
interactive mode allows
learners to test code snippets
and receive immediate feedback, facilitating learning.
• Real-world Applications: Learning
Python provides practical skills that are in high demand in the job market, enhancing career prospects.
12. Explain various
types of Errors.
• Syntax Errors: Errors in the structure
of the code, such as missing colons, parentheses, or incorrect indentation.
• Runtime Errors: Errors that occur during program execution, such as division
by zero or accessing a variable
that has not been defined.
• Logical Errors: Errors in the logic of the code that produce
incorrect results, even though the code runs without crashing.
EXERCISES (CHAPTER END QUESTIONS)
Question 1
Which of the following identifier names are invalid
and why?
1. Serial_no.
2. 1st_Room
3. Hundred$
4. total-Marks
5. True
Answer:
• Identifier name can’t contain dot.
• 1st_Room: Invalid because
identifiers cannot start with a digit.
• $ symbol is special character that can’t be part of an identifier name.
• total-Marks: Invalid because
identifiers cannot contain
hyphens (-).
•
True: Invalid because True is a keyword in Python and cannot be used as an identifier.
Question 2
Write the corresponding Python assignment statements:
1. Assign 10 to variable length
and 20 to variable breadth.
2. Assign the average
of values of variables length
and breadth to a variable
sum.
3. Assign a list containing strings
‘Paper’, ‘Gel Pen’, and ‘Eraser’
to a variable stationery.
4. Assign the strings
‘Mohandas’, ‘Karamchand’, and ‘Gandhi’ to variables first,
middle and last.
5. Assign the concatenated value of string variables first, middle and
last to variable fullname. Make sure to incorporate blank spaces appropriately between different parts of names.
Answer:
1. length = 10
2. sum = (length
+ breadth) / 2
3.
R THEEN
stationery = [‘Paper’, ‘Gel Pen’, ‘Eraser’]
4.
first = ‘Mohandas’
5. fullname = first
+ ’ ’ + middle
+ ’ ’ + last
Question 3
Write logical expressions
corresponding to the following statements in Python and evaluate the expres- sions (assuming
variables num1, num2, num3, first, middle, last are already
having meaningful values):
1. The sum of 20 and –10 is less than 12.
2. num3 is not more than 24.
3. 6.75 is between
the values of integers num1 and num2.
4. The string ‘middle’
is larger than the string
‘first’ and smaller
than the string ‘last’.
5. List Stationery is empty.
Answer:
1. (20 + -10) < 12 # True
2. num3 <= 24
3. num1 <= 6.75 <=num2
4. first < middle < last
5. len(stationery) == 0
Question 4
Add a pair of parentheses to each expression so that it evaluates to True.
1. 0 == 1 == 2
2. 2 + 3 == 4 + 5 == 7
3. 1 < -1 == 3 > 4
Answer:
1. 0 == (1 == 2)
2. 2 + (3 == 4) + 5 == 7
3. (1 < -1) == (3 > 4)
THEEN
Question 5
Write the output
of the following:
1.
num2 = num1 + 1 num1 = 2 print(num1, num2)
2.
num1, num2 = 2, 6
3.
Answer:
1. 2 5
2. 6 4
3. This code will result in an error because num3 is not defined.
Question 6
Which data type will be used to represent the following data values and why?
1. Number of months
in a year
2. Resident of Delhi
or not
3. Mobile number
4. Pocket money
5. Volume of a sphere
6. Perimeter of a square
7. Name of the student
8. Address of the student
Answer:
1. int - The number of months is a whole number.
2. bool - It is a binary state
(True or False).
3. str - Mobile
numbers can contain
leading zeros and are not used for calculations.
4. float - Pocket
money can have decimal values.
5. float - Volume
can be a decimal value.
6. float - Perimeter can be a decimal value.
7. str - Names
are textual data.
8. str - Addresses
are textual data.
Question 7
Give the output
of the following when num1 = 4, num2 = 3, num3 = 2:
1. += num2 + num3
2. num1 = num1 ** (num2 + num3)
3. num1 **= num2 + num3 4. num1 = ‘5’ + ‘5’ print(num1)
5. print(4.00 / (2.0 + 2.0))
6. num1 = 2 + 9 * ((3 * 12) - 8) / 10
print(num1)
7.
num1 = 24 // 4 // 2 print(num1)
R
8. num1 = float(10)
9. num1 = int(‘3.14’)
10. print(‘Bye’ == ‘BYE’)
11. print(10
!= 9 and 20 >= 20)
12. print(10
+ 6 * 2 ** 2 != 9 // 4 - 3 and 29 >= 29 / 9)
13. print(5
% 10 + 10 < 50 and 29 <=
29)
14. print((0
< 6) or (not(10 == 6) and (10 < 0)))
Answer:
1. 9
2. 1024
3. 1024
4. 55
5. 1.0
6. 27.2
7. 3
8. 10.0
9. Error (cannot convert
‘3.14’ to an integer)
10. False
11.
True
12.
True
13.
True
14.
True
Question 8
Categorise the following
as syntax error,
logical error or runtime error:
1. 25 / 0
2. num1 = 25; num2 = 0; num1/num2
Answer:
1. Runtime error (division
by zero)
2. Runtime error (division
by zero)
Question 9
A dartboard of
radius 10 units and the wall it is hanging on are represented using a
two-dimensional coordinate system,
with the board’s center at coordinate (0,0). Variables x and y store the
x-coordinate and the y-coordinate of a dart that hits the dartboard. Write a Python expression using variables x and y that evaluates to True if the dart hits (is within)
the dartboard, and then evaluate the expression for these dart coordinates:
1. (0,0)
2. (10,10)
3. (6, 6)
4. (7,8)
Answer:
(x**2 + y**2) <= 100
1. True (0,0 is at the center)
2. False (10,10 is outside the dartboard)
3. True (6,6 is within the dartboard)
4. True (7,8 is within the dartboard)
Question 10
Write a Python program
to convert temperature in degree Celsius
to degree Fahrenheit. If water boils at 100 degree C and freezes
at 0 degree C, use the program
to find out what is the boiling
point and freezing
point of water on the Fahrenheit scale.
Answer:
boiling_point_C = 100
freezing_point_C = 0
# Conversion formula: F
=
C
*
9/5
+
32 boiling_point_F = boiling_point_C * 9/5 + 32 freezing_point_F = freezing_point_C * 9/5 + 32 print(f"Boiling point of water: {boiling_point_F}°F")
print(f"Freezing point
of water: {freezing_point_F}°F")
Output: Boiling point of water: 212.0°F Freezing point of water: 32.0°F Question
11
Write a Python program
to calculate the amount payable
if money has been lent on simple
interest. Prin- cipal or money lent = P, Rate of interest = R% per annum and Time = T years. Then Simple Interest (SI)
= (P x R x T)/ 100. Amount
payable = Principal + SI. P, R and T are given as input to the program.
Answer:
P = float(input("Enter the principal amount:
")) R = float(input("Enter the rate of interest: ")) T = float(input("Enter the time in years:
"))
SI = (P
\* R \* T)
/ 100 amount\_payable = P + SI print(f"Simple Interest: {SI}")
print(f"Amount Payable:
{amount\_payable}")
Question 12
Write 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.
Answer:
x = float(input("Enter the number of days A takes to complete the work: ")) y = float(input("Enter the number
of days B takes to complete the work: ")) z = float(input("Enter the number
of days C takes to complete the work: ")) total_days = (x * y
* z) / (x *
y + y * z
+ x * z)
print(f"The work will be completed in {total_days} days if A, B, and C work together.")
Question 13
Write a program to enter two integers and perform all arithmetic operations on them. Answer:
a = int(input("Enter the first integer: ")) b = int(input("Enter the second
integer: ")) print(f"Addition: {a + b}")
print(f"Subtraction:
{a - b}") print(f"Multiplication: {a
* b}") print(f"Division:
{a / b}") print(f"Modulus: {a
% b}") print(f"Exponentiation: {a ** b}") print(f"Floor Division:
{a //
b}")
Question 14 Write a program to swap two numbers using
a third variable.
Answer:
a = int(input("Enter the first number: ")) b = int(input("Enter the second
number: ")) temp = a
a = b
b = temp
print(f"After swapping: a = {a}, b = {b}")
Question 15
Write a program to swap two numbers without
using a third variable. Answer:
a = int(input("Enter the first number: ")) b = int(input("Enter the second
number: ")) a, b = b, a
print(f"After swapping: a = {a}, b = {b}")
Question 16
Write a program to repeat the string “GOOD MORNING” n times. Here ‘n’ is an integer
entered by the user.
Answer:
n = int(input("Enter the number
of times to repeat the string: ")) result = "GOOD MORNING "
* n
print(result)
Question 17
Write a program to find average
of three numbers.
Answer:
num1 = float(input("Enter the first number: ")) num2 = float(input("Enter the second
number: ")) num3 = float(input("Enter the third number: ")) average
= (num1 + num2 +
num3) / 3
print(f"The average
of the three numbers is {average}")
Question 18
Write a Python program
to find the volume of spheres with radius 7cm, 12cm, 16cm, respectively. Answer:
import math
# Input from the user for three spheres
(assuming fixed number)
radius1 = float(input("Enter the
radius of sphere 1 in cm: ")) radius2
= float(input("Enter the
radius of sphere 2 in cm: ")) radius3
= float(input("Enter the
radius of sphere 3 in cm: ")) # Calculating and printing volumes for each sphere
volume1 = (4/3) * math.pi *
radius1**3 volume2 = (4/3) * math.pi *
radius2**3 volume3 = (4/3) * math.pi *
radius3**3 # Printing
the volumes
print(f"The volume
of a sphere with radius
{radius1} cm is {volume1} cubic cm") print(f"The volume of a sphere
with radius {radius2} cm is {volume2} cubic cm") print(f"The volume of a sphere
with radius {radius3} cm is {volume3} cubic cm")
Question 19
Write a program that asks
the user to enter their name and age. Print
a message addressed to the user that tells the user the year in which they will turn 100 years old.
Answer:
import datetime
name = input("Enter your
name: ") age = int(input("Enter your age: "))
current_year =
datetime.datetime.now().year year_turning_100 = current_year +
(100
- age)
print(f"Hello, {name}! You will turn 100 years old in the year {year_turning_100}.")
Question 20
The formula
E=mc² states that the equivalent energy (E) can be calculated as the mass (m) multiplied by the speed of light (c = about 3×1083
×10^83×108 m/s) squared.
Write a program that accepts
the mass of an object
and determines its energy.
Answer:
c = 3 * 10**8 # speed of light in m/s
mass = float(input("Enter the mass of the object in kg: ")) energy = mass * c**2
print(f"The energy
equivalent of the mass is {energy} joules.")
Question 21
Presume that a ladder
is put upright against a wall. Let variables length
and angle store the length
of the ladder and the angle that it forms with the ground as it leans
against the wall. Write a Python program to compute
the height reached
by the ladder on the wall for the following
values of length
and angle:
1. 16 feet and 75 degrees
2. 20 feet and 0 degrees
3. 24 feet and 45 degrees
4. 24 feet and 80 degrees
Answer:
#import the math module, to use sin & radians
function
import math
length
= int(input("Enter the length of the ladder:
")) degrees = int(input("Enter the alignment degree: ")) #Converting degrees to radian
radian = math.radians(degrees)
#Computing sin value
sin = math.sin(radian)
# Calculating height
and rounding it off to 2 decimal
places
height = round(length * sin,2)
#displaying the output
print("The height reached
by ladder with length",length,"feet and aligned
↪ at",degrees,"degrees is",height, "feet.")
Important Questions
1. Mention the features
of Python programming language.
2. Mention the two modes of execution in Python IDLE.
3. What is Keyword?
Mention some of the keywords
in Python.
4. What is Identifier? Mention the rules for naming an Identifier in Python?
5. Explain the statement: “Everything is an Object in Python”.
6. Mention the names
of various data types in Python.
7. Menton the names of the two sequence
data types in Python?
8. Distinguish between Mutable
and immutable data types. Give a suitable
example.
9. What is Operator?
Explain different types of operators
in Python.
10. What is an Expression?
11. What is type conversion? Explain two types of type conversion with suitable examples.
12. What is Debugging? Explain various types of Errors.