Class 11 Computer and Communicatio Notes Chapter 5 (Chapter 5) – CCT Part-I Book
Detailed Notes with MCQs of Chapter 5, which typically introduces you to the fundamentals of Python programming. This is a crucial chapter, especially for competitive exams where basic programming concepts are often tested. Pay close attention to the definitions, syntax, and examples.
Chapter 5: Getting Started with Python - Detailed Notes
1. Introduction to Python
- What is Python? Python is a high-level, interpreted, general-purpose programming language.
- High-Level: Closer to human language, abstracting away complex machine details.
- Interpreted: Code is executed line by line by an interpreter, without needing prior compilation for the entire program (unlike C++ or Java).
- General-Purpose: Can be used for a wide variety of applications (web development, data science, scripting, automation, etc.).
- Key Features:
- Simple and Easy to Learn: Clean syntax, emphasizes readability.
- Free and Open Source: Available for free, community-driven development.
- Interpreted: Easier debugging, line-by-line execution.
- Platform Independent (Portable): Python code can run on various operating systems (Windows, macOS, Linux) without modification.
- Dynamically Typed: You don't need to declare the type of a variable explicitly; the type is inferred at runtime.
- Extensive Libraries: Large standard library and vast ecosystem of third-party packages (like NumPy, Pandas, Matplotlib for data science).
- Expressive Language: Fewer lines of code required compared to many other languages for the same task.
2. Working with Python
- Modes of Operation:
- Interactive Mode (REPL):
- You type commands one by one directly into the Python interpreter (often accessed by typing
python
orpython3
in the terminal/command prompt). - The prompt is usually
>>>
. - The interpreter executes the command immediately and shows the result.
- Good for testing small snippets of code and exploring features.
- Code is not saved permanently.
- You type commands one by one directly into the Python interpreter (often accessed by typing
- Script Mode:
- You write your Python code in a file (usually with a
.py
extension, e.g.,myprogram.py
). - You then run the entire file using the Python interpreter (e.g.,
python myprogram.py
). - Suitable for writing longer programs.
- Code is saved for later use and modification.
- You write your Python code in a file (usually with a
- Interactive Mode (REPL):
3. Python Fundamentals
- Keywords: Reserved words that have special meaning in Python. They cannot be used as variable names or identifiers. Examples:
if
,else
,for
,while
,def
,class
,True
,False
,None
,import
,return
,try
,except
, etc. (Case-sensitive). - Identifiers: Names given to entities like variables, functions, classes, etc.
- Rules:
- Can start with a letter (a-z, A-Z) or underscore (_).
- Followed by letters, underscores, or digits (0-9).
- Cannot be a keyword.
- Case-sensitive (
myVar
is different frommyvar
). - No special characters like !, @, #, $, % are allowed.
- Conventions: Use meaningful names.
snake_case
(e.g.,student_name
) is common for variables and functions.PascalCase
(e.g.,StudentName
) is common for classes.
- Rules:
- Variables: A named location in memory used to store data.
- Assignment: Use the assignment operator (
=
). Example:age = 25
,name = "Alice"
. - Dynamic Typing: The type of the variable is determined by the value assigned to it. You can reassign a variable to a different type:
x = 10
(x is int), thenx = "hello"
(x is now str).
- Assignment: Use the assignment operator (
- Comments: Used to explain code; ignored by the interpreter.
- Single-line comment: Starts with
#
. Example:# This is a comment
- Multi-line comment: Often done using multi-line strings (triple quotes
""" """
or''' '''
), though technically these are just strings not assigned to anything. Example:""" This function calculates the sum of two numbers. """
- Single-line comment: Starts with
- Indentation:
- Crucial! Python uses indentation (whitespace at the beginning of a line) to define blocks of code (like loops, function definitions, conditional statements).
- Incorrect indentation will cause errors (
IndentationError
). - Standard practice is to use 4 spaces per indentation level. Tabs can be used but consistency is key.
4. Basic Data Types
- Numbers:
int
: Integers (whole numbers), e.g.,10
,-5
,0
.float
: Floating-point numbers (numbers with a decimal point), e.g.,3.14
,-0.5
,2.0
.complex
: Complex numbers (with real and imaginary parts), e.g.,3+4j
,2j
. (Less common in basic usage).
- String (
str
): Sequence of characters enclosed in single quotes ('...'
), double quotes ("..."
), or triple quotes ('''...'''
or"""..."""
).- Examples:
"Hello"
,'Python'
,"""Multi-line string"""
. - Immutable (cannot be changed in place after creation).
- Examples:
- Boolean (
bool
): Represents truth values.- Only two possible values:
True
andFalse
(Note the capitalization).
- Only two possible values:
- NoneType (
None
): Represents the absence of a value or a null value.- Only one possible value:
None
. Often used to indicate that a variable doesn't have a value yet.
- Only one possible value:
5. Operators
- Arithmetic Operators: Perform mathematical calculations.
+
(Addition),-
(Subtraction),*
(Multiplication)/
(Float Division - always results in a float), e.g.,10 / 4 = 2.5
//
(Integer/Floor Division - divides and rounds down to the nearest whole number), e.g.,10 // 4 = 2
,-10 // 4 = -3
%
(Modulus - remainder of division), e.g.,10 % 3 = 1
**
(Exponentiation - raise to the power), e.g.,2 ** 3 = 8
- Relational (Comparison) Operators: Compare values and return
True
orFalse
.==
(Equal to)!=
(Not equal to)>
(Greater than)<
(Less than)>=
(Greater than or equal to)<=
(Less than or equal to)
- Logical Operators: Combine boolean expressions.
and
: ReturnsTrue
if both operands are true.or
: ReturnsTrue
if at least one operand is true.not
: Reverses the logical state (not True
isFalse
).
- Assignment Operators: Assign values to variables.
=
: Simple assignment.+=
,-=
,*=
,/=
,//=
,%=
,**=
: Compound assignment (e.g.,x += 5
is shorthand forx = x + 5
).
6. Input and Output
- Output (
print()
function): Displays values/variables to the console.print("Hello, World!")
print(variable_name)
- Can print multiple items, separated by commas (default separator is a space):
print("Age:", age)
sep
argument: Changes the separator:print(1, 2, 3, sep='-')
-> Output:1-2-3
end
argument: Changes what is printed at the end (default is a newline\n
):print("Hello", end=' ')
print("World")
-> Output:Hello World
(on the same line)
- Input (
input()
function): Reads input from the user via the console.- Always returns the input as a string (
str
). - Can take an optional string argument as a prompt:
name = input("Enter your name: ")
- If you need a number, you must convert the input string using
int()
orfloat()
.
- Always returns the input as a string (
7. Type Conversion (Type Casting)
- Converting a value from one data type to another.
- Functions:
int(x)
: Convertsx
to an integer. Raises error if conversion isn't possible (e.g.,int("hello")
). Can convert floats (truncates decimal) and strings representing whole numbers.float(x)
: Convertsx
to a float. Can convert integers and strings representing numbers (including decimals).str(x)
: Convertsx
to a string. Works for most data types.bool(x)
: Convertsx
to a boolean. Most values convert toTrue
, except forFalse
,None
,0
,0.0
, empty strings (""
), and empty collections (which convert toFalse
).
- Example:
num_str = input("Enter a number: ") # num_str is a string num_int = int(num_str) # Convert string to integer result = num_int * 2 print("Result:", result)
Multiple Choice Questions (MCQs)
-
Which of the following describes Python accurately?
a) Compiled, Statically Typed
b) Interpreted, Statically Typed
c) Compiled, Dynamically Typed
d) Interpreted, Dynamically Typed -
What is the output of
print(10 // 3)
?
a) 3.333
b) 3.0
c) 3
d) 1 -
Which of the following is NOT a valid variable name in Python?
a) _my_var
b) myVar2
c) 2myVar
d) MyVar -
What does the
input()
function return by default?
a) Integer (int)
b) Float (float)
c) String (str)
d) Boolean (bool) -
Which symbol is used for single-line comments in Python?
a) //
b) /* ... */
c) #
d) """ ... """ -
What is the data type of the value
None
?
a) int
b) bool
c) str
d) NoneType -
What is the output of
print(3 * 'A')
?
a) AAA
b) 3A
c) Error
d) A A A -
Which operator is used for exponentiation (power)?
a) ^
b) **
c) %
d) // -
What is the result of the expression
5 > 3 and 10 == 9
?
a) True
b) False
c) Error
d) 1 -
How do you define a block of code (like inside an
if
statement) in Python?
a) Using curly braces{}
b) Using parentheses()
c) Using indentation
d) Using keywordsbegin
andend
Answers to MCQs:
- d) Interpreted, Dynamically Typed
- c) 3 (
//
is floor division) - c) 2myVar (Identifiers cannot start with a digit)
- c) String (str)
- c) #
- d) NoneType
- a) AAA (String repetition)
- b) **
- b) False (
5 > 3
is True,10 == 9
is False.True and False
is False) - c) Using indentation
Study these notes thoroughly. Focus on understanding the why behind the syntax and rules, not just memorizing. Practice writing small code snippets in both interactive and script modes. Good luck with your preparation!