0% found this document useful (0 votes)
7 views116 pages

Introduction to Python Programming

This document serves as an introduction to Python programming, covering fundamentals such as installation, syntax, data types, control structures, functions, and modules. It emphasizes Python's ease of learning, versatility, and community support, while also providing practical exercises for hands-on learning. Additionally, it highlights the use of popular libraries like NumPy and Pandas for data analysis and numerical computing.

Uploaded by

mohinaltahmim01
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)
7 views116 pages

Introduction to Python Programming

This document serves as an introduction to Python programming, covering fundamentals such as installation, syntax, data types, control structures, functions, and modules. It emphasizes Python's ease of learning, versatility, and community support, while also providing practical exercises for hands-on learning. Additionally, it highlights the use of popular libraries like NumPy and Pandas for data analysis and numerical computing.

Uploaded by

mohinaltahmim01
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

Introduction to

Python Programming
Your Journey into the World of Programming Begins Here

[Link]
Table of Contents

01 02
Python Fundamentals Data Types and
Control Structures

03 04
Functions and Modules File handling and
Error Management
05
Object Oriented
Programming and GUI
01
Python
Fundamentals
Today's Agenda
• What is Python?
• Why choose Python?
• Installing Python
• Python development environments
• Your first Python program
• Basic syntax and structure
• Interactive Python shell
• Hands-on practice

[Link]
What is Python?

High-Level Language Interpreted

Easy to read and write, closer No need to compile, runs


to human language directly from source code

Object-Oriented Cross-Platform

Supports object-oriented Runs on Windows, macOS,


programming paradigm Linux, and more
Why Choose Python

• Easy to Learn: Simple, readable syntax

• Versatile: Web development, data science, AI, automation

• Large Community: Extensive documentation and support

• Rich Libraries: Thousands of pre-built modules

• Industry Standard: Used by Google, Netflix, Instagram

• Career Opportunities: High demand in job market


Your First Python Program

• print("Hello, World!")
• print("Welcome to Python!")

Let's create and run this program together!


Basic Python Syntax

Key Point: Python uses indentation instead of braces!


Hands-On Practice
Let's Try These Together:

# Practice 1 :
• Basic printing print("My name is [Your Name]")
• print("I am learning Python!")
# Practice 2 :
• Simple calculations print(10 + 5) print(20 - 8) print(6 * 7)
# Practice 3 :
• Using variables age = 25 print("I am", age, "years old")
What Can You Build with Python?

Web Development Machine Learning


Django, Flask, FastAPI scikit-learn, TensorFlow, PyTorch

Data Science Desktop Applications


pandas, NumPy, Matplotlib Tkinter, PyQt, Kivy

Game Development
Pygame, Panda3D
Python Syntax Basics

Key Features:

• Indentation : Python uses indentation to define code blocks

• No Semicolons : Line endings are determined by newlines

• Case Sensitive : Variable names are case-sensitive

• Comments : Use # for single-line comments


02
Data Types and
Control Structures
Quick Recap - Day 1
✅ Installed Python and development environment

✅ Created first Python program

✅ Learned basic syntax and structure

✅ Used interactive Python shell

✅ Understood Python's philosophy

# Yesterday's Hello World


print("Hello, World!")
print("Welcome to Python!")
Today's Learning Journey

First Hour : Second Hour :

• Variables and assignment • Conditional statements (if/else)

• Numbers (int, float) • Comparison operators

• Strings and text • Loops (for and while)

• Booleans and logic • Loop control (break/continue)

• Lists and collections • Practical exercises

[Link]
Variables
Variables are containers for storing data values
# Creating variables name = "Alice"
age = 25
height = 5.6
is_student = True

# Using variables Remember: Python is dynamically


print("Name:", name) typed - you don't need to declare
print("Age:", age) variable types!
print("Height:", height, "feet")
print("Is student:", is_student)

[Link]
Python Data Types

Numbers Text Boolean

int, float, complex str (strings) True, False

age = 25 name = "Python" is_active = True


price =19.99 message = 'Hello!' is_done = False

Collections
list, tuple, dict, set

numbers = [1, 2, 3]
coords = (10, 20)
Working with Numbers
Floats (float)
Integers (int)
# Decimal numbers
# Whole numbers
price = 19.99
age = 25
year = 2024 temperature = 98.6
negative = -10 pi = 3.14159
# Math operations # Float
result = 10 + 5 # 15
operations result = 10 /3 # 3.333... result
result = 20 - 8 # 12
result = 6 * 7 # 42 = 7.5 + 2.5 # 10.0 result =
result = 15 // 3 # 5 (integer round(3.14159, 2) # 3.14
division)
# Type checking
result = 2 ** 3 # 8 (power)
print(type(price)) #
<class 'float'>
Strings - Working with Text

[Link]
Strings - Formatting
Boolean Values
True/False Values Truthy/Falsy Values
Lists - Storing Multiple Items
Break Time!
5-minute break

● Great job learning about data types!


● When we return, we'll dive into control structures
● Stretch your legs
● Grab some water
● Review what we've learned
Control Structures
Control the flow of your program's execution

Conditional Loops Control


if, elif, else for, while break, continue
If Statements - Making Decisions

[Link]
Comparison Operators
Basic Comparisons Logical Operators

[Link]
For Loops - Repeating Actions
While Loops - Conditional Repetition
Loop Control - Break and Continue
Break Statement Continue Statement
Practice Time!
Exercise 1: Number Guessing Game

[Link]
Let's Practice Together
Exercise 2: Shopping List Manager
Day 2 Summary
Data Types Mastered : Control Structures Learned :
✅ Variables and assignment ✅ If/elif/else statements
✅ Numbers (int, float) ✅ Comparison operators
✅ Strings and formatting ✅ For loops and range()
✅ Booleans and logic ✅ While loops
✅ Lists and operations ✅ Break and continue

Tomorrow: Functions and Modules


03
Functions and
Modules
Functions: Introduction
• A function is a reusable block of code that performs a specific task

• Helps in organizing code and promoting reusability

• Reduces repetition and improves code readability

Basic Function Syntax Simple Function Example


Function Parameters and Arguments

Best Practices

• Use descriptive parameter names

• Provide default values when

appropriate

• Be consistent with argument order


Variable Scope
• A function is a reusable block of code that performs a specific task

• Helps in organizing code and promoting reusability

• Reduces repetition and improves code readability

Basic Function Syntax Simple Function Example

[Link]
Local vs Global Variables
Lambda Functions
What are Lambda Functions?
• Short, anonymous functions
• Single expression functions
• Useful for simple, one-line operations
Lambda Functions
What are Lambda Functions?
• Short, anonymous functions
• Single expression functions
• Useful for simple, one-line operations

[Link]
Modules: Introduction
Why Use Modules?
• Makes your code organized
• Helps you reuse code
• Easy to share and manage
Creating Custom Modules
Why Use Modules?
• Makes your code organized
• Helps you reuse code
• Easy to share and manage
Standard Library Modules
Python's Standard Library is a collection of modules that come pre-installed
with Python, providing solutions for common programming tasks.

Key Benefits:

• No installation required - Available with every Python installation (unlike

NumPy, Pandas, etc.)

• Well-tested and reliable - Maintained by Python core developers

• Cross-platform compatible - Works on Windows, macOS, and Linux

• Extensive documentation - Comprehensive guides and examples


Standard Library Modules
Important: Don't confuse the Standard

Library with third-party packages!

Environments like Anaconda/Spyder come

with many pre-installed packages (NumPy,

Pandas, Matplotlib), but these are NOT part

of Python's Standard Library.

[Link]
Module Categories
System & OS File Handling
os, sys, subprocess, pathlib, shutil, glob,
platform tempfile

Data Processing Networking


json, csv, sqlite3, urllib, http, socket,
pickle email

Date & Time


Mathematics
datetime, time,
math, random,
calendar, zoneinfo
statistics, decimal
Popular Modules in Action

1. Working with Files - pathlib

[Link]
Popular Modules in Action
2. JSON Data - json

[Link]
Popular Modules in Action
3. Date and Time - datetime

[Link]
Popular Modules in Action
4. Random Numbers - random
Break Time!
5-minute break

● Great job learning about data types!


● When we return, we'll dive into control structures
● Stretch your legs
● Grab some water
● Review what we've learned

[Link]
Python Third-Party Libraries

NumPy
Fundamental package for numerical computing with
powerful N-dimensional array objects
Pandas
High-performance data manipulation and analysis library
with DataFrame structures
Matplotlib
Comprehensive library for creating static, animated, and
interactive visualizations
NumPy - Numerical Python

NumPy is the foundation of scientific computing in Python, providing


support for large, multi-dimensional arrays and matrices.

Key Features:

• N-dimensional array object (ndarray)

• Broadcasting functions

• Tools for integrating C/C++ and Fortran code

• Linear algebra, Fourier transform, and random number capabilities

[Link]
NumPy - Numerical Python
✅ What is NumPy?
Stands for Numerical Python Used for fast and efficient array operations, math,
and data analysis Ideal for working with large datasets, machine learning, and
scientific computing

Creating NumPy Arrays

Arrays are faster and more compact than lists

[Link]
NumPy - Numerical Python
• We want to work with vectors and matrices

• We want our code to run fast


• We want support for linear algebra

[Link]
List slicing
basic syntax: [start : stop : step]

► if step=1
► Slice contains the elements startto stop-1
► slice contains stop-startelements
► start, stop, and also step can be negative
► default values:

► start
► stop
0, i.e. starting from the first element
► step N, i.e up to and including the last element 1
Getting started
Import the NumPy package:

from numpy import *


from numpy import array, sin, cos import numpy
import numpy as np
Indexing and slicing in higher dimensions
► Usual slicing syntax

► Difference to lists: slices for the various axes separated by comma

a[2, -3]
0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39
Indexing and slicing in higher dimensions

0 1 2 3 4 5 6 7
a[:3, :5]
8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39
Indexing and slicing in higher dimensions

0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39
Indexing and slicing in higher dimensions

0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39
Indexing and slicing in higher dimensions

0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39
Indexing and slicing in higher dimensions

0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39

[Link]
a[1::2, ::3]
Indexing and slicing in higher dimensions
a[(1, 1, 2, 2, 3, 3), (3, 4, 2, 5, 3, 4)]

0 1 2 3 4 5 6 7

8 9 10 11 12 13 14 15

16 17 18 19 20 21 22 23

24 25 26 27 28 29 30 31

32 33 34 35 36 37 38 39

a[1::2, ::3]
Creating Arrays: Array Operations:
Pandas - Data Analysis Library

Pandas provides high-performance, easy-to-use data structures and


data analysis tools for Python.

Key Features:

• Data alignment and integrated handling of missing data

• Data filtering, grouping, and aggregation

• Merging and joining datasets

• Time series functionality

• Input/Output tools for CSV, Excel, SQL databases, and more

[Link]
Pandas Code Examples

Creating DataFrames:

[Link]
Pandas Code Examples

Data Operations:

[Link]
Matplotlib - Visualization Library
Matplotlib is a comprehensive library for creating static, animated, and
interactive visualizations in Python.

Components: Supported Plot Types:


• pyplot - MATLAB-like interface • Line plots, scatter plots, bar charts

for simple plotting • Histograms, pie charts, box plots

• Figure - The whole figure • Contour plots, 3D plots

(window) • Subplots and complex layouts

• Axes - The plot area with data


Matplotlib/pyplot Code Examples
Basic Plotting:
Matplotlib/pyplot Code Examples
Multiple Plots:

[Link]
Combining Libraries - Real Example
These libraries work seamlessly together for complete data analysis workflows:
Combining Libraries - Real Example
Summary & Best Practices
NumPy Matplotlib
• Numerical computations • Data visualization
• Array operations • Statistical plots
• Mathematical functions • Publication-quality figures
• Performance-critical code • Custom visualizations

Pandas
• Data cleaning and preparation
• Exploratory data analysis
• Time series analysis
• Data import/export
04
File handling and
Error Management
Agenda
Part 1: File Handling Basics
• Opening, reading, writing files
• File modes
• Context managers
Part 2: Advanced File Operations
• CSV, JSON, Binary files
• Directory operations
Part 3: Error Handling Try-except
• Exception types
• Best practices
Part 4: Integration & Practice Combining concepts
• Real-world examples • Q&A
File Handling Basics
Working with Files in Python

Mode Description If File Exists

'r' Read (default) Opens file

'w' Write Overwrites

'a' Append Adds to end

'x' Exclusive create Fails

Add to other modes ('rb',


'b' Binary mode
'wb')
Basic Syntax

• Handles errors gracefully


• Cleaner, safer
• No need to manually call [Link]()

[Link]
Reading Files

[Link]
Writing to Files

Note : Mode 'w' overwrites existing content! Use 'a' to append.


CSV File Operations
Reading CSV
CSV File Operations

Writing CSV

[Link]
Basic Error Handling

Try-Except Structure

Console Output in Spyder

Red text = Errors


Yellow text = Warnings
White/Black text = Normal output
Debugging with Variable Explorer
Spyder Debugger
Setting Breakpoints
IPython Magic Commands

Useful Commands for Debugging


Post-Mortem Debugging

Post-Mortem Debugging

[Link]
Try-Except-Else-Finally
Error Handling Best Practices
Do's
• Be specific with exception types

• Use context managers (with statement) for files

• Log errors for debugging

• Provide helpful error messages

• Clean up resources in finally blocks Don'ts ❌

• Don't use bare except clauses

• Don't suppress errors silently

• Don't use exceptions for flow control


Error Handling Best Practices

[Link]
Complete Example: Data Processor
Summary

Key Takeaways

• Use Spyder's Variable Explorer to inspect error context

• Set breakpoints for step-by-step debugging

• Use %debug for post-mortem analysis

• Write specific exception handlers

• Always clean up resources in finally blocks


05
Object Oriented
Programming and GUI
Object Oriented Programming
Object Oriented Programming
OOP organizes code into objects containing data and functions.

Real-World
Concept Description
Example

Class Blueprint for objects Car blueprint

Object Instance of a class Your specific car

Attributes Data/properties Color, model, year

Methods Functions/behaviors start(), drive(), stop()


The Four Pillars

01 Abstraction Hiding complex implementation

02 Encapsulation Bundling data and methods

03 Inheritance Creating new classes from existing ones

04 Polymorphism Same interface, different implementations


Object Oriented Programming
Object Oriented Programming

Key Points:
• __init__ is the constructor (initializer)
• self refers to the current instance
• Methods are functions defined inside a class

[Link]
Encapsulation & Properties
Encapsulation & Properties
Inheritance
Inheritance
Polymorphism

[Link]
Polymorphism

Benefits:
• Code reusability
• Flexibility
• Easy to extend

[Link]
[Link]
What is a GUI?
• GUI stands for Graphical User Interface
• Allows users to interact with programs visually (buttons, menus, windows)
• Examples: Calculator, File Explorer, Media Player

Popular Python GUI Libraries

• Tkinter - Comes with Python, great for beginners


• PyQt / PySide - Feature-rich, used in professional apps
• Kivy - Open source, best for multitouch apps (mobile/tablets)
• wxPython - Native look and feel on every platform
Why Use Tkinter?
• Built into Python, no need to install anything
• Very easy to write and understand
• Works on all major systems (Windows, Mac, Linux)
• Can create useful programs like forms, simple games, and data apps

Creating a Basic Window (Tkinter)


Adding Widgets
• Label: Display text or images
• Button: Perform actions on click
• Entry: Single-line text input
• Text: Multi-line text input
• Frame: Group related widgets visually

Creating a Basic Window (Tkinter)


Adding Widgets
• Label: Display text or images
• Button: Perform actions on click
• Entry: Single-line text input
• Text: Multi-line text input
• Frame: Group related widgets visually
Handling Events (Button Click)

• command=say_hello tells the button to run the function when clicked


• Useful for interactive GUIs

Entry and Label Update

• Gets user input from Entry


• Updates Label text dynamically
Menus and Message Boxes
• Adds File menu with Exit option
• Pops up an info box with a message
Menus and Message Boxes
• Adds File menu with Exit option
• Pops up an info box with a message

[Link]
Simple GUI App: Age Checker
Simple GUI App: To-Do List

[Link]
Simple GUI App: Age Checker
Question and answer

[Link]
Thanks!
Do you have any questions?
[Link]@[Link]
+9647503296645

You might also like