Introduction to Python
Python is a high-level, general-purpose programming language used for application development,
web, and AI tasks. Its syntax is simple, readable, and case-sensitive. Python is free, open-source,
and runs on multiple platforms.
Features:
Easy to learn and use
Interpreted language
Supports OOP and functional programming
Portable and open-source
Quick Revision Questions:
What type of language is Python (interpreted/compiled)?
Name three uses of Python.
Is Python case-sensitive?
Keywords, Identifiers, and Variables
Keywords: Reserved words like if, else, for, def, having special meaning. Identifiers: Names given
to variables, functions, etc.; must start with a letter/underscore, can't use keywords.
Variables: Containers to store data, e.g., a = 10. Python uses dynamic typing.
Quick Revision Questions:
What is a keyword in Python?
Can a variable name start with a digit?
How do you define a variable in Python?
Data Types
Python supports multiple data types:
int, float, complex for numbers
str for strings (sequence of characters)
bool for boolean
list, tuple, set, dict for collections
Quick Revision Questions:
What is the difference between mutable and immutable data types in Python?
Give examples of three basic data types in Python.
Comments
Comments are lines ignored by the Python interpreter , used for code explanation.
Single-line: Start with #
Multi-line: Use triple quotes """ ... """
Quick Revision Questions:
How do you add a comment in Python?
Why are comments used?
Operators
Python supports several types of operators:
Operator TypeExamples Purpose Arithmetic +, -, *, /, //, %, **Perform mathematical ops
Assignment =, +=, -=, *=, /=Assign values Relational ==, !=, >, <, >=, <=Compare two values
Logical and, or , notLogical operations Identity is, is notCheck object identity Membership in, not
inTest if value in sequence
Quick Revision Questions:
What does // operator do?
How is the identity operator different from the equality operator?
List all relational operators in Python.
Input and Output
Use input() to read from the user .
Use print() to display output.
Quick Revision Questions:
How do you take user input in Python?
What is the syntax of the print() function?
Conditional Statements (If, Elif, Else)
Python decisions are made with if, elif, and else. Syntax:
if condition: statement elif another_condition : statement else: statement
Quick Revision Questions:
How do you write an if-elif-else block?
What will happen if no condition is True?
Flow of Control: Loops
Python has two main loops:
for loop: Iterates over a sequence
while loop: Repeats as long as condition is true Break (break), continue (continue).
Quick Revision Questions:
What is the syntax for a for loop?
When do you use break in a loop?
Strings in Python
Strings are sequences of characters stored in str objects.
Can be indexed and sliced
Common methods: upper(), lower(), replace(), strip()
Quick Revision Questions:
Write code to extract 'abc' from 'abcde'.
Name two string methods.
Lists in Python
Lists are ordered, mutable collections.
Use square brackets: a =
List operations: append, remove, pop, slice
Quick Revision Questions:
What is the difference between lists and tuples?
Write code to add 10 to the end of a list.
Tuples in Python
Tuples are ordered, immutable sequences.
Use parentheses: t = (1, 2, 3)
Cannot change elements after creation
Quick Revision Questions:
How do you define a tuple?
Can you change the value of a tuple's element?
Dictionaries in Python
Dictionaries store key-value pairs.
Use braces: d = {'a': 1, 'b': 2}
Keys must be unique and immutable
Quick Revision Questions:
How do you access the value for a key in a dictionary?
Write code to add a new key-value pair .
Membership and Identity Operators
Membership: in, not in (checks existence in sequence)
Identity: is, is not (checks if two references point to same object)
Quick Revision Questions:
What does in operator do?
How does is differ from ==?
Python Modules
Modules are files containing Python code (functions, variables).
Built-in modules: math, random, statistics
Import using import module_name
Quick Revision Questions:
How do you import the math module?
Write code to use the sqrt() function from math module.
Important Programs and Practice Questions
WAP to check if a number is even or odd.
WAP to count vowels in a string.
WAP to find the largest of three numbers.
WAP to reverse a list.
WAP to check for palindrome string.
Introduction to Python
Q1: What type of language is Python? A1: Python is an interpreted language, which means code is
executed line-by-line by the Python interpreter .
Q2: Name three uses of Python. A2: Python is used in web development, artificial intelligence, data
science, and application programming.
Q3: Is Python case-sensitive? A3: Yes, Python is case-sensitive. For example, Var and var are
considered different identifiers.
Keywords, Identifiers, and Variables
Q4: What is a keyword in Python? A4: A keyword is a reserved word with a predefined meaning in
the language syntax, such as if, else, while, def, etc.
Q5: Can a variable name start with a digit? A5: No, variable names (identifiers) cannot start with a
digit. They must begin with a letter or underscore.
Q6: How do you define a variable in Python? A6: Variables are defined by assigning values using
the assignment operator =. Example:
x = 10 name = "Alice"
Data Types
Q7: What is the difference between mutable and immutable data types in Python? A7: Mutable data
types (like lists and dictionaries) can be changed after creation; immutable types (like integers,
floats, strings, tuples) cannot be changed once created.
Q8: Give examples of three basic data types in Python. A8: Examples include int (e.g.,
5), float (e.g., 2.5), and str (e.g., "hello").
Comments
Q9: How do you add a comment in Python? A9: Single-line comments start with #. Multi-line
comments can be enclosed between triple quotes """ ... """.
Q10: Why are comments used? A10: Comments are used to explain code, making it easier to
understand and maintain.
Operators
Q11: What does the // operator do? A11: The // operator performs floor division, which divides and
returns the integer part of the quotient.
Q12: How is the identity operator different from the equality operator? A12: The identity operator (is)
checks if two variables point to the same object, whereas equality operator (==) checks if the values
are equal.
Q13: List all relational operators in Python. A13: Relational operators are: ==, !=, <, >, <=, >=.
Input and Output
Q14: How do you take user input in Python? A14: Use the input() function to read input from the
user as a string.
Q15: What is the syntax of the print() function? A15: The syntax is print(object1, object2, ..., sep=' ',
end='\n').
Conditional Statements (If, Elif, Else)
Q16: How do you write an if-elif-else block? A16:
if condition1: # code block1 elif condition2: # code block2 else: # code block3
Q17: What will happen if no condition is True? A17: The else block will be executed if provided; if
no else block exists, nothing happens.
Loops
Q18: What is the syntax for a for loop? A18:
for variable in sequence: # code block
Q19: When do you use break in a loop? A19: break is used to exit a loop prematurely when a
certain condition is met.
Strings
Q20: Write code to extract 'abc' from 'abcde'. A20:
s = "abcde" print(s[0:3]) # Output: abc
Q21: Name two string methods. A21: Two string methods are .upper() and .replace().
Lists
Q22: What is the difference between lists and tuples? A22: Lists are mutable (can be changed),
whereas tuples are immutable (cannot be changed once created).
Q23: Write code to add 10 to the end of a list. A23:
lst = [1, 2, 3] [Link](10) print(lst) # Output: [1, 2, 3, 10]
Tuples
Q24: How do you define a tuple? A24:
t = (1, 2, 3)
Q25: Can you change the value of a tuple's element? A25: No, tuples are immutable; their elements
cannot be changed.
Dictionaries
Q26: How do you access the value for a key in a dictionary? A26:
d = {'a': 1, 'b': 2} print(d['a']) # Output: 1
Q27: Write code to add a new key-value pair to a dictionary. A27:
d['c'] = 3
Membership and Identity Operators
Q28: What does the in operator do? A28: It checks if a value exists within a sequence (list, string,
tuple) and returns True or False.
Q29: How does is differ from ==? A29: is checks whether two variables point to the same
object; == checks if their values are equal.
NCERT Chapter Important Questions and Answers (Python Fundamentals)
Q30: Write a Python program to check if a number is even or odd. A30:
num = int(input("Enter a number: ")) if num % 2 == 0: print("Even") else: print("Odd")
Q31: Write a Python program to count the number of vowels in a string. A31:
string = input("Enter a string: ") vowels = 'aeiouAEIOU' count = 0 for char in string: if char in vowels:
count += 1 print("Number of vowels:", count)
Q32: Write a Python program to find the largest of three numbers. A32:
a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) c = int(input("Enter third
number: ")) if a >= b and a >= c: print("Largest is", a) elif b >= a and b >= c: print("Largest is", b)
else: print("Largest is", c)
Q33: Write a Python program to reverse a list. A33:
lst = [1, 2, 3, 4, 5] [Link]() print(lst) # Output: [5, 4, 3, 2, 1]
Q34: Write a Python program to check if a string is palindrome or not. A34:
string = input("Enter a string: ") if string == string[::-1]: print("Palindrome") else: print("No t
Palindrome")
Python Keywords with Definitions, Usage, and Examples
if Definition: Used to execute a code block only if a specified condition is true. Usage: Conditional
branching. Example:
if x > 0: print("Positive")
else Definition: Used with if to execute a code block if the if condition is false. Usage: Alternative
branch in condition. Example:
if x > 0: print("Positive") else: print("Non-positive")
elif Definition: Stands for "else if", used to check multiple conditions sequentially. Usage: Additional
conditional checks. Example:
if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative")
and Definition: Logical operator returning True if both operands are True. Usage: Combines
multiple conditions. Example:
if a > 0 and b > 0: print("Both positive")
or Definition: Logical operator returning True if at least one operand is True. Usage: Either condition
true check. Example:
if a > 0 or b > 0: print("At least one positive")
not Definition: Logical operator that negates the condition (True becomes False, and vice versa).
Usage: Negate conditions. Example:
if not a > 0: print("a is not positive")
True Definition: Boolean literal representing truth value True. Usage: Used for boolean comparison
and assignments. Example:
is_sunny = True
False Definition: Boolean literal representing falsehood value False. Usage: Used similarly to True.
Example:
is_raining = False
None Definition: Represents the absence of a value or null. Usage: Used to denote "no value" or
default uninitialized value. Example:
result = None if result is None: print("No result yet")
for Definition: Used to create a loop that iterates over a sequence or range. Usage: Repeating block
of code multiple times. Example:
for i in range(5): print(i)
while Definition: Used to create a loop that repeats while a condition is true. Usage: Loop with
condition check before each iteration. Example:
count = 0 while count < 5: print(count) count += 1
break Definition: Terminates the nearest enclosing loop prematurely. Usage: Exit loop before
normal end. Example:
for i in range(10): if i == 5: break print(i)
continue Definition: Skips the current iteration of the loop and continues with the next iteration.
Usage: Skip steps in loops conditionally. Example:
for i in range(5): if i == 2: continue print(i)
def Definition: Used to define a function. Usage: Create reusable blocks of code. Example:
def greet(): print("Hello") greet()
return Definition: Exits a function and optionally passes a value back to the caller . Usage: Provide
output from a function. Example:
def square(x): return x * x print(square(4))
class Definition: Used to define a class (custom data type/object). Usage: Object-oriented
programming. Example:
class Dog: def bark(self): print("Woof!")
import Definition: Imports a module to use its functions and classes. Usage: Include external
libraries. Example:
import math print([Link](16))
from Definition: Imports specific attributes or functions from a module. Usage: Selective import.
Example:
from math import pi print(pi)
as Definition: Creates an alias while importing or with context managers. Usage: Rename imported
module or manage resources. Example:
import math as m print([Link](25))
pass Definition: A null statement which does nothing, used as a placeholder . Usage: Create empty
code blocks. Example:
def function(): pass # To be implemented later
global Definition: Declares that a variable inside a function refers to a global variable. Usage: Modify
global variable inside function. Example:
x = 5 def modify(): global x x = 10 modify() print(x) # 10
nonlocal Definition: Refers to a variable in the nearest enclosing scope (not global). Usage: Modify
outer function variables in nested functions. Example:
def outer(): x = 5 def inner(): nonlocal x x = 10 inner() print(x) # 10 outer()
try Definition: Starts a block to test for exceptions. Usage: Handle runtime errors gracefully.
Example:
try: print(10 / 0) except ZeroDivisionError : print("Cannot divide by zero")
except Definition: Block to handle exceptions raised in try. Usage: Catch errors. Example: See
above.
finally Definition: Block that runs after try and except, regardless of exceptions. Usage: Cleanup
code. Example:
try: x = 5 finally: print("Done")
raise Definition: Raises a specified exception intentionally. Usage: Trigger error conditions.
Example:
raise ValueError("Invalid value")
lambda Definition: Creates anonymous functions (functions without names). Usage: Short, inline
functions. Example:
square = lambda x: x * x print(square(5))
yield Definition: Used to return a generator from a function, producing values one by one. Usage:
Create iterators efficiently. Example:
def gen(): yield 1 yield 2 for val in gen(): print(val)
assert Definition: Tests if a condition is True, raises AssertionError if False (used for debugging).
Usage: Check assumptions. Example:
assert 2 + 2 == 4
del Definition: Deletes an object, variable, or item from a list/dictionary. Usage: Remove data or
references. Example:
a = [1, 2, 3] del a[1] print(a) # [1, 3]
is Definition: Tests if two variables point to the same object (identity). Usage: Compare object
identity. Example:
a = [1, 2] b = a print(a is b) # True
in Definition: Tests if a value exists in a sequence (list, tuple, string). Usage: Membership check.
Example:
print(3 in [1, 2, 3]) # True