HomeComputer ScienceClass 11Getting Started with Python

Chapter 3: Getting Started with Python

Introduction to Python

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability and simplicity, making it ideal for beginners and professionals alike.

Key Characteristics of Python:

  • Simple and readable: Code reads like English
  • Interpreted: Code is executed line by line
  • High-level: Abstracts complex details automatically
  • Case-sensitive: Python and python are different
  • Platform-independent: Runs on any OS with Python installed

Advantages of Python

  • Easy to learn: Simple syntax similar to English
  • Free and open source: No cost to download and use
  • Large community: Extensive support and resources
  • Versatile: Used in web development, AI, data science, automation
  • Rich libraries: Thousands of pre-built modules available
  • Cross-platform: Works on Windows, macOS, Linux

Disadvantages of Python

  • Slower execution: Being interpreted, it's slower than compiled languages like C++
  • Memory consumption: Uses more memory than languages like C
  • Mobile development: Not suitable for mobile app development
  • Runtime errors: Errors caught only at runtime, not compile time
  • Indentation dependency: Incorrect indentation causes errors

Installing Python

Downloading Python

  1. Visit www.python.org
  2. Click on 'Downloads' menu
  3. Select your Operating System (Windows, macOS, Linux)
  4. Download the latest stable version (3.x)
  5. Choose between 32-bit or 64-bit based on your system

Installation on Windows

  1. Double-click the downloaded installer (.exe file)
  2. Check 'Add Python 3.x to PATH' (IMPORTANT!)
  3. Click 'Install Now' or customize installation
  4. Wait for installation to complete
  5. Click 'Close' when finished

Important: Always check 'Add Python to PATH' during installation. This allows you to run Python from command prompt.

Verifying Installation

In Command Prompt/Terminal, type:

python --version

If installed correctly, it will show the Python version (e.g., Python 3.12.0)

Python Interactive Shell (IDLE)

IDLE is Python's Integrated Development and Learning Environment, included with Python installation.

To open IDLE:

  • Windows: Search 'IDLE' in Start Menu and click
  • Or open Command Prompt and type: idle

Writing Your First Program

In IDLE Interactive Mode:

>>> print("Hello, World!")
Hello, World!
>>>

Creating a Python Script File:

  1. Open IDLE and go to File → New File
  2. Type your code: print("Hello, World!")
  3. Save the file with .py extension (e.g., first_program.py)
  4. Run by pressing F5 or Run → Run Module

Python Syntax and Structure

Python Character Set

The set of valid characters that Python recognizes:

  • Letters: A-Z, a-z (English alphabets)
  • Digits: 0-9
  • Special Characters: + - * / = ( ) [ ] : ; , . ! ? @ # $ % ^ & ~
  • Whitespace: Space, Tab, Newline

Tokens

Smallest meaningful units in Python code:

1. Keywords (Reserved Words)

Words with special meaning to Python compiler. Cannot be used as variable names.

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

2. Identifiers

Names given to variables, functions, classes, and modules.

Rules for Identifiers:

  • Must start with letter or underscore (_), not a digit
  • Can contain letters, digits, and underscores
  • Case-sensitive: Name, name, and NAME are different
  • No spaces allowed
  • Cannot be Python keywords

Valid identifiers: name, _name, name123, myVariable, MY_CONSTANT

Invalid identifiers: 123name, my-var, my var, if, class

3. Literals

Fixed values written directly in code: 10, 3.14, "Hello", True

4. Operators

Symbols for operations: +, -, *, /, =, ==, !=, etc.

5. Delimiters

Special characters: ( ) [ ] , : . ; @ # $ % & ^ ~ !

Indentation

Python uses indentation (whitespace at the beginning of lines) to define code blocks. This replaces curly braces used in other languages.

if True:
    print("This is indented")  # 4 spaces
    print("Same block")
print("Outside block")

Important: Use consistent indentation (typically 4 spaces). Mixing tabs and spaces causes errors.

Variables in Python

A variable is a name that refers to a memory location where data is stored. In Python, you don't need to declare variable types - Python automatically determines the type.

Variable Assignment

name = "John"      # String variable
age = 25           # Integer variable
height = 5.9       # Float variable
is_student = True  # Boolean variable

# Multiple assignment
x = y = z = 10     # All three get value 10
a, b, c = 1, 2, 3  # a=1, b=2, c=3

Dynamic Typing

Python variables can change type during execution:

x = 10        # x is an integer
x = "Hello"   # x is now a string
x = 3.14      # x is now a float

Data Types in Python

1. Numeric Types

  • int (Integer): Whole numbers without decimal (10, -5, 0)
  • float (Floating-point): Numbers with decimal (3.14, -2.5, 0.0)
  • complex: Numbers with real and imaginary parts (3+4j)

2. String (str)

Sequence of characters enclosed in quotes:

name = "Python"      # Double quotes
lang = 'Python'      # Single quotes
text = """Multi
line string"""       # Triple quotes

3. Boolean (bool)

Represents True or False values. Used in conditional statements.

4. None Type

Represents absence of value or null value: x = None

5. Sequence Types

  • List: Ordered, mutable collection [1, 2, 3]
  • Tuple: Ordered, immutable collection (1, 2, 3)
  • Range: Sequence of numbers range(1, 10)

6. Mapping Type

Dictionary (dict): Key-value pairs {"name": "John", "age": 25}

7. Set Types

  • Set: Unordered, unique elements {1, 2, 3}
  • Frozenset: Immutable set

Type Checking and Conversion

# Check type
type(10)        # <class 'int'>
type("Hello")   # <class 'str'>

# Type conversion
int("25")       # Converts string to int: 25
str(100)        # Converts int to string: "100"
float(10)       # Converts int to float: 10.0

Operators in Python

1. Arithmetic Operators

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
//Floor Division10 // 33
%Modulus10 % 31
**Exponent10 ** 31000

2. Comparison (Relational) Operators

OperatorNameExampleResult
==Equal5 == 5True
!=Not equal5 != 3True
>Greater than5 > 3True
<Less than5 < 3False
>=Greater or equal5 >= 5True
<=Less or equal5 <= 3False

3. Logical Operators

  • and: Returns True if both conditions are True
  • or: Returns True if at least one condition is True
  • not: Reverses the Boolean value

4. Assignment Operators

  • = Simple assignment (x = 10)
  • += Add and assign (x += 5 means x = x + 5)
  • -= Subtract and assign
  • *= Multiply and assign
  • /= Divide and assign
  • //= Floor divide and assign
  • %= Modulus and assign
  • **= Exponent and assign

5. Identity Operators

  • is: Returns True if both variables refer to same object
  • is not: Returns True if variables refer to different objects

6. Membership Operators

  • in: Returns True if value exists in sequence
  • not in: Returns True if value does not exist in sequence

Input and Output

Output: print() Function

print("Hello, World!")
print("Name:", "John")       # Multiple values
print("Age:", 25, sep="-")   # Custom separator
print("Line1", end=" ")      # Custom end character
print("Line2")

Input: input() Function

The input() function always returns a string:

name = input("Enter your name: ")
age = int(input("Enter your age: "))    # Convert to integer
marks = float(input("Enter marks: "))   # Convert to float

Comments in Python

Comments are used to explain code and are ignored by the interpreter.

Single-line Comments

# This is a single-line comment
x = 10  # This is an inline comment

Multi-line Comments

"""
This is a multi-line comment
Also called docstring when used
at the beginning of a function
"""

Debugging in Python

Debugging is the process of finding and fixing errors (bugs) in code.

Types of Errors

1. Syntax Errors

Errors in code structure that prevent execution:

print("Hello"   # Missing closing parenthesis
if x == 5       # Missing colon

2. Runtime Errors

Errors that occur during execution:

x = 10 / 0      # Division by zero
print(name)     # NameError: variable not defined

3. Logical Errors

Code runs but produces incorrect results:

# Intended: average of a and b
average = a + b / 2  # Wrong: should be (a + b) / 2

Related Resources

Need Help?

Join our tuition classes for personalized guidance on Python.

Register for Classes →