BPP-Lect-02-Introduction-To-Python
BPP-Lect-02-Introduction-To-Python
Prepared By:
Professor Dr. Md. Mijanur Rahman
Department of Computer Science & Engineering
Jatiya Kabi Kazi Nazrul Islam University
www.mijanrahman.com
Introduction To
Python Programming
CONTENTS
2.1. Python Programming ............................................................................................................1
2.1.1 Major Features of Python ................................................................................................2
2.2. Basic Structure of Python Program .......................................................................................2
2.2.1 Components of Python Program......................................................................................4
Python is also widely used for artificial intelligence and machine learning applications, and its
simplicity and ease of use have made it one of the most popular programming languages for data
scientists and machine learning engineers. The language provides a variety of libraries and tools
for tasks such as data visualization, numerical computing, and machine learning, making it a great
choice for those looking to build AI applications.
Python provides a very basic and simple structure for writing a program. It consists of different
sections. Some sections are compulsory, and some are optional. We can include or exclude the
optional sections as per requirement or as per the situation. Figure 2.1 shows the basic structure of
the Python program, and a brief explanation of each section in the Python program structure is as
follows:
1. Documentation section: The documentation section includes comments that specify the aim
of the program. We write comments in a program to improve the readability of the program.
2. Import statements: This section includes various in-built or user-defined modules in
different modules so that we can use functionality already defined in the existing module.
3. Global declaration section: In this section, we define global variables for the programs. A
global variable is a variable that we can access from anywhere in the program.
4. Class section: This section tells the information about the user-defined classes present in the
program. A class is a group of variables (called data members) and member functions (called
methods) that work on data members. It contains the class definition, data members, and
methods definition.
5. Subprogram section: In this section, we define user-defined functions. A function is a set
of statements that will execute when we call it from anywhere in the program.
6. Playground section: This is the main section where we call user-defined functions and class
methods. Moreover, we create an object of the class in this section.
In Python, there is no main function (i.e., main method) that separates the other section from
the playground (main) section. We can separate it by writing a comment line between the
playground and other sections for a better understanding.
This is a basic introductory program that is often used to demonstrate the syntax and structure of
a programming language.
2. Comments: In Python, we can add comments to the code to provide explanations, and
documentation, or to disable certain lines of code. Comments are ignored by the Python
interpreter and are meant for human readers.
The following are the two ways to write comments in Python:
a. Single-line comments: To add a comment that spans only a single line, we can use the
# symbol. Everything following the # symbol on that line will be considered a
comment. Example:
# This is a single-line comment in Python
b. Multi-line comments: If we want to add a comment that spans multiple lines, we can
enclose the comment in triple quotes (""" or '''). This is often referred to as a docstring
and can be used as a multi-line comment. Example:
"""
This is a multi-line comment
3. Import statements: These statements allow to import modules or libraries into the program.
The imported modules can provide additional functionality and classes in the program.
There are a few different ways to use import statements in Python:
a. Importing an entire module:
import module_name
This form of import statement allows to import an entire module. To access functions,
classes, or variables from the module, we need to prefix them with the module name
followed by a dot. Example:
import math
result = math.sqrt(16)
b. Importing specific names from a module:
from module_name import name1, name2
This form allows to import specific functions, classes, or variables directly into the
code, without needing to use the module name as a prefix. Example:
from math import sqrt, pi
result = sqrt(16)
c. Importing an entire module with a different name:
import module_name as alias_name
This form allows to import a module and assign it a different name (alias), which can
be useful if the original module name is long or conflicts with other names in the code.
Example:
import math as m
result = m.sqrt(16)
d. Importing all names from a module:
from module_name import *
This form imports all names (functions, classes, variables) from a module directly
into the code. However, it is generally considered good practice to avoid using this
form, as it can lead to name clashes and make the code less readable. Example:
from math import *
result = sqrt(16)
4. Function definitions: Functions are blocks of code that perform specific tasks. They can be
called multiple times from different parts of the program. Functions are defined using the
"def" keyword followed by the function name, parameters, and a colon. Example:
def function_name(parameters):
# Function body
# Code block with instructions
# Optional return statement
return value
5. Variables: Variables are used to store data in a program. Variables in Python can be
dynamically typed, meaning that the type of data stored in a variable can change during the
course of a program. We can assign a value to a variable using the assignment operator (=).
Example:
length = 5
width = 3
area = length * width # calculation using variables
name = "Rahman"
message = "Hello, " + name # concatenating strings
# Example:
print("This is the main code.")
result = some_function()
print("Result:", result)
7. Output statements: These statements are used to print output to the screen or to another
output device. The "print" function is used to print output in Python. Example:
print("The sum is ", sum)
The structure of a Python program is flexible and there is no strict rule on the order in which these
components should be placed, but it is a good practice to follow a standard structure to make your
code more readable and maintainable.
"""
This is a multi-line comment.
It spans multiple lines.
"""
'''
This is also a multi-line comment.
It can be enclosed within single quotes.
'''
Parameters:
x (int): The first number.
y (int): The second number.
Returns:
int: The sum of x and y.
"""
return x + y
# Commented-out code
# print(add(5, 10))
This script includes single-line comments, multi-line comments, comments at the end of lines,
comments for documentation (docstrings), and commented-out code.
x = 25
y = math.sqrt(x) # Calculate square root
print("The value of x:", x)
print("Square root of x:", y)
current_time = datetime.now()
print("Current time:", current_time)
data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print("Dataset:", data)
print("Mean:", mean(data)) # Mean value
print("Median:", median(data)) # Median value
# Float assignment
y = 3.14
print("\nFloat assignment:")
print("y is:", y) # Output: 3.14
# String assignment
name = "Alice"
print("\nString assignment:")
print("name is:", name) # Output: Alice
# Boolean assignment
is_valid = True
print("\nBoolean assignment:")
print("is_valid is:", is_valid) # Output: True
# Multiple assignments
a, b, c = 1, 2, 3
print("\nMultiple assignments:")
print("a is:", a) # Output: 1
print("b is:", b) # Output: 2
print("c is:", c) # Output: 3
# Swap values
x, y = y, x
print("\nSwapping values:")
print("x is:", x) # Output: 3.14
Parameters:
name (str): The name of the user.
Returns:
str: A greeting message.
"""
return f"Hello, {name}! Welcome to our program."
# Function call
user_name = input("Please enter your name: ")
greeting_message = greet(user_name)
print(greeting_message)
In this script, we define a function called greet that takes one parameter name. Inside the function,
we use an f-string to generate a greeting message with the provided name. The function returns
the greeting message. We then prompt the user to input their name. We call the greet function with
the provided user name and store the returned greeting message. Finally, we print the greeting
message to the console.