0% found this document useful (0 votes)
9 views

DFI Python Beginners Slides_111226

The document outlines a beginner's Python course covering essential topics such as setup, coding basics, data types, control flow, and data structures. It highlights Python's versatility in web development, data science, and automation, and provides practical examples for coding concepts. The course also emphasizes the importance of following best practices like PEP 8 and includes hands-on exercises for learners.

Uploaded by

Somebody's Bae
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DFI Python Beginners Slides_111226

The document outlines a beginner's Python course covering essential topics such as setup, coding basics, data types, control flow, and data structures. It highlights Python's versatility in web development, data science, and automation, and provides practical examples for coding concepts. The course also emphasizes the importance of following best practices like PEP 8 and includes hands-on exercises for learners.

Uploaded by

Somebody's Bae
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 122

Python Beginners

Digital Fortress Institute


Course Outline
• Introduction to Python
• What can Python do
• Setup and Installation
• Take Note
• Coding proper (print, comment)
• Variable
• Input
• Data Types (Integer, String, Boolean, Float)
• Operators in Python(Logical and Arithmetic operator)
• Flow Control (If statement, try and except and Loops)
• Data structure in Python
• Functions
• Lambda
• File Handling
• Python with database (Sqlite3)
• Tkinter
• PEP 8
Introduction to Python
• Python is a multipurpose high level programming language,
developed by Guido Van Rossum in 1991, with aim of
providing a simple, readable and and performance base
programming language.
• Python support multiple programming paradigms including
procedural, object oriented, and functional programming
style.
• Python is widely used in many field mostly in the
STEM( Science Technology, Engineering and Mathematic)
organizations. Companies like MANG (Meta, Amazon, Netflix
and Google) and other tech organizations uses python as part
of it’s tech stack.
What can Python do?
• Python is widely used in web development with the
availability of packages like Django Flask and FastAPI etc.
which also come with a very large and active community.
• Python is also used in Data Science and Machine Learning
• Python can also be use in web scraping, web automation and
Scripting Mobile and Desktop App development,
Setup and Installation😊
• To run Python on your local machine(PC i.e Personal
computer which can be laptop or even Desktop), you need
to install the python IDE from the python official website.
Download 🔗 https://www.python.org/
• For the course, we’ll be using Visual Studio Code (Vscode)
Download 🔗
https://code.visualstudio.com/download
• Also we’ll be making use of Git Bash as our terminal where
we would see the outcome of our code
Download 🔗 https://git-scm.com/downloads
Take Note of the following
After you’ve downloaded python install it, but after
tapping on the .exe file you’ll see a pop-up, tick the “add
python to exe…..”
In the course bear in mind that python is dynamically
typed and reads from top to bottom and left to right.
Lastly Open your Vscode, at the top left you’ll see the
extension as displayed below tap on it
After that download the following by tapping the search
like bar at the top and search and download the following
Pylance, Python, and Python debugger
Coding Proper
• Now that we have Python IDE, Vscode (i.e our code editor) and
GitBash as our terminal we can now start coding
• The first Thing we’ll be doing is the log data on our terminal
• Before that create a folder and open the folder in your vscode,
then create a .py file in the folder after the vscode is opened
• PRINT statement
In python, "print" is a syntax or command used to display messages
or output to the user via the terminal.
- It allows you to show information on the screen or console.
- Example
print("Hello, World!")
COMMENTS
In Python, the syntax `#` is used to indicate a comment. Comments are lines
in the code that are ignored by the Python interpreter and are used for
documentation or to annotate the code for readability.

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.

When `""""""` is used as a comment, it typically indicates a block of


commented-out code or a placeholder for future code. It doesn't have any
functional impact on the code since it's treated as a comment and ignored by
the interpreter. However, it can serve as a visual separator or marker within the
code to indicate the start or end of a section or to temporarily disable a block
of code during debugging or development.
Variable
• A variable is a placeholder for storing data in a program.
• - Variables have names and values
- Example:
age = 25
name = "John"
A variable can also be set as a value for a variable for
example
name = input()
What this means is that our variable name “name” has a
value of an input, which we can print back on the terminal
name = input()
print(name)
output: So let’s say after you run the code the typed in
“Adeswa”
And you click on enter it still console Adesewa
• Do you know that you can print that variable by:
age = 25
print(age)
Now you’ll observe that we didn’t have to add “” this
time, why because it’s a variable is not a data type.
Data Types in Python
We have four standard data types in python which are:
• Strings - identified by text in between “ ” e.g “Hello
world”
• Integers – They are numbers in python e.g 0 – 9, they
do not require “”.
• Floats – These are decimal number e.g 18.99, 45.99 etc
• Booleans – These are True or False statement in python
written as True and False no inverted comma
needed
Input
• Now that we’ve learnt how to log data to our terminal
(i.e the print statement), we also need to learn how to
collect or accept input from the terminal.
• By default every input from our terminal is a string
except if declared
• To collect input from the terminal we’ll use the syntax
called “input” followed by parenthesis “()”
E.g input()
When we run this we’ll see that our terminal allows us to
type in via the terminal
We can Take full control of our input by declaring what of data and
how the data should be collected.
String input:
An input can be assigned to accept only string and nothing more
by adding str() and the input() in between the str parenthesis e.g
username = str(input())
Integer input:
An input can be assigned to accept only integers and nothing
more by adding int() and the input() in between the int parenthesis
e.g
age = int(input())
Float input:
An input can be assigned to accept only floats and nothing more
by adding float() and the input() in between the int parenthesis e.g
price = float(input())
Boolean input:
An input can be assigned to accept only Boolean and nothing
more by adding bool() and the input() in between the int
parenthesis e.g
confirm = bool(input())

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.

Lists are created using square brackets:

Create a List:

thislist = ["apple", True, 12, 2422.433]

print(thislist)
Attribute of a list
List Items

List items are ordered, changeable, and allow duplicate


values.

List items are indexed, the first item has index [0], the
second item has index [1] etc.
Ordered

When we say that lists are ordered, it means that the


items have a defined order, and that order will not
change.

If you add new items to a list, the new items will be


placed at the end of the list.

Changeable

The list is changeable, meaning that we can change, add,


and remove items in a list after it has been created.
Ordered

When we say that lists are ordered, it means that the


items have a defined order, and that order will not
change.

If you add new items to a list, the new items will be


placed at the end of the list.

Changeable

The list is changeable, meaning that we can change, add,


and remove items in a list after it has been created.
Allow Duplicates

Since lists are indexed, lists can have items with the
same value:

Example

thislist = ["apple", "banana", "cherry", "apple", "cherry"]

print(thislist)
List items can be of any data type:

Example

list1 = ["apple", "banana", "cherry"]

list2 = [1, 5, 7, 9, 3]

list3 = [True, False, False]


Note that “()” is a constructor.

type()

What is the data type of a list?

mylist = ["apple", "banana", "cherry"]

print(type(mylist))
The list() Constructor

It is also possible to use the list() constructor when creating a new


list.

Example

Using the list() constructor to make a List:

thislist = list(("apple", "banana", "cherry")) # note the double


round-brackets

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}

Note that in list named my_dict “apple”, “banana”, and


“orange” is the key while 2, 3 and 1 are thor value each
Accessing Values in a Dictionary:

We can access the values of of a associated with a


specific key using square bracket [] e.g

print(my_dict[banana])
Adding and Modifying Entries

To add a new key-value pair or modify an existing one,


simply assign a value to the key:

my_dict["grape"] = 4 # Adding a new entry

my_dict["banana"] = 5 # Modifying an existing entry


Removing Entries

You can remove entries from a dictionary using the `del`


keyword or the `pop()` method:

del my_dict["apple"] # Removes the entry with key


"apple"

my_dict.pop("orange") # Removes the entry with key


"orange"
Removing Entries

You can remove entries from a dictionary using the `del`


keyword or the `pop()` method:

del my_dict["apple"] # Removes the entry with key


"apple"

my_dict.pop("orange") # Removes the entry with key


"orange"
Dictionary Methods

Python dictionaries offer various built-in methods for


performing common operations in dictionary. Some
useful methods include:

- `keys()`: Returns a view object that displays a list of all


the keys in the dictionary.

- `values()`: Returns a view object that displays a list of


all the values in the dictionary.
- `items()`: Returns a view object that displays a list of tuples
containing key-value pairs.

- `get()`: Returns the value associated with a specified key. If


the key does not exist, it returns a default value (if provided)
or `None`.

- `update()`: Updates the dictionary with the key-value pairs


from another dictionary or an iterable of key-value pairs.

- `clear()`: Removes all the key-value pairs from the


dictionary.
You can iterate through a dictionary using loops. For
example, to iterate through keys:

for key in my_dict:

print(key, my_dict[key])

To iterate through key-value pairs:

for key, value in my_dict.items():


print(key, value)

Dictionary Comprehensions

Similar to list comprehensions, you can also create


dictionaries using dictionary comprehensions. For
example:

squares = {x: x*x for x in range(1, 6)}


Nested Dictionaries:

nested_dict = {

"person1": {"name": "John", "age": 30},

"person2": {"name": "Alice", "age": 25}

}
Tuple

What is a Tuple?

A tuple in Python is a data structure that is used to store an


ordered sequence of elements. It is similar to a list, but with the
key difference being that tuples are immutable, meaning they
cannot be modified once created. Tuples are created by enclosing
comma-separated values within parentheses `()`.
Creating Tuples

Here's how you create a tuple in Python:

my_tuple = (1, 2, 3, 4, 5)

Tuples can also contain elements of different data types:

mixed_tuple = ('apple', 3.14, True, 42)


Accessing Elements

You can access elements of a tuple using indexing.


Indexing in Python starts from 0.

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple[0]) # Output: 1
print(my_tuple[2]) # Output: 3
Tuple Operations

1. Concatenation:

You can concatenate two tuples using the `+` operator.

tuple1 = (1, 2, 3)

tuple2 = (4, 5, 6)
concatenated_tuple = tuple1 + tuple2

print(concatenated_tuple) # Output: (1, 2, 3, 4, 5, 6)


2. Multiplication:

You can repeat a tuple using the `*` operator.

my_tuple = ('a', 'b')

repeated_tuple = my_tuple * 3

print(repeated_tuple) # Output: ('a', 'b', 'a', 'b', 'a', 'b')


Tuple Methods

1. count():

Returns the number of occurrences of a specified value in the


tuple.

my_tuple = (1, 2, 2, 3, 2, 4)

print(my_tuple.count(2)) # Output: 3
2. index():

Returns the index of the first occurrence of a specified


value.

my_tuple = (1, 2, 3, 4, 5)

print(my_tuple.index(3)) # Output: 2
Tuple Packing and Unpacking

Packing:

Packing multiple values into a tuple.

my_tuple = 1, 2, 'hello'

print(my_tuple) # Output: (1, 2, 'hello')


Unpacking:
Assigning individual values of a tuple to variables.

my_tuple = (1, 2, 'hello')

a, b, c = my_tuple

print(a) # Output: 1
print(b) # Output: 2

print(c) # Output: 'hello'

When to Use Tuples

Use tuples when you have a collection of items that


should not be changed, such as days of the week,
coordinates, or database records
Sets
A set in Python is an unordered collection of unique elements. It
is similar to the mathematical concept of a set. Sets are
mutable, meaning you can add or remove elements from them,
but they cannot contain duplicate elements. You can create a
set in Python by enclosing comma-separated values within curly
braces `{}`.

my_set = {1, 2, 3, 4, 5}

If you have a list and want to convert it to a set to remove


duplicates, you can use the `set()` function.
my_list = [1, 2, 2, 3, 4, 4, 5]

unique_set = set(my_list)

print(unique_set)

Since sets are unordered collections, you cannot access


elements by index. You can, however, check for
membership using the `in` keyword.
my_set = {1, 2, 3, 4, 5}

print(3 in my_set)

print(6 in my_set)

You can add elements to a set using the `add()` method.

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)

Sets have several useful methods such as `union()`,


`intersection()`, `difference()`, `symmetric_difference()`,
and `clear()`.
print(set1.union(set2))

print(set1.intersection(set2))

print(set1.difference(set2))

print(set1.symmetric_difference(set2))

set1.clear()
print(set1)

Sets are a powerful tool in Python for working with


collections of unique elements. They offer efficient
methods for set operations like union, intersection, and
difference. Understanding sets is essential for any Python
programmer.
Function
Function are block of code that gives room for re-usebility,
modularity and cleaner code. In python we use function to
declare lines of code that we want to make use of.
In python we declare function by the def followed by the
name(i.e the desired name of your function) ()
parenthesis and column.
E.g. def greetings():
Then whatever comes under this line must be indented.
Also it is also important that we close our function by
using the return statement
E.g.
def greetings():
word = “Hello Boss”
return word
The above is a proper illustration of a function, aside
from just greetings we can perform several logic within
the function block and return the output.
The now call a function we move outside the function and
type the function name followed by the parenthesis
E.g.
def greetings():
word = “Hello Boss”
return word
greetings()
We can also put a function within the print synatax
print(greetings())
In python function we can set parameters in a function,
which makes our function dynamic and flexible. For
example
E.g.
def greetings(a):
word = f“Hello {a} ”
return word
greetings(“Badmus”)
The function above has been fixed with one parameter
defined as a to take one argument which we declared as
“Badmus”.
E.g.
def add(a, b):
c=a+b
return c
add(2, 4)
The output of this code is 6 because the function
parameters adds the two arguments and return the
output
Lambda
In Python, a lambda function is a compact and
anonymous function that can take any number of
arguments but can only have one expression. It's often
used for short, simple tasks where defining a full function
is unnecessary. Let me illustrate how to create and use
lambda functions:
1. Basic Syntax:

- A lambda function is defined using the keyword


`lambda`, followed by the arguments and the expression.

- The expression is executed when the lambda function


is called, and the result is returned.
x = lambda a: a + 10

print(x(5)) # Output: 15

2. **Multiple Arguments**:

- Lambda functions can take multiple arguments.


- For instance, multiplying `a` with `b`:

x = lambda a, b: a * b

print(x(5, 6)) # Output: 30


3. Use Cases:

- Lambda functions are particularly useful when used as


anonymous functions inside other functions.

- Suppose you have a function that takes an argument


`n` and multiplies it with an unknown number:
def myfunc(n):

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:

- Use lambda functions when you need an anonymous


function for a short period of time, especially within other
functions.

Remember, lambda functions are concise and handy for


specific scenarios
File Handling
Certainly! Let’s delve into the world of file handling in Python. 📂

File handling is a crucial aspect of any programming language,


allowing you to create, read, update, and delete files. In Python,
the primary function for working with files is the open() function.
Let’s explore the basics:

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")

Equivalent to: f = open("demofile.txt", "rt")

(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:

1. SQLite: A lightweight, file-based database often used for smaller


applications or prototyping.

2. MySQL / MariaDB: Popular open-source relational database


3. PostgreSQL: Another powerful open-source relational database
management system.

4. MongoDB: A NoSQL database, suitable for document-oriented


data storage.

For this class we’ll majorly focus on Sqlite3 as it comes as a default


package when you install python
Connect to the Database

For SQLite:

import sqlite3

# Connect to SQLite database (create if it doesn't exist)

connection = sqlite3.connect('example.db')
# Create a cursor object to execute SQL queries

cursor = connection.cursor()

# Perform database operations

# Don't forget to close the connection when done

connection.close()
Perform Database Operations

You can execute SQL queries or MongoDB operations using the


cursor object. For example:

# Execute a SQL query

cursor.execute("SELECT * FROM tablename")


# Fetch results (for SELECT queries)

rows = cursor.fetchall()

for row in rows:

print(row)
# Insert data

cursor.execute("INSERT INTO tablename (column1,


column2) VALUES (%s, %s)", ("value1", "value2"))

# 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:

cursor.execute(“SELECT * FROM users WHERE id = ?”, (1,))


followed by cursor.fetchone() which is used to conclude the statement above
NB that the second argument “(1,)” is the pepsi id which is automatically
generated using the AUTOGENERATE key word in the table create
Updating the data in our database
We can only update an existing data. To update and existing data, we use:
cursor.execute(UPDATE users, SET name = ?, email = ? WHERE id = ?, (JohnDoe, [email protected]
))
connection.commit()

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()

This will update the data


Delete Data
Deleting data is a crucial part of database operation. So in python we use;
cursor.exectute(“DELETE FROM users WHERE id = ?, (1,)”)
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

Always remember to close the database connection when you're


done with it

connection.close()

By following these steps, you'll be able to connect Python to your


chosen database and perform various operations on it. Remember
to handle errors appropriately and ensure proper data handling
practices to maintain data integrity and security.
Python GUI (Tkinter)

Python GUI stands for Python Graphical User Interface.


Which allows us to build user friendly application with
appealing interface and design.
In the course we’ll be using Tkinter as a case study as it is
user and beginner friendly and provides rapid development
Tkinter is pronounced as tea-kay-inter and serves as the Python
interface to Tk, the GUI toolkit for Tcl/Tk.

Tcl (pronounced as tickle) is a scripting language frequently used


in testing, prototyping, and GUI development. Tk, on the other
hand, is an open-source, cross-platform widget toolkit utilized by
various programming languages to construct GUI programs.

Python implements Tkinter as a module, serving as a wrapper for C


extensions that utilize Tcl/Tk libraries.

Tkinter allows you to develop desktop applications, making it a


valuable tool for GUI programming in Python.
Certainly! Tkinter is a Python library used for creating GUI
(Graphical User Interface) applications. It's widely used because
it's simple, easy to learn, and comes pre-installed with Python.
Below is a comprehensive guide that will take you from a novice to
a proficient user of Tkinter. Tkinter is the standard GUI library for
Python. It provides various tools and widgets to create GUI
applications. Tkinter is based on the Tk GUI toolkit which was
developed for the Tcl programming language. Tkinter provides a
way to create windows, labels, buttons, entry fields, etc., and
arrange them in an organized manner.

To use Tkinter, you don't need to install any separate package. It


comes bundled with Python. You just need to import it into your
Python script:
•import tkinter as tk

•1. Widgets: Widgets are the basic building blocks of a Tkinter application. They include
buttons, labels, entry fields, etc.

•2. Geometry Managers: Tkinter provides different geometry managers to arrange


widgets within the application window. Common ones include `pack()`, `grid()`, and
`place()`.

•# Create the main application window

•root = tk.Tk()
root.title("My Tkinter App")

# Add widget

label = tk.Label(root, text="Hello, Tkinter!")

label.pack()
# Start the main event loop

root.mainloop()
1. Label: Used to display text or images.

2. Button: Used to perform actions when clicked.

3. Entry: Used to get input from the user.

4. Text: Multi-line text box for user input.

5. Frame: Container for other widgets.


6. Canvas: For drawing graphics.

7. Checkbutton, Radiobutton: For selecting options

8. Menu, Menubutton: For creating menus.


1. pack(): Packs widgets in a block.

2. grid(): Organizes widgets in a table-like structure.

3. place(): Places widgets using absolute positioning.

Event Handling: Tkinter applications are event-driven. You can bind


functions to events such as button clicks, mouse movements, etc.

def button_click():
print("Button clicked!")

button = tk.Button(root, text="Click me",


command=button_click)

button.pack()
1. Custom Widgets: You can create custom widgets by subclassing
existing ones.

2. Styling: Tkinter supports basic styling options like colors, fonts,


etc.

3. Dialogs: Tkinter provides built-in dialogs for common tasks like


file selection, message display, etc.

4. Threading: Use threading to prevent the GUI from freezing


during long-running tasks.
5. Integration with Other Libraries: Tkinter can be
integrated with other Python libraries like Matplotlib for
data visualization.
PEP 8
PEP 8 is the official style guide for Python code, and it offers guidelines
on how to format Python code for better readability and consistency.
Here are some key points from PEP 8:
1. Indentation: Use 4 spaces per indentation level. This is the preferred
method for indentation in Python, ensuring consistency across different
editors and platforms.
2. Line Length: Keep lines to a maximum of 79 characters. This helps
with readability, especially when viewing code on smaller screens or in
side-by-side diff views.
3. Imports: Imports should usually be on separate lines and should be
grouped in the following order: standard library imports, related third-
party imports, and local application/library-specific imports. Additionally,
individual imports should be on separate lines to avoid confusion.
4. Whitespace: Use whitespace to improve readability. For example,
surround operators with spaces, but don't use spaces around function
5. Naming Conventions: Follow consistent naming conventions. For
example, use `lowercase_with_underscores` for variable names,
`CapitalizedWords` for class names, and
`CAPITALIZED_WITH_UNDERSCORES` for constants.

6. Comments: Write comments to explain code when necessary, but


avoid unnecessary comments or redundant explanations.

7. Function and Method Naming: Function names should be lowercase,


with words separated by underscores as necessary to improve
readability. Method names should be the same as function names, but
with `self` as the first parameter.

8. Whitespace in Expressions and Statements: Use whitespace around


9. Documentation Strings: Use docstrings to document modules,
classes, functions, and methods. Follow the conventions outlined in
PEP 257 for writing docstrings.

10. Avoid Trailing Whitespace: Remove trailing whitespace at the


end of lines, as it can cause issues with version control systems
and diff tools.

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

You might also like