Python Programming Extended Answers
1. Salient Features of Python with print(), input(), and len()
Salient Features of Python:
- Simple & Easy to Learn
- Interpreted Language
- Dynamically Typed
- High-Level Language
- Extensive Standard Library
- Object-Oriented
- Portable
- Open Source
Examples:
name = input("Enter your name: ")
print("Hello", name)
print("Length of your name:", len(name))
2. String Concatenation and Replication
Concatenation: Joining strings using '+'.
Example:
str1 = "Hello"
str2 = "World"
print(str1 + " " + str2) # Hello World
Replication: Repeating a string using '*'.
Example:
print("*" * 5) # *****
3. Basic Type Functions: str(), int(), float()
Used to convert data types.
str() - to string
Python Programming Extended Answers
int() - to integer
float() - to float
Example:
x=5
y = "10"
print(str(x) + y) # 510
print(int(y) + x) # 15
print(float(x) + 2.5) # 7.5
4. Comparison and Boolean Operators
Comparison Operators: ==, !=, >, <, >=, <=
Boolean Operators: and, or, not
Example:
a = 10
b=5
print(a > b) # True
print(a < b or a == 10) # True
print(not(a < b)) # True
5. Flow Control Statements in Python
Includes if, elif, else, for, while, break, continue.
Example:
if x > 0:
print("Positive")
else:
print("Non-positive")
for i in range(5):
Python Programming Extended Answers
print(i)
while i < 5:
print(i)
i += 1
6. Importing Modules in Python
1. import math
2. import math as m
3. from math import sqrt
4. from math import *
Example:
import math
print(math.sqrt(25))
from math import sqrt
print(sqrt(36))
7. Exception Handling in Python
try:
a = int(input("Enter a number: "))
b = 10 / a
print("Result:", b)
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
8. Local and Global Scope in Python
x = 10 # global
Python Programming Extended Answers
def display():
x = 5 # local
print("Local x:", x)
display()
print("Global x:", x)
Use 'global' to refer to global variable inside function:
def modify():
global x
x = 20