Python 1 [One]
Python 1 [One]
Python 1 [One]
IN
PYTHON
{Lesson Notes I: REVISED EDITION}
Compiled by
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
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)
4. Using variables
name = "Meiram"
age = 20
address = “10 Lowcost Housing Estate Ext. Potiskum.”
print("Name:", name, "Age:", age, “Address:”, address)
7. Printing to a file
with open('output.txt', 'w') as f:
print("This will be written to output.txt.", file=f)
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.
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")
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)
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!")
Example
# Example of a while loop
count = 0
while count < 5:
print("Count:", count)
count += 1
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)
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
4. Lists
- lists as ordered collections of data.
- to create, access, modify, and iterate through lists.
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")
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.
SIMPLE PROJECTS
i. Design a program that solves quadratic problems using the Almighty Formula:
iii. Write a program that handles the volumes of a cylinder, cube, cuboid and a
sphere.
INTRODUCTION TO PYTHON 11