Unit 1: Python Environment Setup and Basics - Subjective Questions
CSR101 — Python Programming • Practice Questions with Detailed Answers
20 questions
Explain the steps involved in installing Python using Anaconda and describe how to launch and use Jupyter Notebook.
Anaconda installation and Jupyter usage:
- Download the appropriate Anaconda distribution for the operating system from the official website.
- Run the installer and select the required installation options.
- Add Anaconda to the system path if necessary, or use the Anaconda Navigator application.
- Open Anaconda Navigator and launch Jupyter Notebook.
- In Jupyter Notebook, create a new Python notebook using the Python 3 kernel.
- Enter Python code into cells and execute a cell using
Shift + Enter. - Save the notebook with the
.ipynbextension.
Anaconda provides Python along with useful libraries and tools, while Jupyter supports interactive programming, documentation, visualization, and experimentation.
Compare Anaconda, Jupyter Notebook, and Visual Studio Code as tools for Python development.
Comparison:
- Anaconda: A Python distribution that includes the interpreter, package manager, libraries, and development tools. It is especially useful for data science and scientific computing.
- Jupyter Notebook: An interactive environment where code, output, mathematical expressions, and explanatory text can be combined in notebook cells. It is suitable for learning, analysis, and demonstrations.
- Visual Studio Code: A general-purpose source-code editor that can be extended with Python extensions. It supports debugging, source control, project management, and script development.
Anaconda focuses on Python distribution and package management, Jupyter focuses on interactive execution, and VS Code focuses on structured software development.
Describe the basic syntax rules of Python and explain how indentation, comments, identifiers, and statements are used.
Python syntax rules:
- Python uses indentation to define blocks of code instead of braces. Consistent spaces, commonly four, must be used.
- A comment begins with
#and is ignored during execution. - An identifier is a name given to variables, functions, or other objects. It may contain letters, digits, and underscores, but it cannot begin with a digit or be a reserved keyword.
- A statement is an instruction executed by Python, such as an assignment or function call.
- Python is case-sensitive, so
valueandValueare different identifiers. - A colon
:is generally placed after statements that introduce a block, such asif,for, orwhile.
Example:
if temperature > 30:
print("Hot day")The indentation determines which statement belongs to the if block.
Explain variables and common Python data types with suitable examples.
A variable is a name that refers to a value in memory. Python variables do not require an explicit type declaration because the type is inferred from the assigned value.
Examples of common data types include:
int: whole numbers, such as25float: decimal numbers, such as3.14complex: complex numbers, such as2 + 3jbool: logical values, such asTrueandFalsestr: text, such as"Python"list: ordered and mutable collection, such as[1, 2, 3]tuple: ordered and immutable collection, such as(1, 2, 3)set: unordered collection of unique values, such as{1, 2, 3}dict: collection of key-value pairs, such as{"name": "Asha"}
Example:
age = 20
name = "Asha"
marks = 85.5
passed = TrueThe type() function can be used to inspect the type of a value.
Explain arithmetic, assignment, comparison, logical, membership, and identity operators in Python.
Python operators:
- Arithmetic operators:
+,-,*,/,//,%, and**perform calculations. - Assignment operators:
=,+=,-=,*=, and/=assign or update values. - Comparison operators:
==,!=,>,<,>=, and<=compare values and produce Boolean results. - Logical operators:
and,or, andnotcombine or reverse Boolean expressions. - Membership operators:
inandnot intest whether a value occurs in a sequence or collection. - Identity operators:
isandis nottest whether two references point to the same object.
Example:
x = 10
print(x >= 5 and x < 20)
print(3 in [1, 2, 3])Comparison and logical operators produce either True or False.
What is an expression in Python? Explain how expressions are evaluated using operators and operands.
An expression is a combination of values, variables, operators, and function calls that Python evaluates to produce a result. The values and variables are called operands, while symbols or keywords such as + and and are called operators.
Examples:
result = 4 + 5 * 2
average = total / count
valid = age >= 18 and citizen is TrueIn the first expression, multiplication is performed before addition, so the result is . Parentheses can be used to specify the desired order:
result = (4 + 5) * 2This expression produces . Expressions may produce numbers, strings, Boolean values, or other objects.
Explain operator precedence and associativity in Python. Evaluate the expression 3 + 4 * 2 ** 2 - 6 / 3 step by step.
Operator precedence determines which operator is applied first, while associativity determines the evaluation direction when operators have the same precedence. A simplified order is:
- Parentheses
- Exponentiation
** - Multiplication, division, floor division, and modulus
- Addition and subtraction
- Comparisons
notandor
For the expression:
Evaluation proceeds as follows:
- Exponentiation:
- Multiplication and division: and
- Addition and subtraction:
Therefore, the result is . Parentheses should be used when they improve clarity or alter the default order.
Describe Python input and output operations. Write a program that accepts two numbers and displays their sum.
Python uses the input() function to accept data from the user and the print() function to display output. The value returned by input() is always a string, so it must be converted when numeric input is required.
first = float(input("Enter the first number: "))
second = float(input("Enter the second number: "))
sum_value = first + second
print("The sum is:", sum_value)In this program:
input()reads values from the keyboard.float()converts the entered text into a decimal number.- The
+operator calculates the sum. print()displays the result.
The print() function can also use keyword arguments such as sep and end to control formatting.
Explain Python modules and describe how the math module can be imported and used.
A module is a Python file containing definitions such as functions, variables, and classes. Modules support code organization and reuse.
The math module provides mathematical constants and functions. It can be imported in several ways:
import math
print(math.sqrt(25))
print(math.pi)A specific function can be imported as follows:
from math import factorial
print(factorial(5))An alias may also be used:
import math as m
print(m.ceil(4.2))Common functions include sqrt(), pow(), ceil(), floor(), factorial(), and trigonometric functions. Importing modules avoids rewriting commonly used code and improves program structure.
Explain how text is represented in Python and discuss string creation, indexing, slicing, and immutability.
Python represents text using the string data type, written as str. Strings are sequences of Unicode characters and can be enclosed in single quotes, double quotes, or triple quotes.
text1 = 'Python'
text2 = "Programming"
text3 = """This is a multiline string."""Strings support indexing and slicing:
word = "Python"
print(word[0]) # P
print(word[-1]) # n
print(word[1:4]) # y thon portion: "yth"The first character has index , and negative indices count from the end. Strings are immutable, meaning their individual characters cannot be changed directly. A new string must be created instead:
word = "Python"
word = "J" + word[1:]Python uses Unicode, allowing strings to represent text from many languages and writing systems.
Discuss important string methods and operations in Python with examples.
Python provides many operations and methods for processing strings.
- Concatenation joins strings using
+. - Repetition uses
*. len()returns the number of characters.lower()andupper()change letter case.strip()removes leading and trailing whitespace.split()divides a string into a list.join()combines sequence elements.replace()substitutes part of a string.find()searches for a substring.
Example:
text = " Python Programming "
clean = text.strip()
print(clean.upper())
print(clean.replace("Python", "Java"))
print(clean.split())Since strings are immutable, these methods return new strings rather than modifying the original string.
Explain lists in Python. Describe their characteristics and demonstrate common list operations.
A list is an ordered, mutable collection that can store elements of different data types. Lists are created using square brackets.
items = [10, "pen", 3.5, True]Common operations include:
- Indexing:
items[0] - Slicing:
items[1:3] - Adding an element:
append() - Inserting an element:
insert() - Removing an element:
remove()orpop() - Sorting:
sort() - Reversing:
reverse() - Finding length:
len()
Example:
numbers = [3, 1, 2]
numbers.append(4)
numbers.sort()
print(numbers) # [1, 2, 3, 4]Lists may contain duplicate values and nested lists. Unlike strings and tuples, list elements can be changed after creation.
Summarize the common Python data types and distinguish between mutable and immutable objects.
Python's common data types include:
- Numeric types:
int,float, andcomplex - Boolean type:
bool - Text type:
str - Sequence types:
list,tuple, andrange - Set type:
set - Mapping type:
dict - Null value type:
NoneType, represented byNone
Mutable objects can be changed after creation. Examples include lists, dictionaries, and sets.
Immutable objects cannot be changed after creation. Examples include integers, floats, Boolean values, strings, and tuples.
For example, a list can be updated using numbers[0] = 10, but a string cannot be updated using text[0] = 'A'. When an immutable value appears to change, Python creates a new object rather than modifying the old one.
Explain type conversion in Python. Distinguish between implicit and explicit conversion with examples.
Type conversion changes a value from one data type to another.
Implicit conversion is performed automatically by Python when it can safely combine compatible types:
result = 5 + 2.5Here, the integer is converted to a floating-point value, and the result is 7.5.
Explicit conversion, also called type casting, is performed by the programmer using functions such as int(), float(), str(), list(), and bool():
age = int("21")
price = float("19.50")
text = str(100)Invalid conversions can produce errors. For example, int("hello") raises a ValueError. Conversion should therefore be applied only when the source value has a suitable format.
Explain binary numbers and describe how Python represents and converts integers between decimal and binary forms.
The binary number system uses only two digits, and , and has base . Each position represents a power of .
For example:
Python provides built-in functions for conversion:
print(bin(11)) # 0b1011
print(int("1011", 2)) # 11The prefix 0b indicates a binary literal:
value = 0b1011The format() function can represent a decimal number in binary form:
print(format(11, "b"))Binary representation is important in computer memory, digital electronics, bitwise operations, and data encoding.
Explain string formatting in Python using concatenation, formatted string literals, and the format() method.
String formatting inserts values into a text message in a controlled and readable way.
Concatenation:
name = "Ravi"
age = 20
message = "Name: " + name + ", Age: " + str(age)Formatted string literal, or f-string:
message = f"Name: {name}, Age: {age}"format() method:
message = "Name: {}, Age: {}".format(name, age)Formatting can control decimal precision and alignment:
price = 12.3456
print(f"Price: ${price:.2f}")The .2f specification displays two digits after the decimal point. F-strings are generally preferred because they are concise, readable, and easy to maintain.
Describe how the Python shell can be used as a calculator and explain how to run a simple Python script.
The Python shell, also called the interactive interpreter, executes commands immediately after the prompt >>>. It is useful for testing expressions and learning basic operations.
Example:
>>> 8 + 4
12
>>> 10 / 2
5.0
>>> 2 ** 3
8To run a script:
- Open a text editor or IDE.
- Write Python statements in a file.
- Save the file with a
.pyextension, such aswelcome.py. - Open a terminal in the file's directory.
- Run
python welcome.py, or usepython3 welcome.pyon systems where that command is required. - Observe the program output.
For example, welcome.py may contain:
print("Welcome to Python")The shell is best for quick experiments, while scripts are suitable for saving and reusing complete programs.
Explain software development best practices, PEP 8, and code readability in Python.
Software development best practices make programs easier to understand, test, modify, and maintain.
Important practices include:
- Use meaningful names for variables and functions.
- Keep functions small and focused on one task.
- Avoid unnecessary repetition.
- Add comments and documentation where they clarify intent.
- Validate input and handle possible errors.
- Test code using normal and unusual inputs.
- Use version control and make incremental changes.
PEP 8 is Python's official style guide. It recommends four spaces for indentation, a maximum line length commonly limited to 79 characters, clear naming conventions, appropriate blank lines, and spaces around operators.
Readable code should express its purpose clearly. For example, total_price is more informative than tp, and consistent formatting allows developers to understand code quickly.
Explain the working of an if-else statement in Python and write a program to determine whether a number is positive, negative, or zero.
An if-else statement performs conditional execution. Python evaluates the condition as either True or False. An elif clause allows additional conditions to be tested.
number = float(input("Enter a number: "))
if number > 0:
print("The number is positive")
elif number < 0:
print("The number is negative")
else:
print("The number is zero")The conditions are checked from top to bottom. When one condition is true, its indented block executes and the remaining branches are skipped. If no if or elif condition is true, the else block executes. Correct indentation is essential because it defines each branch.
Distinguish between equality operators and identity operators in Python. Explain why == and is should not generally be used interchangeably.
The equality operator == compares the values of two objects, whereas the identity operator is checks whether two references point to the same object.
Example:
first = [1, 2, 3]
second = [1, 2, 3]
third = first
print(first == second) # True: equal contents
print(first is second) # False: different list objects
print(first is third) # True: same objectUse == when the contents or values need to be compared. Use is mainly for identity checks, especially when testing for the singleton value None:
if result is None:
print("No result")Using is for general value comparison can produce incorrect or implementation-dependent results.
Explain the steps involved in installing Python using Anaconda and describe how to launch and use Jupyter Notebook.
Anaconda installation and Jupyter usage:
- Download the appropriate Anaconda distribution for the operating system from the official website.
- Run the installer and select the required installation options.
- Add Anaconda to the system path if necessary, or use the Anaconda Navigator application.
- Open Anaconda Navigator and launch Jupyter Notebook.
- In Jupyter Notebook, create a new Python notebook using the Python 3 kernel.
- Enter Python code into cells and execute a cell using
Shift + Enter. - Save the notebook with the
.ipynbextension.
Anaconda provides Python along with useful libraries and tools, while Jupyter supports interactive programming, documentation, visualization, and experimentation.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →