Basic Elements of Python
Prof. Murali Krishna Gurram
Dept. of Geo-Engineering & RDT
Centre for remote Sensing, AUCE
Andhra University, Visakhapatnam – 530 003
Dt. 27/09/2024
Basic Elements of Python
a) Rapid introduction to procedural programming
b) Data Types:
• Identifiers and Keywords,
• Integral types,
• Floating Point Types
Procedural Programming
Procedural Programming
Definition:
Procedural programming is a programming paradigm derived from
structured programming.
It relies on the concept of procedure calls, where procedures (or
functions) are blocks of code that perform a task.
Key Concepts:
• Sequential Execution: Instructions are executed in order.
• Procedures (Functions): Encapsulated code blocks that perform a
specific task.
• Variables: Store data used in procedures.
• Control Structures: Decision-making (if-else) and loops (for, while).
Procedural Programming
Key Concepts:
Sequential Execution: Instructions are executed in order.
Procedures (Functions): Encapsulated code blocks that perform
a specific task.
Variables: Store data used in procedures.
Control Structures: Decision-making (if-else) and loops (for,
while).
Procedural Programming
Key Concepts:
Example: A simple Python program that uses a function to print a message.
def greet():
print("Hello, world!") # Procedure (function) definition
greet() # Function call
Procedural Programming
2. Functions: The Core of Procedural Programming:
Why Use Functions?
Code Reusability: Avoid repeating code.
Modularity: Break complex problems into smaller,
manageable tasks.
Maintainability: Easier to update and maintain.
Procedural Programming
2. Functions: The Core of Procedural Programming:
Basic Function Structure:
Function Definition: Uses the def keyword.
Parameters: Inputs to the function.
Return Values: Functions can return values.
Example: A function to add two numbers.
def add_numbers(a, b):
return a + b # Returns the sum of a and b
# Calling the function
result = add_numbers(3, 5)
print("Sum:", result)
Procedural Programming
3. Variables: Local vs. Global Scope:
Local Variables: Defined inside a function and only
accessible within that function.
Global Variables: Defined outside all functions and
accessible throughout the program.
Example: Demonstrating local and global variables.
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Inside function:", x) # Local x is used
my_function()
print("Outside function:", x) # Global x is used
Procedural Programming
4. Control Structures in Procedural Programming:
Procedural programming heavily relies on control structures
to define the flow of execution.
Conditionals (If-Else Statements):
Allows decision-making in code based on conditions.
Example: Checking if a number is positive, negative, or zero.
def check_number(n):
if n > 0:
print("Positive number")
elif n < 0:
print("Negative number")
else:
print("Zero")
check_number(10)
Procedural Programming
4. Control Structures in Procedural Programming:
Loops (For and While Loops):
Loops are essential for repetitive tasks.
For Loop: Iterates over a sequence (like a list or range).
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)
While Loop: Repeats as long as a condition is true.
count = 0
while count < 5:
print("Count:", count)
count += 1
Procedural Programming
5. Example: Simple Python Calculator using Functions:
Procedural programming enables the creation of organized
and reusable code like a calculator with functions.
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b != 0:
return a / b
else:
return "Error: Division by zero"
# Example usage
num1 = 10
num2 = 5
print("Addition:", add(num1, num2))
print("Subtraction:", subtract(num1, num2))
print("Multiplication:", multiply(num1, num2))
print("Division:", divide(num1, num2))
Procedural Programming
6. Real-World Application:
Key Takeaways:
Procedural programming breaks complex problems into smaller,
manageable tasks through functions.
It is widely used in automation scripts, data processing, and
solving computational problems.
Practical Example: Procedural programming in Python is commonly
used for:
Building automation scripts.
Performing mathematical computations.
Data analysis tasks in fields like finance and research.
Procedural Programming
Quick Exercise:
Write a function that calculates the factorial of a given number
using a loop.
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # Output: 120
Data Types:
Identifiers and Keywords,
Integral types,
Floating Point Types
Introduction to Data Types in Python
Definition:
A data type in Python refers to the kind of value a variable can
hold.
Python’s dynamically typed nature allows it to infer the type of
a variable when it’s assigned a value.
Common Data Types in Python:
Numeric Types : int, float
Text Type : str
Boolean Type : bool
Sequence Types : list, tuple, etc.
Introduction to Data Types in Python
Why Data Types are Important:
Data Types help Python interpret and perform operations on
data correctly.
Data Types ensure efficient memory usage and error-free code.
Visual Example:
Imagine each data type as a box that holds values of a specific
kind:
Integers (whole numbers) go into one type of box.
Floating-point numbers (with decimal points) go into another.
Introduction to Data Types in Python
2. Identifiers and Keywords:
Identifiers:
Definition: Identifiers are names given to variables, functions,
classes, or other objects in Python.
Rules for Naming Identifiers:
Can contain letters (a-z, A-Z), digits (0-9), and underscores
(_).
Cannot start with a digit (e.g., 1st_place is invalid).
Python is case-sensitive, so 'Var' and 'var' are different
identifiers.
Introduction to Data Types in Python
2. Identifiers and Keywords:
Example:
# Valid Identifiers
age = 25
student_name = "Alice"
height_in_meters = 1.75
# Invalid Identifiers
1st_place = "Winner" # Starts with a number
student-name = "Alice" # Contains hyphen (-), which is not allowed
Introduction to Data Types in Python
2. Identifiers and Keywords:
Best Practices:
Use descriptive names: student_name instead of x.
Follow naming conventions:
lowercase with underscores for variable names.
PascalCase for class names.
Keywords:
Definition: Keywords are reserved words in Python that have a
special meaning. These cannot be used as identifiers.
List of Common Keywords:
if, else, for, while, class, def, return, True, False
Introduction to Data Types in Python
2. Identifiers and Keywords:
A flowchart illustrating the use of keywords in Python (such as if-
else structures).
Introduction to Data Types in Python
2. Identifiers and Keywords:
Example: The following would raise an error because def is a
keyword.
def = 5 # Invalid, because "def" is a keyword
Example: To list all Python keywords.
import keyword
print(keyword.kwlist)
Introduction to Data Types in Python
3. Integral Types (int):
Integer Data Type:
Definition:
• The int type in Python represents whole numbers, both positive
and negative, without a decimal point.
Memory Usage:
• Python automatically adjusts the size of integers based on the
magnitude of the number. Unlike other languages, Python does
not restrict integer size.
Key Characteristics:
• No size limit.
• Python supports both positive and negative integers.
Introduction to Data Types in Python
3. Integral Types (int):
Example: To list all Python keywords.
x = 10 # Positive integer
y = -25 # Negative integer
z = 0 # Zero
Introduction to Data Types in Python
3. Integral Types (int):
Basic Arithmetic Operations:
Python provides built-in operators for performing arithmetic on
integers.
• Addition: +
• Subtraction: -
• Multiplication: *
• Division: / (Always results in a float, even if both operands are
integers)
a = 15
b=4
print("Addition:", a + b) # Output: 19
print("Subtraction:", a - b) # Output: 11
print("Multiplication:", a * b) # Output: 60
print("Division:", a / b) # Output: 3.75 (Float result)
Introduction to Data Types in Python
3. Integral Types (int):
Integer Division (//):
Integer Division returns the floor value of the division, discarding
the decimal part.
print("Integer Division:", a // b) # Output: 3 (floored result)
Introduction to Data Types in Python
3. Integral Types (int):
Modulus (%):
Modulus returns the remainder of the division.
print("Modulus:", a % b) # Output: 3 (remainder of 15/4)
Introduction to Data Types in Python
3. Integral Types (int):
Exponentiation (**):
Exponentiation raises one number to the power of another.
print("Exponentiation:", a ** b) # Output: 50625 (15 raised to the power
of 4)
Introduction to Data Types in Python
3. Floating Point Data Types (int):
Definition:
The float type represents numbers with decimal points. It's used when more
precision is needed than integers can offer, especially for scientific and financial
calculations.
Key Characteristics:
Follows the IEEE 754 standard for floating-point arithmetic.
Can represent very large or small numbers using scientific notation.
pi = 3.14159 # A common floating-point number
g = -9.8 # Negative floating-point number
scientific = 1.23e4 # 1.23 × 10^4 = 12300.0
Introduction to Data Types in Python
3. Floating Point Data Types (int):
Floating-Point Arithmetic:
Just like integers, floating-point numbers support basic arithmetic operations,
but with decimal precision.
x = 10.5
y = 4.2
print("Addition:", x + y) # Output: 14.7
print("Subtraction:", x - y) # Output: 6.3
print("Multiplication:", x * y) # Output: 44.1
print("Division:", x / y) # Output: 2.5
Introduction to Data Types in Python
3. Floating Point Data Types (int):
Precision Issues in Floating-Point Numbers:
Floating-point numbers are not always 100% precise due to how they're stored
in memory.
result = 0.1 + 0.2
print(result) # Output: 0.30000000000000004 (slight precision error)
Introduction to Data Types in Python
3. Floating Point Data Types (int):
Rounding Floats:
To handle precision errors, you can use Python’s round() function to round off
floating-point numbers to a specified number of decimal places.
value = 3.14159
print(round(value, 2)) # Output: 3.14 (rounded to 2 decimal places)
Introduction to Data Types in Python
3. Floating Point Data Types (int):
Scientific Notation with Floats:
Python allows very large or small numbers to be written in scientific notation
using e (exponent) notation.
large_number = 2.5e6 # 2.5 × 10^6 = 2500000.0
print(large_number) # Output: 2500000.0
Thank You