0% found this document useful (0 votes)
4 views30 pages

Introduction To Python

Uploaded by

birimomall2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

Introduction To Python

Uploaded by

birimomall2
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Horn of Africa College

ALPHA UNIVERSITY
Las’Anod campus

Topic Python

Title Introduction

Presenter Abdirahman Ahmed Mohamed

abdirahman4644@[Link] 00252905181633
Introduction to Python

1 What is Python? 2 What does a Python do?

Python is a high level, general- With python you can perform:


purpose programming language. ▪ Data analysis
It supports multiple programming ▪ Automation
paradigms, including structured ▪ Web Apps
(particularly procedural), object- ▪ Mobile Apps
oriented and functional ▪ AI / ML
programming. ▪ Hacking and so on.
print () function

1 What is print ()function? 2 print ()function syntax examples

Print () function prints the Print (“Hello World!”)


specified message on the screen Hello World
or other standard output devices.
Print (10+20)
30
Variables

1 What is a variables? 2 Variable declaration examples

A python variable is a reserved Magac = “Abdirahman Ahmed”


memory location to store values.
Age = 25
Age = 25 Job = Instructor
Variable Assignment Value
Operator a=b=c=2
Variable classes

1 Classes/types of variables 2 Print classes and multiple assignment

Int (integer) Class=> Print (type (name))


<class ‘str’>
Float
Str (string) Multiple assignment => a = b = 2
str => name = “Ahmed” print (a, b)
22
Int => age = 30 a, b, c, = 4, 10.5, “Ahmed”
Float => height = 1.78
Basic Operators

Arithmetic operators Exapmle


a = 10
+ (plus) b = 12
- (minus) Print (a + b)
22
* (times)
a = “Ahmed)
/ (float division) b = 10*a
// (int division) Print(b)
% (remainder)
a = 10 * “Ahmed \n”
** (power) Print (a)
Basic Operators

Comparison operators Examples


< (less than) a = 10
> (greater than) b = 20
== (equal to) Print (a > b)
!= (not equal to)
>= (greater than or equal to)
False
<= (less than or equal to) Print ( a != b )
True
Basic Operators

Assignment operators Examples


a = 10
= (assignment) a += 5
+= (add) Print (a)
*= (times) 15
b = “Ahmed \n)
-= (subtract) b *= 10
/= (float division) Print (b)
//= (int division) Ahmed
Ahmed
%= (remainder equal) Ahmed..
**= (times equal)
Basic Operators

Logical operators Membership operators


In
and not in
or Example
not a = “Hello”
B = “l”
Example Print (a in b)
a = True True
b = True Print (a not in b)
False
Print (a and b)
Basic Operators

Identity operators Print (a is not b)


True
is
is not
Examples
a = 10
b = 12
Print (a is b)
False
Input function

magac = input (“Gali magacaaga: ”)


Print (magac)
Gali magacaaga: Axmed
sannadka= int (input(“Gali sannadka dhalashada: ”))
da’ = 2023 – sannadka
Print (da)
Gali sannadka dhalashada: 1998
25
Control flow – conditionals

If if…..else nested if
Example ( if ..)
a = int (input(“Enter a number less than 10: ”))
If a < 10:
Print (a, “is less than 10”)
If a == 10:
Print (a, “equals 10”)
If a > 10:
Print (a, “is greater than 10”)
Control flow – conditionals

If…. else
Example
a = int (imput())
If a %2 == 0:
print (“dhaban”)
Else:
print(“kinsi”)
Control flow – conditionals

If…..elif…. else
Example
a = int (input(“Enter a number: ”))
If a > 0:
print (“Positive”)
elif a < 0:
print(“Negative”)
else:
Print (“Zero)
Control flow – conditionals
Nested …. If
Example Num = int (input(“Enter a number: ”)
If num % 2 == 0:
if num % 3 ==0:
print (“divisible by 2 and 3”)
else:
print (“divisible by 2 not 3”)
Else:
if num % 3 == 0:
print (“divisible by 3 not 2”)
else:
print (“not divisible by 2 and 3”)
loops
While loop
Example
i=0
While i <= 10:
print (i)
i += 1
1
2
3
4
….
loops
for loop
Example
For i in range (10):
Print (i)
1
2
3

9
loops
for loop (use more parameters)
Example
For i in range (1, 10, 2):
Print (i)
1
3
5
7
9
Loop control statements
Continue
Example
For i in range (1, 10, 2):
if i == 5:
continue
Print (i)
1
3
5
7
9
Loop control statements
Continue
Example
For i in range (1, 10, 2):
if i == 5 or i == 9:
continue
Print (i)
1
3
5
7
9
Loop control statements
Break
Example
For i in range (10):
if i == 5:
break
Print (i)
1
2
3

9
List and list comprehensions
# Traditional way to create a list of squares
squares = [] # empty list
for i in range(5): # range(5) generates a sequence of numbers from 0 to 4
[Link](i * i) # append() method adds an element to the end of the
list
print(squares) # Output: [0, 1, 4, 9, 16]

# list comprehension - a more concise way to create lists


squares = [i * i for i in range(5)]
print(squares)
Lists, Tuples and Sets
# array lists in python - the array list is a collection of items that are
ordered and changeable.
# In python, array lists are called lists. Lists are written with square
brackets.
my_list = [1, 2, 3, 4, 5]
print(my_list) # print(my_list)
print(my_list[1]) # access the second element
print(my_list[-1]) # access the last element
# Array list methods
my_list.append(6) # add an element to the end of the list
my_list.remove(3) # remove an element from the list
my_list.insert(2, 3) # insert an element at a specific position
my_list.pop() # remove the last element from the list
my_list.sort(reverse=True) # sort the list in descending order
my_list.reverse() # reverse the order of the list
my_list.clear() # clear the list
Lists, Tuples and Sets
# # tuples in python - a tuple is a collection of items that are ordered and
unchangeable.
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple) # print(my_tuple)
print(my_tuple[1]) # access the second element
print(my_tuple[-1]) # access the last element
# my_tuple.append(6) # tuples are immutable, so this will raise an error
print(my_tuple)
del my_tuple # delete the entire tuple
# sets in python - a set is a collection of items that are unordered and
unindexed.
my_set = {1, 2, 3, 4, 5}
print(my_set) # print(my_set)
my_set.add(6) # add an element to the set
my_set.remove(3) # remove an element from the set
my_set.update([7, 8, 9]) # add multiple elements to the set
my_set.discard(9) # remove an element from the set only if it exists
Dictionary
# # dictionaries in python - a dictionary is a collection of items that are
unordered, changeable and indexed.
my_dict = {"name": "John", "age": 30, "city": "New York"}
print(my_dict)
print(my_dict["name"]) # access the value of the key "name"
print(my_dict.get("age")) # access the value of the key "age"
my_dict["country"] = "USA" # add a new key-value pair
my_dict["age"] = 31 # update the value of the key "age"
my_dict.pop("city") # remove the key-value pair with the key "city"
my_dict.update({"city": "Los Angeles"}) # update the value of the key "city"
my_dict.clear() # clear the dictionary
del my_dict # delete the entire dictionary
Functions
# Functions in python - a function is a block of code that performs a
specific task only when it is called.
def greeting():
return “Hello, how are you?"
print(greeting())
--------------------------------------------------------------------------
# Functions with parameters – a parameter is a variable that is used to pass
information into a function.
def greeting(name):
return f"Hello {name}" # function that returns a greeting message with
the given name
print(greeting("Ahmed")) # calling the function and printing the result
passed with the argument "Ahmed".
---------------------------------------------------------------------------
def power(a, b): return a**b
print(power(10, 2))
Modules
# modules in python - a module is a file that contains python code. A module
can define functions, classes and variables.

from datetime import date


print([Link]()) # prints the current date

------------------------------------------------------------------

from datetime import datetime


print([Link]()) # prints the current date and time
File I/O
# Reading and writing files in python - Python has built-in functions for
creating, reading, updating, and deleting files.

with open('[Link]', 'w') as file:


[Link]("Hello World")
--------------------------------------------------------------------

with open('[Link]', 'w') as file:


[Link]('print("Hello word")’)
--------------------------------------------------------------------

with open('[Link]', 'r') as file:


content = [Link]()
print(content)
Exception Handling
# Exceptions in python - an exception is an error that occurs during the
execution of a program.
try:
number = int(input("Enter a number: "))
print(f"You entered {number}")
except ValueError:
print("You didn't enter a valid number")
-------------------------------------------------------------------------
try:
age = int(input("Enter your age: ")) # asks the user to enter their age
if age > 0:
print(f"You are {age} years old.") # prints the age
else:
# prints an error message if the age is not a positive integer
print("Age can only be a positive integer.")
except ValueError:
print("OOPS! You didn't enter a valid number.")
Thank you!

You might also like