Essential Python Programming Concepts and Exercises
Q1. Membership Operators in Python
Membership operators test whether a value exists within a sequence (string, list, tuple, set, or dictionary).
- in: Returns
Trueif the value is found. - not in: Returns
Trueif the value is NOT found.
fruits = ['apple', 'banana', 'cherry']
print('apple' in fruits) # True
print('mango' in fruits) # False
print('mango' not in fruits) # TrueQ2. Comparing islower() and isupper() Methods
These string methods check the casing of characters within a string.
islower(): ReturnsTrueif all cased characters are lowercase.isupper(): ReturnsTrueif all cased characters are uppercase.
s1 = 'hello'
s2 = 'HELLO'
print(s1.islower()) # True
print(s2.isupper()) # TrueQ3. Understanding the Continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next.
for i in range(10):
if i == 5:
continue
print(i) # Prints 0-4 and 6-9, skipping 5Q4. Python Program: Even or Odd
Using the modulus operator (%) to determine if a number is divisible by 2.
num = int(input('Enter a number: '))
if num % 2 == 0:
print(f'{num} is Even')
else:
print(f'{num} is Odd')Q5. Python Indentation Rules
Indentation is mandatory in Python to define code blocks (e.g., loops, functions, if-statements). Standard practice is 4 spaces.
x = 10
if x > 5:
print('x is greater than 5') # Indented blockQ6. Python Data Type Classification
Python is dynamically typed. Common types include:
- Numeric:
int,float,complex - Sequence:
str,list,tuple,range - Mapping:
dict - Set:
set,frozenset - Boolean:
bool
Q7. String Data Structure and Methods
Strings are immutable sequences of characters. Key methods include:
upper(): Converts to uppercase.lower(): Converts to lowercase.replace(old, new): Swaps substrings.split(sep): Divides string into a list.strip(): Removes whitespace.
Q8. Palindrome Check Program
A palindrome reads the same forward and backward.
num = input('Enter a number: ')
if num == num[::-1]:
print('Palindrome')
else:
print('Not a Palindrome')Q9. Simple Calculator Implementation
A basic calculator using conditional statements to perform arithmetic based on user input.
Q10. Type Conversion (Casting)
Converting data types explicitly using functions like int(), float(), str(), and bool().
Q11. The range() Function and Patterns
The range(start, stop, step) function generates sequences. It is frequently used in nested loops to create patterns like alphabetic pyramids.
Q12. Operators, Precedence, and Associativity
Operators perform operations on variables. Precedence determines the order of evaluation (e.g., ** before *), while associativity determines the direction (left-to-right or right-to-left) for operators of equal priority.
