2 Marks
1. Key Features of Python
-Python’s simple and readable syntax makes it beginner-friendly.
-Python runs seamlessly on Windows, macOS, and Linux.
includes libraries for tasks like web development, data analysis, and machine learning.
-Variable types are determined automatically at runtime, simplifying code writing.
-Supports multiple programming paradigms, including object-oriented, functional, and
procedural programming.
-Python is free to use, distribute, and modify.
2. C++ Vs Python differences.
-C++ is statically typed, while Python is dynamically typed.
-C++ is a compiled language, while Python is an interpreted language.
-C++ has manual memory management, while Python has automatic memory management.
3. Interpreter in Python.
In Python, an interpreter is a program that reads and executes Python code line by line,
translating it into machine-readable instructions that the computer can understand. It is a slow
process that doesn't generate any form of output.
Interpreted Languages: Perl, BASIC, Python, JavaScript, Ruby, PHP.
4. Tuple data type.
It is also a list of comma-separated elements or values in round brackets. The values can be of
any data type, but can't be changed, i.e., Immutable, and it is ordered.
Example:
tuple1=(‘a’,’b’,’c’)
5. Structure of String.
String literals represent sequences of characters enclosed within quotes. Python supports
several ways to define string literals:
-Single quotes: 'Hello, world!'
-Double quotes: "Hello, world!"
-Triple single quotes: '''This is a multi-line string.'''
-Triple double quotes: """This is also a multi-line string."""
Example:
print("This is a line.\nThis is a new line.")
6. Subscript operator.
In Python, the subscript operator is represented by square brackets []. It is used to access
elements within various data structures that support indexing, such as strings, lists, tuples, and
dictionaries.
Example:
my_list = [10, 20, 30, 40]
first_element = my_list[0] # first_element will be 10
7. Slice and its syntax.
Slicing allows you to extract a sub-sequence of elements. It is used within the subscript
operator.
Syntax:
[start:end: step]
Where start is the inclusive starting index, end is the exclusive ending index, and step is the
increment between elements (defaulting to 1).
Example:
my_string = "Python"
substring = my_string[1:4] # substring will be "yth"
8. Break statement.
Break command terminates the loop's execution and transfers the program's control to the
statement next to the loop.
Example:
for i in range(10):
if i == 5:
print("Breaking the loop at i =", i)
break
print(i)
print("Loop finished.")
Output:
0
1
2
3
4
Breaking the loop at i = 5
Loop finished.
9. Python shell
A Python shell is an interactive interpreter for running Python code. It's also known as the
Python interactive console or REPL (Read-Eval-Print Loop). You can type Python code directly
into the shell, and the interpreter will immediately evaluate it and print the result.
10. Uses of Python.
-Web development
-Data analysis
-Machine learning
-Automation and Scripting
-Game development
11. Define a Complex number.
Complex numbers are numbers with real and imaginary parts. Example: 2 + 3j
In Python, it is a data type used with the keyword complex.
Example:
complex_num = complex(2, 3)
print(complex_num) #Output (2+3j)
12. Methods to add elements to a list.
-append(): This method adds a single element to the very end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4) # my_list is now [1, 2, 3, 4]
-insert(): This method adds a single element at a specified index within the list. Existing
elements from that index onwards are shifted to the right.
Example:
my_list = [1, 2, 4]
my_list.insert(2, 3) # Insert 3 at index 2, and my_list is now [1, 2, 3, 4]
-extend(): This method adds multiple elements from an iterable (like another list, tuple, or string)
to the end of the current list. Each element from the iterable is added individually.
Example:
my_list = [1, 2]
new_elements = [3, 4, 5]
my_list.extend(new_elements) # my_list is now [1, 2, 3, 4, 5]
-List Concatenation (+ operator): This operator creates a new list by combining two or more
lists. The original lists remain unchanged.
Example:
list1 = [1, 2]
list2 = [3, 4]
combined_list = list1 + list2 # combined_list is now [1, 2, 3, 4], and list1 and list2 remain [1, 2]
and [3, 4] respectively
13. Define escape sequences.
Escape sequences are special character combinations within string literals that begin with a
backslash (`\`). They are used to represent characters that are difficult or impossible to type
directly, or to embed special formatting instructions within a string.
Common escape sequences include:
\n: Newline (moves the cursor to the next line)
\t: Tab (inserts a horizontal tab space)
\\: Backslash (inserts a literal backslash character)
Example:
print(“1\n2\t3”)
Output:
1
2 3
16 Marks
1. Write short notes on:
a) Variable b) Keywords c) Identifiers d) Escape Sequences
a. Variables:
A variable is a symbolic name that refers to an object in memory. It allows you
to store and manipulate data within your program.
Example:
x = 10
name = "Alice" #x and name are variables
Rules:
- Variable names must start with a letter or underscore (_).
- They can contain letters, digits, and underscores.
- They are case-sensitive (Name and name are different).
b. Keywords:
These are words that have some special meaning or significance in a programming language.
They can't be used as variable names, function names, or any other random purpose.
They include try, False, and True, etc.
Example:
print(10) #print is a keyword used to display output
c. Identifiers: Identifiers are the names given to any variable, function, class, list, method, etc.,
for their identification.
Rules
-Identifiers are case-sensitive
-Identifier starts with a capital letter (A-Z), a small letter (a-z), or an underscore( _ ). It can't start
with any other character.
-Digits can also be a part of an identifier, but can't be the first character of it.
-No other characters or spaces allowed
-An identifier can't be a keyword.
Example:
b=10 #b is an Identifier
d. Escape sequences:
These are special character combinations within string literals that begin with a backslash (`\`).
They are used to represent characters that are difficult or impossible to type directly, or to
embed special formatting instructions within a string.
Common escape sequences include:
\n: Newline (moves the cursor to the next line)
\t: Tab (inserts a horizontal tab space)
\\: Backslash (inserts a literal backslash character)
Example:
print(“1\n2\t3”)
Output:
1
2 3
2. Types of Loops in Python with Examples.
A loop in Python is a sequence of instructions that repeats until a condition is met. In Python,
there are two main types of loops: for loops and while loops.
Types:
For Loop
Python's for loop is designed to repeatedly execute a code block while iterating through a list,
tuple, dictionary, or other iterable objects of Python. The process of traversing a sequence is
known as iteration.
Syntax;
for value in sequence:
code block
else:
Example:
string = "123"
for s in a string:
print(s)
Output:
1
2
3
With the help of the range() function, we may produce a series of numbers. range(10) will
produce values between 0 and 9. (10 numbers).
Example:
for i in range(3):
print(i)
Output:
0
1
2
While Loop
While loops are used in Python to iterate until a specified condition is met. However, the
statement in the program that follows the while loop is executed once the condition changes to
false.
Syntax:
while <condition>:
code block
else:
code block
Example:
i= 0
while (i < 3):
print(i)
i+=1
else:
print("Code block inside the else statement")
Output:
0
1
2
Code block inside the else statement
Nested loops
We can iterate a loop inside another loop.
Example:
for i in range(3):
for j in range(i + 1):
print("*", end=" ")
print()
Output:
***
***
***
3. Program to Convert Binary to Decimal and Vice Versa.
Python Program to convert Binary to Decimal
def binary_to_decimal(binary_str):
try:
decimal_number = int(binary_str, 2)
return decimal_number
except ValueError:
return "Invalid binary number."
binary_input = input("Enter a binary number: ")
decimal_output = binary_to_decimal(binary_input)
print(f"Decimal value: {decimal_output}")
Output:
Enter a binary number: 1011
Decimal value: 11
Python program to convert Decimal to Binary:
def decimal_to_binary(decimal_num):
if decimal_num == 0:
return "0"
binary = ""
while decimal_num > 0:
remainder = decimal_num % 2
binary = str(remainder) + binary
decimal_num = decimal_num // 2
return binary
decimal_input = int(input("Enter a decimal number: "))
binary_output = decimal_to_binary(decimal_input)
print(f"Binary equivalent: {binary_output}")
Output:
Enter a decimal number: 13
Binary equivalent: 1101
4. String Methods in Python.
These are built-in functions that operate on string objects. They help to manipulate, inspect, and
transform strings easily and are called using dot notation: string.method().
Strings are immutable, so these methods return new strings; they do not modify the
original.
Common String Methods
Method Description Example
strip() Removes leading and trailing " hello ".strip() → "hello"
whitespace
lower() Converts string to lowercase "HELLO".lower() → "hello"
upper() Converts string to uppercase "hello".upper() → "HELLO"
replace(old, new) Replaces occurrences of “hello".replace("l", "p") →"heppo"
substring old with new
find(sub) Returns index of first occurrence
of sub or -1 if not found "hello".find("l") → 2
split(sep) Splits string into list using sep
(default whitespace) "a b c".split() → ["a","b","c"]
startswith(prefix) Returns True if string starts
with prefix "hello".startswith("he")→True
endswith(suffix) Returns True if string ends
with suffix "hello".endswith("lo") → True
count(sub) Returns the number of occurrences
of substring sub "hello".count("l") → 2
isalpha() Returns True if all characters
are alphabets "abc".isalpha() → True
isdigit() Returns True if all characters
are digits "123".isdigit() → True
join(iterable) Joins elements of iterable with
the string as separator ",".join(["a", "b"]) → "a,b"