Python Basics
Dr M Chandralekha
Assistant Professor (Sr. Grade)
Dept. of CSE
Agenda
• Overview of Programming Paradigms
• Introduction to Python
• Setting up Python with Anaconda
• Input and Output
• Variables
• Operators
• Data Types
• Strings
Overview of Programming Paradigms
• Definition
• A programming paradigm is a style or way of programming.
• Different paradigms provide different approaches to solving problems.
• Key Programming Paradigms
1. Procedural Programming
2. Object-Oriented Programming (OOP)
Procedural Programming
• Definition Example
• A programming paradigm based on the concept of
procedure calls, where code is organized into def calculate_area(length, width):
sequences of instructions or steps (procedures).
return length * width
• Focuses on functions and the flow of data through
functions.
area = calculate_area(5, 3)
• Key Characteristics print("Area:", area)
• Linear Structure: Code is typically written in a top-
down approach.
• Functions: Reusable blocks of code that perform # Output: Area: 15
specific tasks.
• Global Data: Data is often shared and modified
across multiple functions.
Object-Oriented Programming (OOP)
• Definition
• Example
• A programming paradigm that organizes code into objects,
which are instances of classes. Objects contain both data class Rectangle:
(attributes) and functions (methods) that operate on the data. def __init__(self, length, width):
• Focuses on creating reusable and modular code through [Link] = length
encapsulation, inheritance, and polymorphism. [Link] = width
• Key Characteristics
def calculate_area(self):
• Encapsulation: Bundling of data and methods that operate on
return [Link] * [Link]
the data within a class.
• Inheritance: Mechanism for creating new classes from
rect = Rectangle(5, 3)
existing ones.
print("Area:", rect.calculate_area())
• Polymorphism: Ability of different classes to be treated as
# Output: Area: 15
instances of the same class through inheritance.
Introduction to Python
• What is Python?
• High-Level Language: Easy to read and write, making it ideal for beginners and experts
alike.
• Interpreted: Code runs line by line, allowing for quick testing and debugging.
• Versatile: Used in web development, data science, automation, AI, and more.
• Cross-Platform: Works on Windows, macOS, Linux, and more.
• Why Python?
• Simplicity: Clean syntax that emphasizes readability.
• Large Community: Extensive libraries and resources available.
• Growing Demand: Widely used in industries, leading to strong job prospects.
Setting up Python with Anaconda
•Step 1: Download Anaconda
•Visit the Anaconda website.
•Choose the appropriate installer for your operating system (Windows, macOS, or Linux).
•Step 2: Install Anaconda
•Run the installer and follow the on-screen instructions.
•Windows Users: Ensure you check the option to add Anaconda to your PATH environment
variable.
•macOS/Linux Users: Follow the standard installation instructions.
•Step 3: Launch Anaconda Navigator
•Open Anaconda Navigator from the Start Menu (Windows) or Applications (macOS).
•Explore tools like Jupyter Notebook, Spyder, and more.
•Step 4: Verify Installation
•Open Anaconda Prompt or your terminal.
•Type conda --version to check that Anaconda is installed correctly.
•Test Python installation by typing python in the Anaconda Prompt and running a simple
command, like print("Hello, Anaconda!").
•Step 5: Create a Python Environment (Optional)
•Create a new environment: conda create -n myenv python=3.8
•Activate the environment: conda activate myenv
•Step 6: Manage Packages with Conda
•Install new packages: conda install package_name
•Update packages: conda update package_name
Input and Output
• Output: Using ‘print()’
• Basic Syntax:
print("Hello, World!")
• Multiple Outputs:
print("Hello,", "World!")
• Formatting Output:
• Using ‘f-strings’:
name = "Alice"
print(f"Hello, {name}!")
• Using ‘format()’ method:
age = 25
print("I am {} years old".format(age))
• In Python, .2f is a format specifier used to format floating-point
numbers to display exactly two decimal places.
• The f indicates that the number should be treated as a floating-point
number, and .2 specifies the precision, meaning two digits after the
decimal point.
Output:
3.14
• Input: Using ‘input()’
• Basic Syntax
name = input("Enter your name: ")
print(f"Hello, {name}!")
• Handling Numbers
• Convert input to integer or float
age = int(input("Enter your age: "))
height = float(input("Enter your height: "))
• Example
name = input("What is your name? ")
print(f"Nice to meet you, {name}!")
Variables
• Definition
• A variable is a name that refers to a value stored in memory.
• Variables are used to store data that can be referenced and manipulated in a program.
• Creating Variables
• Syntax
• variable_name = value
• Example
• x = 10 # Integer
• y = 3.14 # Float
• name = "Alice" # String
• is_student = True # Boolean
• Variable naming Rules
• Must start with a letter (a-z, A-Z) or an underscore (_).
• Can contain letters, numbers, and underscores (_).
• Case-sensitive (age, Age, and AGE are different variables).
• Cannot use Python keywords (e.g., if, while, return).
• Examples
• valid_name = "John"
• age = 25
• _height = 170
• Dynamic Typing
• Explanation
• In Python, variables can change type after they have been set.
• Example
• x = 10 # x is initially an integer
• x = "Hello" # Now x is a string
• print(x) # Output: Hello
• Multiple Assignments
• Example
a, b, c = 5, 10, 15
print(a, b, c) # Output: 5 10 15
# Assigning the same value to multiple variables
x=y=z=0
print(x, y, z) # Output: 0 0 0
Operators
• Arithmetic Operators
x = 10
y=3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
print(x / y) # Division: 3.33
print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
print(x // y) # Floor Division: 3
• Comparison Operators
x = 10
y=5
print(x == y) # Equal: False
print(x != y) # Not Equal: True
print(x > y) # Greater Than: True
print(x < y) # Less Than: False
print(x >= y) # Greater Than or Equal To: True
print(x <= y) # Less Than or Equal To: False
• Logical Operators
a = True
b = False
print(a and b) # Logical AND: False
print(a or b) # Logical OR: True
print(not a) # Logical NOT: False
• Assignment Operators
x = 10
x += 5 # Equivalent to x = x + 5
print(x) # Output: 15
x *= 2 # Equivalent to x = x * 2
print(x) # Output: 30
Data Types
• Definition
• Data types define the type of data a variable can hold in Python.
• Python has several built-in data types that are used to classify data.
• Common Python Data types
• Integer (int) - Whole numbers, positive or negative, without decimals.
• Float (float) - Numbers that contain a decimal point.
• String (str) – A sequence of characters enclosed in single or double quotes.
• Boolean (bool) - Represents one of two values: True or False.
• List (list) - An ordered collection of items, which can be of different types, enclosed in square
brackets.
• Tuple (tuple) - An ordered collection of items similar to a list, but tuples are immutable (cannot be
changed after creation).
• Dictionary (dict) – A collection of key-value pairs, enclosed in curly braces.
• Set (set) - An unordered collection of unique items, enclosed in curly braces.
Strings
• Definition
• A string is a sequence of characters enclosed in single (') or double (") quotes.
• Strings are used to represent text in Python.
• Example
name = "Alice"
greeting = 'Hello, World!’
• String Operations
• Concatenation
Combine strings using the + operator.
• Example
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: John Doe
• Repetition
Repeat strings using the * operator.
• Example
laugh = "Ha" * 3
print(laugh) # Output: HaHaHa
• String Indexing and Slicing
• Indexing
Access individual characters using their index (starts at 0).
• Example
word = "Python"
print(word[0]) # Output: P
print(word[-1]) # Output: n (negative index starts from the end)
• Slicing
Extract a substring using the slice notation [start:end]
• Example
word = "Python“
print(word[0:3]) # Output: Pyt
print(word[2:]) # Output: thon
print(word[:3]) # Output: Pyt
• String Methods
• Common Methods
text = "Hello, World!"
print([Link]()) # Output: hello, world! (convert to lowercase)
print([Link]()) # Output: HELLO, WORLD! (convert to uppercase)
print([Link]("World", "Python")) # Output: Hello, Python! (replace substring)
print([Link](",")) # Output: ['Hello', ' World!'] (split into a list)
• String Formatting
• f-strings
Embed expressions inside string literals, using {}.
• Example
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Alice and I am 30 years old.
• Using format() method:
• Example
price = 9.99
quantity = 3
total = "Total price: ${:.2f}".format(price * quantity)
print(total) # Output: Total price: $29.97
Example#1 – Compound Interest Calculation
# Input values
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual interest rate (in %): "))
time = float(input("Enter the time period (in years): "))
n = int(input("Enter the number of times interest is compounded per
year: "))
# Calculate the amount after the given time period
amount = principal * (1 + rate / (n * 100)) ** (n * time)
# Calculate the compound interest
compound_interest = amount - principal
# Output the results
print(f"Compound Interest: {compound_interest:.2f}")
print(f"Total Amount: {amount:.2f}")
Example#2 – Area and Circumference of the
Circle
import math
# Input value
radius = float(input("Enter the radius of the circle: "))
# Calculate the area of the circle
area = [Link] * radius ** 2
# Calculate the circumference of the circle
circumference = 2 * [Link] * radius
# Output the results
print(f"Area of the Circle: {area:.2f}")
print(f"Circumference of the Circle: {circumference:.2f}")
Example#3 – Volume and Surface Area of the
Cylinder
import math
# Input values
radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))
# Calculate the volume of the cylinder
volume = [Link] * radius ** 2 * height
# Calculate the surface area of the cylinder
surface_area = 2 * [Link] * radius * (radius + height)
# Output the results
print(f"Volume of the Cylinder: {volume:.2f}")
print(f"Surface Area of the Cylinder: {surface_area:.2f}")
Practice Questions
• Write a Python program that calculates the volume and surface area of a sphere given its radius.
• Write a Python program to calculate simple interest given the principal amount, annual interest
rate, and time period.
• Write a Python program that calculates the BMI given a person's weight in kilograms and height in
meters.
• Write a Python program that acts as a simple calculator. It should take two numbers and an
operator (+, -, *, /) as input and perform the corresponding operation.
• Write a Python program that takes the original price of an item and a discount percentage as input
and calculates the discounted price. Formula: Discounted Price = Original Price - (Original Price
×\times× Discount Percentage / 100)