Lesson 1 of 2010 min read

Introduction to Python

Share:WhatsAppLinkedIn

Prerequisites: Basic computer knowledge, understanding of what a program is


1. What is Python?

Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991 at the National Research Institute for Mathematics (CWI) in the Netherlands.

The name "Python" comes from the BBC comedy show Monty Python's Flying Circus, not from the snake.

Key Features of Python

Feature Explanation
Simple and easy to learn Reads almost like English; minimal syntax
Open source Free to download, use, and distribute
Interpreted Executed line by line (no separate compilation step)
Platform independent Same code runs on Windows, macOS, Linux
Case sensitive Number, number, and NUMBER are three different names
Rich standard library Built-in modules for files, math, networking, etc.
Dynamically typed No need to declare variable types
Uses indentation Code blocks defined by indentation (not braces {})

Python 2 vs Python 3

Modern courses (and this path) use Python 3 (specifically 3.x). Key difference to know:

# Python 2 (OLD - do NOT use)
print "Hello"

# Python 3 (current standard)
print("Hello")

2. Installing Python

  1. Go to https://www.python.org/downloads/
  2. Download the latest Python 3.x version for your operating system
  3. During installation on Windows, check "Add Python to PATH"
  4. Python comes with IDLE (Integrated Development and Learning Environment)

To verify installation, open a terminal/command prompt and type:

python --version

Output:

Python 3.12.0

3. Interactive Mode vs Script Mode

Python can be used in two ways:

Interactive Mode (Shell Mode)

  • Open IDLE or type python in terminal, You get the >>> prompt, Type one statement at a time, get result immediately, Good for quick testing and learning
  • Cannot save code for reuse
>>> 2 + 3
5
>>> print("Hello")
Hello
>>> x = 10
>>> x * 2
20

Script Mode (Program Mode)

  • Write code in a file with .py extension (e.g., hello.py), Save the file, Run it: python hello.py or press F5 in IDLE
  • Code is saved and reusable
# File: hello.py
name = "Aarav"
print("Hello,", name)
print("Welcome to Python!")

Output:

Hello, Aarav
Welcome to Python!

Comparison Table

Feature Interactive Mode Script Mode
Prompt >>> No prompt
Execution Line by line Entire file at once
Save code No Yes (.py file)
Best for Testing, quick calculations Writing real programs
Shows result Automatically for expressions Only with print

Important difference: In interactive mode, typing 2 + 3 shows 5. In script mode, you must write print(2 + 3) to see the output.


4. First Program: Hello World

# Example 1: Hello World
print("Hello, World!")

Output:

Hello, World!
# Example 2: Multiple print statements
print("Welcome to Python")
print("Python")
print("Let's start coding!")

Output:

Welcome to Python
Python
Let's start coding!

5. Python Character Set

The characters that Python recognizes and allows in programs:

Category Characters
Letters A-Z, a-z
Digits 0-9
Special Symbols + - * / % = ! < > { } [ ] , . ; : @ # & ' " \ _ ^ ~
Whitespace Space, Tab (\t), Newline (\n)
Other Python 3 supports Unicode (so Hindi, Chinese, etc. can be used in strings)

6. Tokens in Python

A token is the smallest individual unit in a program. Python has 5 types of tokens:

6.1 Keywords (Reserved Words)

Keywords are pre-defined words with special meaning. They cannot be used as variable names. Python 3 has 35 keywords (this number may vary slightly across versions):

False True None and or
not if elif else for
while break continue pass def
return class import from as
try except finally raise with
yield lambda global nonlocal del
in is assert async await
# Example 3: Checking if a word is a keyword
import keyword
print(keyword.kwlist) # prints all keywords as a list
print(len(keyword.kwlist)) # number of keywords
print(keyword.iskeyword("if")) # True
print(keyword.iskeyword("hello")) # False

Output:

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', ...]
35
True
False

6.2 Identifiers (Names)

Identifiers are names given to variables, functions, classes, modules, etc.

Rules for naming identifiers:

  1. Must start with a letter (A-Z or a-z) or underscore (_)
  2. Remaining characters can be letters, digits (0-9), or underscores
  3. Cannot start with a digit
  4. Cannot be a keyword
  5. Case sensitive (age, Age, and AGE are different)
  6. No special characters allowed (!, @, #, $, %, etc.) except underscore
  7. No limit on length (but keep it readable)
Valid Identifiers Invalid Identifiers Reason
name 2name Starts with digit
_count my-name Hyphen not allowed
student1 my name Space not allowed
total_marks for Keyword
MAX_VALUE @price Special character
__init__ marks% Special character
# Example 4: Valid and invalid identifiers
my_name = "Priya" # valid
_score = 95 # valid (starts with underscore)
student1 = "Rahul" # valid (digit not at start)
# 1student = "Error" # INVALID - starts with digit (SyntaxError)
# my-name = "Error" # INVALID - hyphen not allowed (SyntaxError)

6.3 Literals (Constant Values)

Literals are fixed values (data) used in a program.

Numeric Literals:

# Integer literals
a = 10 # decimal (base 10)
b = 0b1010 # binary (base 2) = 10 in decimal
c = 0o17 # octal (base 8) = 15 in decimal
d = 0xFF # hexadecimal (base 16) = 255 in decimal

# Float literals
e = 3.14 # decimal form
f = 1.5e2 # scientific notation = 150.0
g = 2.5E-3 # scientific notation = 0.0025

String Literals:

s1 = 'Hello' # single quotes
s2 = "World" # double quotes
s3 = '''Multi 
line string''' # triple quotes (can span multiple lines)
s4 = "He said \"Hi\"" # escape sequence for quotes inside string

Boolean Literals:

x = True # boolean True (internally = 1)
y = False # boolean False (internally = 0)
print(True + True) # 2 (because True = 1)
print(True + False) # 1

Special Literal:

z = None # represents absence of value / null

Collection Literals:

my_list = [1, 2, 3] # list literal
my_tuple = (1, 2, 3) # tuple literal
my_dict = {"a": 1, "b": 2} # dictionary literal
my_set = {1, 2, 3} # set literal

6.4 Operators

Symbols that perform operations on values/variables:

+, -, *, /, //, %, **, =, ==, !=, <, >, <=, >=, and, or, not, in, is, etc.

(Covered in detail in an earlier lesson.)

6.5 Punctuators

Symbols used to organize code structure:

', ", #, \, (, ), [, ], {, }, ,, :, ., ;, @, =, +=, -=, *=, /=, //=, %=, **=


7. Comments

Comments are notes written by the programmer that are ignored by the Python interpreter. They make code readable and understandable.

Single-Line Comment

Use # symbol. Everything after # on that line is a comment.

# Example 5: Single-line comments
# This program calculates the area of a circle
radius = 7 # radius in centimeters
area = 3.14 * radius ** 2 # area = pi * r^2
print("Area =", area) # display the result

Output:

Area = 153.86

Multi-Line Comment

Python does not have a dedicated multi-line comment syntax. Two approaches:

# Approach 1: Multiple single-line comments
# This is line 1 of the comment
# This is line 2 of the comment
# This is line 3 of the comment

# Approach 2: Triple-quoted string (not a true comment, but commonly used)
'''
This is a multi-line comment.
It spans multiple lines.
Python treats this as a string that is not assigned to any variable,
so it is ignored.
'''

8. Concept of L-value and R-value

This concept explains the two sides of an assignment statement.

  • L-value (Left value): The variable on the left side of =. It represents a memory location where a value will be stored. Must be a valid variable name.
  • R-value (Right value): The expression on the right side of =. It represents a value that will be stored. Can be a literal, variable, or expression.
# Example 6: L-value and R-value
x = 10 # x is L-value (memory location), 10 is R-value (value)
y = x + 5 # y is L-value, x + 5 is R-value (evaluates to 15)
z = y # z is L-value, y is R-value (value of y, which is 15)

# INVALID:
# 10 = x # ERROR! 10 cannot be an L-value (it's not a variable)
# x + 5 = y # ERROR! An expression cannot be an L-value

Key rule: L-value must always be a variable (a name that refers to a memory location). R-value can be any valid expression.


Code Examples Summary

# Example 7: Complete program combining multiple concepts
# Program to calculate simple interest

# Taking input
principal = float(input("Enter principal amount: "))
rate = float(input("Enter rate of interest: "))
time = float(input("Enter time in years: "))

# Calculating simple interest
si = (principal * rate * time) / 100 # formula: SI = PRT/100

# Displaying output
print("Simple Interest =", si)

Output (sample run):

Enter principal amount: 10000
Enter rate of interest: 8.5
Enter time in years: 3
Simple Interest = 2550.0

Common Mistakes

  1. Forgetting parentheses with print: Writing print "Hello" (Python 2 syntax) instead of print("Hello")
  2. Starting identifier with a digit: 1name = "Error" is invalid
  3. Using keywords as variable names: if = 5 causes SyntaxError
  4. Forgetting that Python is case-sensitive: Print("Hello") gives NameError (capital P)
  5. Confusing interactive mode behavior with script mode: Expressions do not auto-display in script mode
  6. Using wrong quotes: Mixing up 'single' and "double" quotes (both are valid, but must match)
  7. Not understanding that comments are ignored: Expecting # print("Hello") to produce output

$1$2 Quick Tips

  1. Definition questions (1-2 marks): "What is Python?", "What are tokens?", "List features of Python", keep answers concise and include 4-5 points
  2. Identify valid/invalid identifiers (1-2 marks): Very common; know the rules thoroughly
  3. Keywords questions: "List any 5 keywords" or "Is ___ a keyword?", memorize the important ones: if, else, elif, for, while, True, False, None, and, or, not, break, continue, def, return, import, class
  4. Interactive vs Script mode (2 marks): Know the differences; can be asked as a table
  5. Find the error (1-2 marks): Given code with syntax errors in identifiers or keywords
  6. Comment questions: Difference between single-line and multi-line comments
  7. L-value and R-value (1-2 marks): Identify L-value and R-value in an assignment statement; explain why 10 = x is invalid

Test Your Knowledge

Take a quick quiz on this lesson

Start Quiz →

Prefer watching over reading?

Subscribe for free.

Subscribe on YouTube