0% found this document useful (0 votes)
79 views19 pages

Introduction to Python Programming

This document outlines a lesson plan for teaching Python, covering its definition, installation, basic syntax, and execution methods. It emphasizes Python's popularity in various industries and compares it with other programming languages. The document also provides detailed instructions for setting up Python on different operating systems and introduces fundamental programming concepts such as variables, data types, and user input.

Uploaded by

gokulkavinmunis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views19 pages

Introduction to Python Programming

This document outlines a lesson plan for teaching Python, covering its definition, installation, basic syntax, and execution methods. It emphasizes Python's popularity in various industries and compares it with other programming languages. The document also provides detailed instructions for setting up Python on different operating systems and introduces fundamental programming concepts such as variables, data types, and user input.

Uploaded by

gokulkavinmunis
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Lesson Objeetives: oRTINJAL

IBy the end of this lesson, students wil] be ablo to.

Understand what Python is and why it is widely used.


Learn how to install and set up Python.
Write and execute their first
Python program.
Explore Python's basic syntax and
interactive shell.
Understand the role of indentation in Python.

1. Introduction to Python
Python is one of the most popular programming languages today. It is known for its
readability, and versatility. Whether you are a beginner in coding or an experienced simplicity,
is a great choice for learning and building developer, Python
applications.

1.1 What is Python?


Python is a high-level, interpreted programming language that was created by Guido van Rossum in
the late 1980s and officially released in 1991. It was designed with code readability and simplicity in
mind, naking it easier for beginners to learn and use.
Key characteristics of Python:

Interpreted: Python code is executed line-by-line, which makes debugging easier.


High-level Language: Python is easy to read and write, similar to the English language.
Dynamically Typed: You don't need to declare data types explicitly; Python assigns them
automatically.
Object-Oriented & Functional: Supports both object-oriented and functional programming
paradigms.
Cross-Platform: Runs on Windows, macOS, Linux, and even on mobile devices.
Extensive Libraries:Comes with built-in libraries for various applications like AI, Data
Science, Web Development, and more.

1.2 Why Python?


Python is widely used across industries for various applications, such as:
I. Web Development
Python provides powerful frameworks like Diango and Flask for developing web applications
efficiently.
[Link] Science & Machine Learning
IWih lbraries like NunPy, Pandas, Matplotib, TensorFlow, and Scikit-learn, Python is the top choice
fo data analysis, visualization, and AI development.
8. Autaion Sorinting
T'ython can autonate repetitive tasks such as file handling, web scraping, and system admin1stiatioh
using libraries like Selenium and BeautifulSoup.
4. Game Development
Python's Pygame library is used for developing simple 2D games.
5. Cybersecurity & Ethical Hacking
Tools like Scapy and PyCrypto help in penetration testing and cybersecurity analysis.
6. Embedded Systems & IoT
Python is used in IoT projects with devices like Raspberry Pi.
7. Desktop Applications
Libraries like Tkinter, PyQt, and Kivy allow Python to be used for GUI-based applications.

1.3 Python's Popularity in the Industry


Python consistently ranks among the top programming languages in the world due to its flexibility,
ease of learning, and growing community support.
Some of the biggest companies using Python include:
Google (used in YouTube, Google Search)
Facebook (backend services)
Netflix (personalized recommendations using AI)
NASA(scientific computing)
Amazon (AWS cloud services)

Python's growing demand makes it an essential skill for students aspiring to build a career in
software development, data science, Al, and cybersecurity.

1.4 Comparing Python with Other Languages


Feature Python C++ Java JavaScript
Syntax
Very simple Complex Medium Mediumn
Simplicity
Compilation Interpreted Compiled Compiled Interpreted
Slower than
Speed C++/Java
Fast Fast Fast

System programming, Enterprise Web


Use Case
General-purpose games apps development
Lenrning Curve Seginner-friendly Steeper Moderate Moderste
Tyhna s'wy rle yniar nd versatility make it a great choice, especially for beginners
2. Installing Python
Before we start writingand executing Python programs, we need to install Python on our system. This
section will guide studentsthrough the installation process on Windows, macOS, and Linux.
along with setting up an IDE (Integrated Development Environment) for a better coding
experience.
2.1 Downloading Python
Python can be downloaded firom its official website:
Download Python
Choosing the Right Version
Python 3.x is recommended, as Python 2.x is outdated and no longer supported.
The latest stable version of Python should be used unless there is a specific reqirement for an
older version.

2.2 Installing Python on Windows


Step 1: Download the Installer

Visit [Link] and download the latest Windows Installer (64-bit or 32-bit, depending
on your system).
Step 2: Run the Installer
to PATH"
Open the downloaded file and ensure you check the box that says "Add Python
before clicking Install Now.
prompt (CMD) directly.
This step is important as it allows us to use Python from the command

Step 3: Verify the Installation


Open Command Prompt (CMD)and type:
python -version
(e.g., Python 3.10.5).
If installed correctly, it should display the installed Python version

2.3Installing Python on macOS


Step 1: InstallUsing the Official Installer
application.
Download the macOS installer from [Link] and install it like any other
Method)
Step 2: Install Python via Homebrew (Alternative
If you have Homebrew installed, you can install Python using:
brew installpython
Step 8:Verify Installation
Open Terminal and type:
thon3 --vErgion
This should d'slay the installed Python version.
2.4 Installing Python on Linux
pre-installed. To check if Python is already installed or
Most Linux distributions come with Python
the Terminal and type:
Python3 --version
Linux distribution:
If Python is not installed, use the following command based on vour
Ubuntu/Debian:

sudoapt update sudo aptinstall python3


Fedora:
sudo dnf install python3
Arch Linux:
sudo pacman -S python
After installation, verify using:
python3 -version

2.5 Setting Up an Integrated Development Environment (IDE)


Python can be written and executed in different environments. Here are some commonly used IDEs
and text editors for Python development:
1. IDLE (Integrated Development and Learning Environment) - Default Python
IDE
Installed automatically with Python.
Simple interface for writing and running Python scripts.
Suitable for beginners.
2. VS Code (Recommended for Beginners & Advanced Users)
Alightweight and powerful editor from Microsoft.
Supports Python through the Python extension.
Steps to install:

Download from [Link].


Install the Python extension from the Extensions Marketplace.
3. PyCharm (Best for Professional Development)
A full-fledged IDE for Python with
debugging and project management features.
Available in Community (Free) and Profession al(Paid) versions.
Download from [Link]/pvcharm.
4, Jupyter Notebok (Best for Data Seience &AI)
TTeed in Daie ScienceGnd Machine Learning.
A:iowsrurning Python co0e in an interactive notebook format.
/Pip install jupyter

Programs
2.6 Running Python
start writing and executing Python programs in multiple ways.
Once Python is installed, you can
(Interactive Mode)
1. Using the Python Shell
or Terminal(MacLinux).
Open Command Prompt(Windows) Python
macOS/Linux) and press Enter to start the interactive
Type python (orpython3 on
shell.
commands directly.
Youcan now type Python
Example:
>>>print("Hello, Python!")
Hello, Python!
Toexit the interactive shell, type:

exit()
2. Running Python Seripts (Seript
Mode)

Open a text editor (IDLE, VS Code, PyCharm).


it with a .py extension.
Write the Python code in a new file and save
prompt:
Run the script in the terminal or command
python [Link]
content:
Example: Create a file [Link] with the following
print("Welcome to Python Programming!")
Run the file using:
python [Link]

3. Running Python Programs


Development Environment
Nowthat Python is installed on your system and you have an Integrated
main ways to execute
(IDE) set up, it's time to learn how to run Python programs. There are two
methods.
Python code: Interactive Mode and Script Mode. This section will guide you through both

3.1Interactive Mode
Interactive Mode allows you to enier and executePython code line-by-line directlv in the termina.
or command prompt. This mode is useful for quick tests, learning, and experimenting with Python
code snippets.
ow to Inter Interactive Mode:
Type python and press Enter (or python3 if you are on a system with multiple Py

versions).
byt
vërsion number followed
The Python shell will open, and you'll see the Python by the
>>> prompt. F

2. macOS/Linux:

Open Terminal.
o Type python 3 (for macOS/Linux, Python 3 is invoked using python 3) and press Enter.
You willsee the Python version number and the >>> prompt, indicating that you are
now in the interactive shell.

Working in Interactive Mode:


Youcan directly enter any Python command at the prompt (>>>) and execute it.
The results of the command are displayed immediately.
Example:
>>>print("Hello, Python!")
Hello, Python!
>>>5 +7
12
>>> 20/4
5.0

Exiting Interactive Mode:


To exit the interactive mode, type the following and press
Enter:
exit()

3.2 Seript Mode


Script Mode allows you to write a Python program in a text file and save it with a .py extension. This
method is ideal for writing larger programs or projects and then executing them in one go.
Steps for Running Python Programs in Script Mode:
1. Step l: Create a Python File

Open yourIDE or text editor (such as IDLE, VS Code, or PyCharm).


Create a new file and write your Python code.
Save the file with a .py extension, such as first_program.py.
Example:
#first [Link]
zrint("Welcome to Python Programming!")
2. Step 2: Run the Python File
Veu can run the Python script in the following ways:
Vsng Command Prompt(Windows) or Terminal (mac0S/Linur):
1 NaVigate to the directory where the Python iie is saved.
2. Type the
following command and press Enter:
python first [Link]
(For macOS/Linux, use python3 instead of python.)

Using an IDE:
If you're using an IDE (VS Code,
PyCharm, IDLE), simply press the
(or use the corresponding keyboard shortcut) to execute the script. Run button
Output:
Welcome to Python Programming!

3.3 Running Python Programs in


IDLE
IDLE (ntegrated Development and Learning Environment) is Python's
interactive environment for writing and running Python code. default editor and provides an
1. Open IDLE from your start menu (Windows) or
applications folder (macS).
2. In IDLE, select File > New File and write
your Python code.
3. Save the file with a .py extension.
4. To run the script, press F5 or select Run > Run Module.

3.4 Running Python Programs in VS Code or Py Charm


VS Code and PyCharm are popular code editors that offer more advanced features than IDLE, such
as syntax highlighting, debugging, and code completion.
VS Code:

1. Open VS Code and install the Python extension from the Extensions Marketplace.
2. Create a new file, write your Python code, and save it with a .py extension.
3. To run the program, press the Run button on the top-right, or press Ctrl+ F5
(Windows/Linux) or Cmd + F5 (macOS).
PyCharm:
1. Open PyCharm and create a new project.
2. Write your Python script in the editor and save it.
3. To run the script, click the Run button at the top-right corner oruse Shift+FI0.

3.5 Debugging Python Code


When running a Python program, sometimes errors may occur. Here are a few wavs to deb:g and
identify issues:
Cyrtaz rror:
eirors), Python will disn
I1 there's an error in the syntax (e.g., missing parenthesesor indentation
error.
an errOr message indicating the line number and type of
Example:
print("Hello, World!"
Output:
SyntaxError: unexpected EOF while parsing
Runtime Errors:

If your code runs into an error while executing. Python willstop execution and display an error
message.
Example:
num = 10 print (num /0)
Output:
ZeroDivisionError: division by zero
Logical Errors:
Logical erTors do not generate error messages but can result in incorrect output. It's important to test
and review your code carefully to debug these issues.

4. Understanding Python Syntax & Structure


Python is known for its clean, simple, and readable syn tax. Unlike other programming languages
that rely on curly braces to define code blocks, Python uses inden tation to structure code. This
section willcover basic Python syntax, including indentation, comments, variables, and data types,
tohelp you write your first Python programswith confidence.

4.1 Python Syntax Overview


Key Features of Python Syntax:
Python code is executed line-by-line (interpreted language).
Indentation is used instead of braces f? to define code blocks.
Python is case-sensitive (name and Name are different variables).
Statements do not require semicolons (), but they can be used optionally.

4.2 Indentation in Python


In Python, indentation (spaces or tabs at the beginning of a line) is mandatory to define code blocks.
Tncorrect indentation results in errors.
3xannpie (Correct Indentation):

le grect(): Ereeti)
3rini/eilo, yirCni ? #Lndenied bicch
Example (Incorrect Indentation - Causes Error):
def greet():
print("Hello, Python!") # Missing indentation greet()
Output:
IndentationError: expected an indented block
V Tip: Always use 4 spaces for indentation instead of tabs to avoid errors.

4.3 Writing Comments in Python


Comments in Python help explain the code but are ignored by the interpreter.
Single-line comments:
Use # before the text.
# This is a comment

print("Hello, VWorld!") # This is also a comment


Multi-line comments:
Use triple quotes ("" or y.

This is amulti-line comment.


Python ignores this while executing the code.

print("Python is fun!")
Tip: Use comments to explain complex logicbut avoid excessive commenting.

4.4 Variables & Data Types


Declaring Variables
A variable stores a value and does not require explicit declaration.
name = "Alice"# String

age = 20 # Integer

height = 5.7# Float

is_student= True # Boolean


Rules for Naming Variables
Must start with a letter (a-z, A-Z) or an underscore
Can contain letters, digits (-9), and underscores
Caniot use Python keywerds (e.g., if, for, def print)
Case-sensitive (Narne and name are different)
my_naIne = ohn "

-age = 25

total_narks = 95
Incorrect Examples (Causes Errors):
2name ="Alice" #Cannot start with a
my name = "Bob" #Spaces are not
number
allowed
def= 50#'def" is a Python keyword

4.5 Data Types in


Python
Python supports various built-in data types:
Data Type Example
Description
int 10
Integer numbers
float 3.14
Decimal numbers
str "Hello"
Text (string)
bool True or False
Boolean values
list [1, 2, 3] Ordered, mutable collection
tuple (10, 20, 30) Ordered, immutable collection
set {1, 2, 3} Unordered, unique elements
dict "name": "Alice", "age": 25} Key-value pairs
Example Using Different Data Types:
x = 10 # int

y=3.14 #float

name= "Alice" #str

is_valid = True # bool

numbers = [1, 2, 3] # list

4.6 Taking User Input


Python allows user input using the input) function.
name input("Enter your name: ")
prins"Heilo, " + name + "jm)

Eyamle with umber input (Using int() to Convert Input to Integer):


nge = ini(inpui("Enter your age: "))

print("Youare", age, "vears old. ")

4.7Printing Output in Python


Python uses the print() function todisplay output.
print("Welcome to Python!")
Printing Multiple Items:
name "Alice"

age = 20

print("Name:", name, "Age:", age)

Using f-strings for Formatted Output:


print(fMy name is fname} and I am fage} years old. ")

4.8 Type Conversion (Type Casting)


str(), etc.
Convert between data types using int(), float(),
Example:
num = "10" # String

integer
num_int = int(num) # Converts string to

print(num_int + 5) # Output: 15

5. Python as an Interpreted Language


its code is executed line by line at runtime
Python is an interpreted language, meaning that characteristic makes Python easier to
instead of being compiled into machine code beforehand. This
we will explore what it means for
debug, highly portable,and dynamically typed. In this lesson,
execution.
Python to be interpreted and how it affects program

5.1 What is an Interpreted Language?


In programming, there are two main types of languages:
1. Compiled Languages (e.g., , C++):
Code is written in a high-level language.
A compiler translates the entire program into machine coe before execution.
The resulting esecuiabie ffle can run without requiring the original source code.

?. Intaroroted Langusges (e.g., Python, JavaScript, Ruby):


language.
Code iswritten in ahigh-level runtime.
o code line by line at
executes the
o An
interpreter reads and
step is nceded.
Noseparate compilation
Python as an Interpreted Language processes thes
compilation before execution. Instead, the Python interpreter
Pythondoes not require
code diectly at runtime.
Example of Python Execution:
print("Hello, World!")
Execution Process:

1. The Python interpreter reads the print() statement.


2. It translates it intomachine-understandable instructions.
3. The output is displayed immediately.

5.2 How Python Executes Code

Python'sexecution happens in two main steps:


Step 1: Converting Source Code to Bytecode
When a Python script runs, the interpreter first converts the high-level Python code into an
intermediate form called bytecode (not machine code yet).
Bytecode is stored in -pyc files (Python Compiled files) inside the_pycache_ folder.
This bytecode helps Python run faster by avoiding recompilation on every execution.
Example: Running a Python File
python [Link]
This command triggers Python's interpreter, which compiles the code into bytecode before executing
it.

Step 2: Running Bytecode in the Python Virtual Machine (PVM)


The Python Virtual Machine (PVM) executes the bytecode.
PVM is platform-independent, meaning Python programs can run on any OS without
modification.

5.3Difference Between Compilation and Interpretation


Interpreted Languages (Python,
Feature Compiled Languages (C, Java) JavaSeript)
Translates the entire code before "Translates and runs line by line
Execution
running
Generally faster Slightly slower

Drctectian Shows allerrors at once Stops at the first error


Reature
Compiled Languages (C, Java) Interpreted Languages (Python,
JavaScript)
Platform Needs recompilation for different
Independence platforms Runs on any system with an interpreter

Ease of Debugging Harder to debug Easier, as errors appear one byone


Example of an Error in an Interpreted Language (Python):
print("Hello, World!")
print(10 /0) # This willcause an error, stopping execution
print("This willnot run.")
Output:
Hello, World!
ZeroDivisionError: division by zero
Since Python is interpreted, execution stops at the first error.

5.4 Advantages of Python Being Interpreted


Ease of Use: Nocompilation step is needed; just run the script.
Portability: Python runs on Windows, macOS, Linux, etc., without recompilation.
Faster Debugging: Errors are detected at runtime.
unlike compiled languages
Dynamic Typing: Python determines variable types at runtime,
that require type declaration.

5.5 Limnitations of an Interpreted Language


generally slower than
Slower Execution: Since Python interprets code line by line, it is
compiled languages.
more memory as it translates code on the
More Resource Usage: The interpreter consumes
fly.
meaning some bugs may not be
Runtime Errors: Python executes until an error occurs,
caught early.

6. Writing Simple Python Programs


an interpreted language, let's apply this
Now that we understand Python's syntax and how it runsas
cover essential programming concepts
knowledge by writing simple Python programs. This lesson will
basicarithmetic operations, and conirol flow.
such as printstciements, variables, user input,

$.1 Vriting Yeur Pirst Python Frogram


extension. Let's start witha simole clie, :
Python progras are Yrivien as text fles [Link]
Example: "Hello, World!" Program
print("Hello, World!")
Output:
Hello, World!

This is the simplest Python program. The print() function is used to disp lay output.

6.2Using Variables in Python


A variable stores data in memory and can be used later in the program.
Example:Storing and Printing Variables
name = "Alice"
age = 20
print("Name:", name)
print("Age:", age)
Output:
Name: Alice

Age: 20

Tip: Python automatically assigns a data type based on the value.

6.3 Taking User Input


Python's input() function allows users to enter values during program execution.
Example: Taking User Input
name = input("Enter your name: ")

print("Hello,", name + "!")


Output (User enters "John'"):
Enter your name: John

Hello, John!
By default, input) takes input as a string. Convert it if needed.
Example: Taking Numeric Input
age =int(input("Enter your age: "))

print("Next year, you will be", age + 1, "years old.")


Output (U'ser enters 18):
EnteryOUr ae: I3

rCrt the inDut to an intege.


6.4 Peri
tornuIng Basic
Python supports basic Arithmetic Operations
Example: Simple Calculator
mathematical operations.
a=
b= int(input("Enter first number: ")
int(input("Enter
Sum_=a+ b second number: ")
diff =a -b
prod =a*b
guotl =a/b # Division returns a
quot2 =a/b # Division returns a float
int
print("Sum:", sum_)
print("Difference:", diff)
print("Product:", prod)
print("Quotient1:", quot1)
print("Quotient2:", quot2)
Output: Simple Calculator
Enter first number: 20
Enter secondnumber:2
Sum: 22
Difference: 18
Product: 40
Quotient1: 10.0
Quotient2: 10
V Tip: Use / for integer division and % for remainder calculation.

6.5 Using Conditional Statements (if-else)


Conditional statements allow programs to make decisions.
Example: Check if a Number is Even or Odd
num = int(input("Enter a number: ))
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")

Output (User enters 7):


7is Odd
V Tip: if statements must be indented correctly.

.Lceing Cenatruets in Python


1o evecurea olcok of code mulinle tines.
for i in range(1, 6):

print("Number:"%, i)
Output:
Number: 1

Number: 2

Number: 3

Number: 4

Number: 5

V Tip: range(start, end) generates numbers from start to end-1.


Example: Using a while Loop
num =1

while num <= 5:

print("Number:", num)
num +=/

Output:
Number: 1

Number: 2
Number: 3

Number: 4

Number: 5

V Tip: Be careful with while loops to avoid infinite loops.

6.7 Writing a Simple Python Program with All Concepts


number
Now, let's combine variables, input, arithmetic, conditionals, and loops into a simple
guessing game.
Example: Number Guessing Game

import cndom
secret_number= [Link](1, 19)

cliempis =
nrintuesg the nuntber öeiiUeen I and ifi
ciuess =
int(input("Enter your guess: "))
attempts += 1
if guess <
secret_number:
print("Too low! Tryagain. ")
elifguess >secret_number:
print("Too high! Try again.")
else:

print(f"Congratulations! You guessed it in fattempts} attempts.")


break
Output (User guesses 3, then 7, then 5 correctly):
Guess the nunber between 1 and 10!

Enter your guess: 8

Too low! Try again.

Enter your guess: 7

Too high! Try again.

Enter your guess: 5

Congratulations! You guessed it in 3 attempts.


VTip: The break statement exits the loop when the user guesses correctly.

7. Interactive Python Shell & Basic Operations


The Python Interactive Shell(also called the Python REPL) is a great tool for testing small pieces
of code quickly. In this lesson, we'l learn how to use the shell, perform basic operations, and
understand its advantages.

7.1What is the Python Interactive Sheil?


The Python Interactive Shell is an environment where you can type Python commands and see
results immediately, without needing to write and run a script.
REPL stands for:

R’ Read (Takes user input)


E’Evaluate (Processes the input)
-Print (Displays thecutput)
, o p (Pepeats the pocess)
7.2 Opening the Python Shell
Method 1: Using the Terminal or Command Prompt
I. Opern a terminal (CommandPrompt, PowerShell, or Terminal on macOS/Linux).
2. Type python or python3 and press Enter.
3. You will see the Python prompt (>>>) where you can enter comimands..
Example:
$ python
Python 3. I1.2 (default, Mar 10 2025, [Link])
[GCC 9.3.0] on linux
Type "help", "copyright", "eredits" or "license" for more information.
>>>

7.3 Using the Python Shell for Quick Caleulations


The Python Shell acts like a calculator and can perform various arithmetic operations.
Example: Basic Arithmetic
>>> 5 +3

>>> 10 -4

>>>3 * 4
12

>>> 10 /2

5.0

V Tip: The /operator always returns a float.


Example: Integer Division & Modulus
>>> 10l3 # Integer division (quotient)
3

>>> 10% 3 # Modulus (remainder)

Ti: gives the quotient, %gives the rermainder.


Exanple: Exponentiation
>>t*? 2raised to the power of 3
4 Assigning and
Using Variables in the Shell
Youcan define
variables in the shell and use them in
Example: Storing Values in calculations.
>>>x = 10 Variables
>>>y=5
>>>Sum_ =X+y

>>>Sum_
15

7.5Using Built-in
Functions in the Shell
The Python Shell allows quick
testing of built-in functions.
Example: Using type)
>>> type(10)
<class 'int>
>>> type(3. 14)
<class float'>
>>> type("Hello")
<class 'str'>

Example: Using input()


>>> name =input"Enter yaur nane: ")
Enter your name: Alice

>>>print("Hello,", name)
Hello, Alice
Note: input() works in the shell, but loops and long programs are
best written in scripts.

7.6 Exiting the Python Shell


To exit the Python Shell:
On
Windows/macOS/Linux, type exit() or press Ctrl + Z (Windows) or Ctrl + D
Linux/macOS).

You might also like