DFI Python Beginners Slides_111226
DFI Python Beginners Slides_111226
The `""""""` is a triple-quoted string in Python. It's a string literal that allows
you to create multiline strings. It's often used for docstrings (documentation
strings) to provide documentation for modules, classes, functions, or methods.
Input attribute
Another method of control is by declaring if your string is
either an uppercase (by adding .upper() after the last bracket of
our input), lowercase(by adding .lower() or if only you want to
capitalize the first letter of your string by using capitaze()
• .upper(): The attribute convert lower case input to
upper case.
e.g
name = str(input()).upper()
the code output
• .lower(): The attribute convert upper case input to
lower case.
e.g
name = str(input()).lower()
the code output
• .capitalize():The attribute convert the first character
of the input to upper case and retain the rest as
lower case character.
e.g
name = str(input()).capitalize()
the code output
• Other attributes are:
.split()
.strip()
.join()
Operators in Python (Logical
and Arithmetic operators)
• Operators in Python:
Operators in Python are indeed used for performing
specific types of logic. They are symbols or special keywords
that operate on operands (values or variables) to produce a
result.
Types of Operators:
Arithmetic Operators:
- Addition (+): Adds two operands.
- Subtraction (-): Subtracts the second operand from the first.
- Multiplication (*): Multiplies two operands.
- Division (/): Divides the first operand by the second.
- Exponentiation (**): Raises the first operand to the power of the second.
- Modulus (%): Returns the remainder of the division if it exist.
- Greater than sign(>)
- Less than sign(<)
- Greater than or equal to (>=)
- Less than or equal to (<=)
- Equivalent to (==)
- Not equal to (!=)
•
Logic Operators:
AND (and): Returns True if both condition are True.
OR (or): Returns True if at least one of the condition is
True.
None : Return True an object requested is not founf
In: Return True if object exist in set of data
Is
not
any
FLOW CONTROL
(IF STATEMENT AND LOOPS)
If
• If statement
• Nested if
Loops
• for loops
• While loops
• Nested loops
IF STATEMENT
. If Statement:
- The "if" statement is used to make decisions in code
based on conditions.
- It executes a block of code only if the condition is
true.
- Example:
It doesn’t just end there, we have the else and elif statements, which
is used to handle otherwise condition. For instance let’s say we have a
form that collect basic information like name age and gender, and we
want the program to address each user according to their gender we’ll
use the else and elif
e.g.
name = str(input(“What’s your name ”)).capitalize()
age = int(input(“What’s your age “))
gender = str(input(“What’s your gender “)).lower()
if gender == “male”:
print(“Hello sir”)
elif gender == “female”:
print(“Hello ma”)
else:
print(“Invalid gender”)
From the example in the previous slide, we can see that our
program flow will respond to our users genders. You can see that
We used the elif because we have to gender(i.e. gender to
satisfy)
And we used the else to handle condition that our user enters
an invalid gender.
With this you use if and else only if you have just One option
the else is mainly used to respond to non existing conditions
outside the given condition
But we use elif if we have more than one options like our
example
So if you have 5 condition you have 1 if 4 elifs and 1 else.
You can’t have more than 1 else in a control
LOOPS
Loops in Python
In programming, loops are used to execute a block of
code multiple times. They are essential for automating
repetitive tasks and iterating over collections of data.
for Loops
For Loop:
- A "for" loop is used to iterate over a sequence (like a
list, tuple, or string) or other iterable objects.
- It executes a block of code for each item in the
sequence.
- Example:
for in range(5):
print(i)
while Loops
. While Loop:
- A "while" loop repeats a block of code as long as the specified
condition is true.
- It's useful when you don't know in advance how many times
you need to iterate.
- Example:
count = 0
while count < 5:
print(count)
count += 1
while True
We use the while True to keep the whole program in a loop even if the
conditions have been satisfied
while True:
name = str(input(“What’s your name ”)).capitalize()
age = int(input(“What’s your age “))
gender = str(input(“What’s your gender “)).lower()
if gender == “male”:
print(“Hello sir”)
elif gender == “female”:
print(“Hello ma”)
else:
print(“Invalid gender”)
Also we use break to end loops(i.e. a block of loop in
python)
while True
We use the while True to keep the whole program
in a loop even if the conditions have been satisfied
while True:
name = str(input(“What’s your name
”)).capitalize()
age = int(input(“What’s your age “))
gender = str(input(“What’s your gender
“)).lower()
if gender == “male”:
print(“Hello sir”)
elif gender == “female”:
print(“Hello ma”)
else:
print(“Invalid gender”)
break
nested Loops
Nested Loop:
- A nested loop is a loop inside another loop.
- Used for iterating over items in multi-dimensional data
structures like lists of lists.
- Example:
for i in range(3):
for j in range(2):
print(i, j)
Which is also applicable to while loops
DATA STRUCTURES IN PYTHON
• List
• Dictionary
• Tuple
• Set
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in structures in Python used to store collections of data,
the other 3 are Dictionary, Tuple and Set, all with different qualities and usage.
Create a List:
print(thislist)
Attribute of a list
List Items
List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered
Changeable
Changeable
Since lists are indexed, lists can have items with the
same value:
Example
print(thislist)
List items can be of any data type:
Example
list2 = [1, 5, 7, 9, 3]
type()
print(type(mylist))
The list() Constructor
Example
print(thislist)
LIST CONSTRUCTOR
We have 11 list operators in python, which are:
Pop
Append
Clear
Count
Extended
Index
Insert
Remove
Reverse
Sort
copying
Dictionary
Python Dictionary is a powerful and versatile data
structure used to store Key value pairs, they are an
unordered, mutable and indexed collection. They are used
to represent mappings between unique keys and values.
Example of a Dictionary
my_dict = {"apple": 2, "banana": 3, "orange": 1}
print(my_dict[banana])
Adding and Modifying Entries
print(key, my_dict[key])
Dictionary Comprehensions
nested_dict = {
}
Tuple
What is a Tuple?
my_tuple = (1, 2, 3, 4, 5)
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
Tuple Operations
1. Concatenation:
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2
repeated_tuple = my_tuple * 3
1. count():
my_tuple = (1, 2, 2, 3, 2, 4)
print(my_tuple.count(2)) # Output: 3
2. index():
my_tuple = (1, 2, 3, 4, 5)
print(my_tuple.index(3)) # Output: 2
Tuple Packing and Unpacking
Packing:
my_tuple = 1, 2, 'hello'
a, b, c = my_tuple
print(a) # Output: 1
print(b) # Output: 2
my_set = {1, 2, 3, 4, 5}
unique_set = set(my_list)
print(unique_set)
print(3 in my_set)
print(6 in my_set)
my_set = {1, 2, 3}
my_set.add(4)
print(my_set)
Sets support various operations like union, intersection,
difference, and symmetric difference.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
print(set1 | set2)
print(set1 & set2)
print(set1 - set2)
print(set1 ^ set2)
print(set1.intersection(set2))
print(set1.difference(set2))
print(set1.symmetric_difference(set2))
set1.clear()
print(set1)
print(x(5)) # Output: 15
2. **Multiple Arguments**:
x = lambda a, b: a * b
return lambda a: a * n
mydoubler = myfunc(2)
print(mydoubler(11)) # Output: 22
mytripler = myfunc(3)
print(mytripler(11)) # Output: 33
4. When to Use Lambda Functions:
Opening a File:
The open() function takes two parameters: the filename and
the mode.
Modes include:
"r" (Read): Opens a file for reading. If the file doesn’t exist,
an error occurs.
"a" (Append): Opens a file for appending data. Creates the
file if it doesn’t exist.
"w" (Write): Opens a file for writing. Creates the file if it
doesn’t exist.
"x" (Create): Creates a new file. Returns an error if the file
already exists.
You can also specify whether the file should be handled in text
mode ("t") or binary mode ("b").
Example:
# Open a file for reading
f = open("demofile.txt")
(Because "r" for read and "t" for text are the default
values) # Make sure the file exists, or you'll get an error
Reading from a File:
Use methods like read(), readline(), or readlines() to
read content from the file.
Writing to a File:
Use the write() method to add content to the file.
Remember to close the file using close() when you’re
done.
Closing the File:
Always close the file after reading or writing to free up
system resources.
Happy coding! 🐍📄
Python with Database
Python to a database is a crucial skill for many applications, as it
allows you to interact with data stored in databases efficiently.
Below is a comprehensive guide on how to connect Python to a
database:
Step 1: Choose a Database Management System (DBMS). First, you
need to choose which database you want to connect to. Common
choices include:
For SQLite:
import sqlite3
connection = sqlite3.connect('example.db')
# Create a cursor object to execute SQL queries
cursor = connection.cursor()
connection.close()
Perform Database Operations
rows = cursor.fetchall()
print(row)
# Insert data
# Commit changes
connection.commit()
Get Specific data
So far we’ve learnt how to fetch all the data from our database using
cursor.fetchall(), Now we want to learn how get specific data from how our
database.Take for instance we want to get 1 out of 10 bottle of pepsi, we need a
way of calling that specific data, here is how we go about it:
In SQL we use;
SELECT * FROM users
WHERE id = ?
our question mark is represent by the product id
But in python we use:
The code above take in the UPDATE key word followed by table name, The we set
the declare that we are expecting some value like name, and email using
SET name = ?, email = ? WHERE id = ?
All within the first argument then the next argument are the values to update the
existing data.
After this, we need to commit the changes using connection.commit()
Here we passed two arguments, the first is the DELETE FROM key word followed
by the table name and the desired id value, then the next argument is the the data
id
Step 5: Close the Connection
connection.close()
•1. Widgets: Widgets are the basic building blocks of a Tkinter application. They include
buttons, labels, entry fields, etc.
•root = tk.Tk()
root.title("My Tkinter App")
# Add widget
label.pack()
# Start the main event loop
root.mainloop()
1. Label: Used to display text or images.
def button_click():
print("Button clicked!")
button.pack()
1. Custom Widgets: You can create custom widgets by subclassing
existing ones.
These are just some of the key points covered in PEP 8. Adhering
to PEP 8 guidelines helps to produce Python code that is
consistent, readable, and maintainable, which is essential for
collaborative projects and long-term code maintenance.
Build a Tip calculator using functions and two file,
your first file is the main.py, the second file is your logic file (which you
can give it any name
what you program should be able to do
1. calculate tip
2. determine the payment method
3. determine if the user will collect change if payment method is cash
4. determine if it’s a joint a single payment