Python 1 [One]

Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

INTRODUCTION TO

OBJECT ORIENTED PROGRAMMING

IN

PYTHON
{Lesson Notes I: REVISED EDITION}

Compiled by

SADIQ MOHAMMED WAZIRI


(ND, B.TECH., M.SC. CS)
INTRODUCTION TO PYTHON
Python, created in 1991 by Guido von Russom, is a versatile programming language that
is used in a wide range of applications, including:
Web Development (Server-Side): Python can be used for server-side web development
through various web frameworks such as Django, Flask, and Pyramid. These frameworks
provide tools and libraries for building web applications, handling HTTP requests,
interacting with databases, and more. Python's simplicity and readability make it a popular
choice for web developers. Django, in particular, is known for its robustness and is often
used for building complex web applications.
Software Development: Python is widely used in software development for creating
various types of applications. It is known for its clear and concise syntax, which makes it
easy to write and maintain code. Python is suitable for developing desktop applications,
scientific software, data analysis tools, games, and more. It has extensive libraries and
frameworks for a wide range of tasks, which simplifies software development.
Mathematics: Python is a popular choice for mathematical and scientific computing.
Libraries like NumPy, SciPy, and SymPy provide powerful tools for numerical
calculations, data analysis, and symbolic mathematics. Scientists, engineers, and
researchers often use Python for tasks such as data visualization, statistical analysis,
machine learning, and solving complex mathematical equations.
System Scripting: Python is frequently used for system scripting and automation. System
administrators and DevOps professionals use Python scripts to automate routine tasks,
manage servers, and perform system-related operations. Its simplicity and cross-platform
compatibility make it a handy tool for creating scripts to interact with the operating system,
configure software, and perform various administrative tasks.

Characteristics of Python

• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python commands are written in lower case.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.

INTRODUCTION TO PYTHON 2
The COMMENT Statement
Comments are non-executable statements that start with a #, and Python ignores them
during its execution. They are used to explain codes or prevent their execution when
debugging/testing.
Examples
# This Program is for Almighty Formula

The PRINT Statement/Function


The print() function is used to display output on the console or terminal. It allows you to
output text, variables, or expressions so that you can see the results of your program
Syntax:
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout,
flush=False)

where:
value1, value2, ... are the values you want to print. You can provide multiple values
separated by commas, and print() will display them one after the other.
sep=' ' is an optional parameter that specifies the separator between the values. By default,
it is a space character (' '). You can change it to any other string if you want.
end='\n' is an optional parameter that specifies what character(s) should be printed at the
end of the print() statement. By default, it is a newline character ('\n'), which means the
next print() statement will start on a new line. You can change it to any other string or an
empty string ('').
file=sys.stdout is an optional parameter that specifies the file-like object where the output
should be directed. By default, it is set to sys.stdout, which represents the standard output
(console). You can redirect output to a different file if needed.
flush=False is an optional parameter that specifies whether the output should be flushed
(i.e., forcibly written to the output stream) immediately. By default, it is set to False,
meaning that Python will decide when to flush the output buffer.
Examples
1. String values
print("Hello, Yahaya!")
print("Hello, Yusuf.", "Do you go to school today?")

INTRODUCTION TO PYTHON 3
2. Numerical values
print(10, 20, 30)
print(100 + 350)

3. Combination of string and numerical values


print("Meiram", 20, “10 Lowcost Housing Estate Ext. Potiskum.”)

4. Using variables
name = "Meiram"
age = 20
address = “10 Lowcost Housing Estate Ext. Potiskum.”
print("Name:", name, "Age:", age, “Address:”, address)

5. Changing the separator


state1 = "Gombe"
state2 = "Bauchi"
state3 = "Adamawa"
state4 = "Yobe"
state5 = "Taraba"
state5 = "Borno"

print(state1, state2, state3, state4, state5, state6, sep=', ')

6. Changing the end character


print("This is my first statement.", end=' ')
print("This is the second one.")

7. Printing to a file
with open('output.txt', 'w') as f:
print("This will be written to output.txt.", file=f)

The INPUT Function


The input() function is used to interactively collect user input from the keyboard. It allows
a program to pause and wait for the user to enter a line of text or data, which can then be
stored in a variable. Here's how it works:

INTRODUCTION TO PYTHON 4
Syntax:
variable = input(prompt)

Where:
variable is the variable where the user's input will be stored. You can choose any valid
variable name.
prompt is an optional string argument that serves as a message or prompt to guide the user
in entering input. It's displayed to the user before waiting for input.

Examples:
1. Basic Input
suna = input("Me sunan ka? ") print("Barka, " suna)
suna = input("Fadi sunan ka: ") print("Barka Malam " + suna + "!")

This program prompts the user to enter their name and then displays a greeting using the
provided name.
2. Numeric Input
age = int(input("Nawa shekarun ka? ")) saura = 80 - age
print("Saura", saura, "ka cika tamanin!")

Here, the user is asked to enter their age as a number. The int() function is used to convert
the input from a string to an integer so that mathematical operations can be performed.
3. Handling User Input
user_input = input("Enter 'yes' or 'no': ")
if user_input.lower() == 'yes':
print("You said 'yes'.")
elif user_input.lower() == 'no':
print("You said 'no'.")
else:
print("I don't understand.")

This program takes user input and performs different actions based on whether the input is
'yes' or 'no,' regardless of the input's case (upper or lower).

INTRODUCTION TO PYTHON 5
The input() function is a valuable tool for creating interactive Python programs. It's
commonly used for tasks like collecting user preferences, accepting numerical input, and
building text-based games and applications. However, keep in mind that input() returns
user input as a string, so you may need to convert it to other data types (e.g., int or float)
when necessary.

The CONTROL STATEMENTS


Control statements, often referred to as control structures or flow control, are essential
elements in programming languages that allow you to control the flow of your program's
execution. They determine the order in which instructions are executed and enable you to
make decisions, loop through code, and create more dynamic and flexible programs.
Control statements are crucial for creating conditional logic, repetition, and branching in
your code.
Here are the primary types of control statements in programming:
1. if, elif, else statement (conditional)
Conditional statements are used to make decisions in your program based on certain
conditions.
The most common conditional statements include:
- if: Executes a block of code if a condition is true.
- elif (short for "else if"): Provides an alternative condition to check if the preceding `if`
condition is false.
- else: Executes a block of code if none of the previous conditions are true.

Syntax
if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
else:
# Code to execute if neither condition1 nor condition2 is
# true

Example
# Example of if, elif, and else statements

INTRODUCTION TO PYTHON 6
x = 10

if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")

2. for, while loops


Looping statements allow you to repeat a block of code multiple times. Common loop
statements include:
- for: Iterates over a sequence (e.g., a list, range) and executes code for each item in the
sequence.
- while: Repeats a block of code as long as a specified condition is true.

Syntax (for loop):


for item in sequence:
# Code to execute for each item in the sequence

Example 1
# Example of a for loop
abinci = ["tuwon_shinkafa", "tuwon_tsari", "masa",
“dan_wake”,”dambu”]
for fruit in fruits:
print(abinci)

Example 2
adj = ["kunun", "ruwan", "hancin",“katuwar”]
fruits = ["kanwa", "zafi", "takalmi",“jaka”]

for x in adj:
for y in fruits:
print(x, y)

For loop allows you to print a given range of items.

INTRODUCTION TO PYTHON 7
Example 3
for x in range(6):
print(x)

Below, for prints all numbers from 0 to 5, and prints a message when the loop has ends
(using else):
for x in range(6):
print(x)
else:
print("Finally finished!")

Syntax (while loop):


while condition:
# Code to execute as long as the condition is true

Example
# Example of a while loop
count = 0
while count < 5:
print("Count:", count)
count += 1

3. Control Statements for Exiting (break, continue)


- break: Terminates the current loop and continues with the next statement after the loop.
- continue: Skips the current iteration of a loop and proceeds to the next iteration.

Syntax (break):
for item in sequence:
if condition:
break

Example
# Example of using break to exit a loop early
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num == 5:
break # Exit the loop when num is 5
print(num)

INTRODUCTION TO PYTHON 8
Syntax (continue):
for item in sequence:
if condition:
continue
# Code here is skipped for the current iteration if the condition
# is true

Example
# Example of using continue to skip an iteration
for num in numbers:
if num % 2 == 0:
continue # Skip even numbers
print(num)

Summarily, in the above examples:


✓ The conditional statements check the value of the variable x and print different
messages based on its value.
✓ The for loop iterates over a list of fruits and prints each one.
✓ The while loop counts and prints numbers until it reaches 5.
✓ The first for loop uses break to exit early when it encounters the number 5.
✓ The second for loop uses continue to skip even numbers and only print odd
numbers.
These examples illustrate how control statements can be used to make decisions, loop
through data, and control the flow of your Python programs.
Control statements are fundamental to creating programs that respond to different
scenarios, process data efficiently, and automate repetitive tasks. They provide the means
to build complex, interactive, and adaptive software. Understanding and using control
statements effectively is a key skill for programmers and software developers.

OTHER BASIC CONCEPTS AND TOPICS THAT NEED CONSIDERING

1. Variables and Data Types


- Explain the concept of variables as containers for storing data.
- Introduce basic data types such as integers, floats, strings, and booleans.
- Teach how to declare and assign values to variables.

INTRODUCTION TO PYTHON 9
name = "Yusuf"
age = 16
is_student = True

2. Mathematical Operations
- Show how to perform basic mathematical operations (addition, subtraction,
multiplication, division, and modulo).

x = 5
y = 3
result = x + y

3. Basic Input Validation


- to use conditional statements to validate user input and handle errors gracefully.

age_str = input("Enter your age: ")


if age_str.isdigit():
age = int(age_str)
else:
print("Invalid input. Please enter a number.")

4. Lists
- lists as ordered collections of data.
- to create, access, modify, and iterate through lists.

tubers = ["dankali", "gwaza", "doya"]


print(tubers[0]) # Access the first element
tubers.append("rogo") # Add an element to the end

5. Functions
- concept of functions as reusable blocks of code.
- to define, call, and pass arguments to functions.

def greet(suna):
print("Barka, " + suna + "!")

greet("Abubakar")

6. Basic Error Handling


- the concept of exceptions and how to handle them using try and except.

INTRODUCTION TO PYTHON 10
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")

7. String Manipulation
- to manipulate strings, including concatenation and string methods.

greeting = "Hello, " + name + "!"


length = len(greeting)

SIMPLE PROJECTS

i. Design a program that solves quadratic problems using the Almighty Formula:

ii. Write a program that solves the cycle geometric problems.

iii. Write a program that handles the volumes of a cylinder, cube, cuboid and a
sphere.

INTRODUCTION TO PYTHON 11

You might also like