Python Questions and Answers - Part A
1) Explain the features of Python that make it a popular choice for various applications.
- **Simple and Readable**: Pythons syntax is easy to understand.
- **Interpreted Language**: Executes line by line, allowing faster debugging.
- **Cross-Platform**: Works on Windows, macOS, Linux.
- **Extensive Standard Library**: Provides built-in functions and modules.
- **Dynamic Typing**: No need to declare variable types.
- **Object-Oriented**: Supports object-oriented programming.
2) Describe the role of variables in Python. How are they declared and assigned values?
- **Variables store data** and are created when assigned a value.
- **Python uses dynamic typing**, so no explicit declaration is needed.
Example:
```python
x = 10 # Integer
name = 'Python' # String
pi = 3.14 # Float
```
3) List and explain any 4 commonly used built-in functions in Python for console input and
output operations.
- **print()**: Outputs data to the console.
```python
print('Hello, World!')
```
- **input()**: Accepts user input.
```python
name = input('Enter your name: ')
print('Hello,', name)
```
- **len()**: Returns the length of a string or list.
- **type()**: Returns the type of a variable.
4) Differentiate between the various types of control flow in Python.
- **Conditional Statements (`if`, `elif`, `else`)**: Used for decision making.
```python
age = 20
if age >= 18:
print('Adult')
else:
print('Minor')
```
- **Loops (`for`, `while`)**: Used for repeated execution.
- **Exception Handling (`try-except`)**: Handles runtime errors.
5) Discuss the various operators in Python and their precedence and association rules.
- **Arithmetic Operators**: `+, -, *, /, %, **, //`
- **Comparison Operators**: `==, !=, >, <, >=, <=`
- **Logical Operators**: `and, or, not`
**Operator Precedence (Highest to Lowest)**:
1. Parentheses `()`
2. Exponentiation `**`
3. Multiplication, Division `*, /, //, %`
4. Addition, Subtraction `+, -`
5. Comparison `==, !=, >, <, >=, <=`
6. Logical `and, or, not`
6) Write a Python expression and calculate the result.
```python
A = 5 + 2 * 3 - 4 / 2 # Result: 9
B = (4 + 5) * 3 / 2 - 1 # Result: 12.5
C = 10 / 2 * 2 + 5 * 2 - 4 # Result: 16
D = (10 - 3) * 2 / (5 - 2) # Result: 4.67
```
7) Write a Python program to find the sum of all even numbers between 1 and a given
number.
```python
num = int(input('Enter a number: '))
sum_even = sum(i for i in range(1, num + 1) if i % 2 == 0)
print('Sum of even numbers:', sum_even)
```
8) Write a Python program to perform arithmetic operations on two variables.
```python
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print('Addition:', a + b)
print('Subtraction:', a - b)
print('Multiplication:', a * b)
print('Division:', a / b if b != 0 else 'Undefined')
```