Back to Curriculum

Python Basics

CBSE Class 11 - Computer Science & Information Practices

Python Basics

Python is a high-level, interpreted programming language known for its simplicity and readability. This guide covers the fundamental concepts of Python programming.

Character Set

Python uses the following characters to form valid tokens:

1. Letters

  • Uppercase: A-Z
  • Lowercase: a-z

2. Digits

  • 0-9

3. Special Characters

" ! @ # $ % ^ & * ( ) - _ + = [ ] { } | \ : ; " ' < > , . ? /

4. White Spaces

Space, tab, newline, and carriage return

Literals

Literals are notations representing a fixed value in the source code.

Example:

Types of Literals:

1. String Literal
'Python'
2. Numeric Literal
24.3 (Float)
3. Boolean Literal
False
4. Special Literal

Operators

1. Arithmetic Operators

OperatorDescriptionExample
+Addition5 + 3 = 8
-Subtraction10 - 3 = 7
*Multiplication4 * 5 = 20
/Division (Float)10 / 3 = 3.333...
//Floor Division10 // 3 = 3
**Exponentiation2 ** 3 = 8
%Modulus (Remainder)10 % 3 = 1

2. Assignment Operators

OperatorDescriptionExample
=Assignmentx = 5
+=Add and Assignx += 3 (x = x + 3)
-=Subtract and Assignx -= 2 (x = x - 2)
*=Multiply and Assignx *= 4 (x = x * 4)
/=Divide and Assignx /= 2 (x = x / 2)
%=Modulus and Assignx %= 3 (x = x % 3)

3. Comparison Operators

OperatorDescriptionExample
<Less than5 < 10 → True
>Greater than10 > 5 → True
<=Less than or equal5 <= 5 → True
>=Greater than or equal10 >= 5 → True
==Equal to5 == 5 → True
!=Not equal to5 != 3 → True

4. Logical Operators

OperatorDescriptionExample
andLogical ANDTrue and False → False
orLogical ORTrue or False → True
notLogical NOTnot True → False

5. Identity Operators

Identity operators compare the memory locations of two objects.

OperatorDescriptionExample
isReturns True if both variables point to same objectx is y
is notReturns True if both variables point to different objectsx is not y

Example:

y = [1, 2, 3]
print(x is y) # False (different objects)
print(x == y) # True (same values)

6. Bitwise Operators

Bitwise operators perform operations on binary representations of numbers.

OperatorDescriptionExample (x=5, y=3)
&Bitwise AND5 & 3 = 1
|Bitwise OR5 | 3 = 7
^Bitwise XOR5 ^ 3 = 6
~Bitwise NOT~5 = -6
<<Left Shift5 << 1 = 10
>>Right Shift5 >> 1 = 2

7. Membership Operators

Membership operators test if a value is a member of a sequence (string, list, tuple, etc.).

OperatorDescriptionExample
inReturns True if value is found in sequence'a' in 'apple' → True
not inReturns True if value is not found in sequence'z' not in 'apple' → True

Example:

print('apple' in fruits) # True
print('grape' not in fruits) # True

Punctuators

Punctuators are special symbols used to organize code structure in Python.

Common Punctuators:

[ ] ( ) { } , : . ; @ = += -= *= /=

Usage:

  • [ ] - Lists, indexing
  • ( ) - Tuples, function calls
  • { } - Dictionaries, sets
  • : - Indentation, slicing

Keywords

Keywords are reserved words in Python that have special meanings and cannot be used as variable names, function names, or any other identifiers.

  • Keywords are case-sensitive
  • They cannot be used as identifiers

Python Keywords (35 keywords):

False
None
True
and
as
assert
async
await
break
class
continue
def
del
elif
else
except
finally
for
from
global
if
import
in
is
lambda
nonlocal
not
or
pass
raise
return
try
while
with
yield

Identifiers

Identifiers are names used to identify variables, functions, classes, modules, and other objects in Python.

Rules for Identifiers:

  • Must begin with an uppercase letter (A-Z), lowercase letter (a-z), or underscore (_)
  • Can contain letters, digits (0-9), and underscores
  • Only special character accepted is underscore (_)
  • Can be of any length
  • Cannot be a keyword
  • Cannot start with a digit
  • Cannot contain spaces or other special characters
✅ Valid Identifiers:
_count
total123
MyClass
❌ Invalid Identifiers:
student-name (has hyphen)
if (is a keyword)
my name (has space)

Comments

Comments are remarks or notes in the code that are ignored by the Python interpreter. They help document and explain code.

1. Single Line Comments

Use # for single-line comments

x = 10 # Assign value to x

2. Multi-Line Comments

Use triple quotes ''' or """

This is a
multi-line comment
'''

Uses of Comments:

  • Documenting code: Explain what the code does
  • Debugging: Temporarily disable code to identify errors
  • Code explanation: Clarify complex logic

Features of Python

1. High-Level Language

Easy to read and write, closer to human language than machine code

2. Interpreted Language

Code is executed line by line, no compilation needed

3. Easy to Understand

Simple syntax, readable code

4. Case-Sensitive

Python distinguishes between uppercase and lowercase

5. Predefined Libraries

Rich standard library with many built-in modules

6. Platform Independent

Runs on Windows, Mac, Linux, etc.

Applications of Python:

  • Machine Learning - Data science, AI
  • Web Development - Django, Flask
  • Data Analysis - Pandas, NumPy
  • Automation - Scripting, automation
  • Game Development - Pygame

Execution Modes in Python

1. Interactive Mode

Code is executed immediately after typing each line. Also known as Python Shell or REPL (Read-Eval-Print Loop).

Hello
>>> x = 10
>>> x + 5
15

Advantages: Quick testing, immediate feedback

2. Script Mode

Code is written in a file (with .py extension) and executed as a complete program.

print("Hello World")
x = 10
print(x + 5)

Advantages: Save and reuse code, better for larger programs

Datatypes in Python

1. Numeric/Number

  • int - Integer (e.g., 5, -10, 100)
  • float - Floating point (e.g., 3.14, -2.5)
  • complex - Complex numbers (e.g., 3+4j)

2. Boolean

  • True or False
  • Used for logical operations

3. Sequence

  • list - Ordered, mutable [1, 2, 3]
  • tuple - Ordered, immutable (1, 2, 3)
  • String - Text "Hello"

4. None

Represents absence of value

Mutable vs Immutable:

Mutable (Changes Allowed):
  • list - Can modify elements
  • dict - Can add/remove keys
  • set - Can add/remove elements
Immutable (Cannot Change):
  • int, float - Numbers
  • tuple - Cannot modify
  • String - Cannot modify

Type Conversion

1. Implicit Type Conversion

Python automatically converts one data type to another when needed (usually to a "larger" type).

Example:

y = 3.5 # float
result = x + y # float (5.0 + 3.5 = 8.5)
print(type(result)) # <class 'float'>

2. Explicit Type Conversion

Manually converting one data type to another using built-in functions.

FunctionDescriptionExample
int()Convert to integerint(5.9) → 5
float()Convert to floatfloat(10) → 10.0
str()Convert to stringstr(100) → "100"
bool()Convert to booleanbool(0) → False

Example:

num_int = int(num) # 100 (integer)
print(num_int + 5) # 105

Errors in Python

1. Syntax Error

Occurs when the code violates the rules of the Python programming language. Syntax means the rules of the language.

Example:

SyntaxError: expected ':'

Correction:

2. Logical Error

The program runs without crashing but produces incorrect output due to flawed logic.

Example:

return length + width # Should be length * width
print(area(5, 4)) # Output: 9 (incorrect, should be 20)

3. Runtime Error (Exception)

Errors that occur during program execution, such as division by zero, file not found, etc.

Example:

ZeroDivisionError: division by zero

PEP 8 - Python Style Guide

PEP 8 is the official style guide for Python code. Following PEP 8 makes your code more readable and maintainable.

1. Indentation

Use 4 spaces per indentation level (no tabs).

if True:
print("Indented correctly")

2. Maximum Line Length

Keep lines ≤ 79 characters. Use line continuation with \ or parentheses.

3. Naming Conventions

TypeConventionExample
Variablessnake_caseuser_name
ConstantsUPPERCASEMAX_LIMIT
Functionssnake_caseget_data()
ClassesPascalCaseDataProcessor

4. Comments

Use # for single-line comments. Write comments before the code, not inline.

def calculate_area(radius):
return 3.14 * radius ** 2
Get in Touch