Introduction To Programming With Python
Introduction To Programming With Python
Outline
1. Print Function
2. Variable, Data types
○ Naming rules
○ Data types
○ Operators in Python
■ Arithmetic Operators
■ Comparison Operators
■ Logical operators
■ Assignment Operators
■ Identity Operators
■ Membership Operators
○ Comments
3. Conditionals
○ Control Flow, elif, and else
○ Or
○ And
4. Loops
○ While Loops
○ For Loops
5. Data Structure
○ List
■ List Items
■ Ordered
■ Changeable
■ Allow Duplicates
■ type()
■ The list() Constructor
■ List Operators in Python
○ Tuples
○ Dictionary
■ Accessing Values in a Dictionary
■ Adding and Modifying Entries
■ Removing Entries
■ Dictionary Methods
■ Iterating Through a Dictionary
■ Dictionary Comprehensions
■ Nested Dictionaries
○ Set
6. Functions
○ What are functions?
○ Argument
○ Returning Values
○ Lambda function
■ Basic Syntax
■ Multiple Arguments
■ Use Cases
■ When to Use Lambda Functions
7. File(I/O)
○ Open
○ With
8. Database
○ Choose a Database Management System
○ Install Necessary Libraries
○ Connet to the Database
■ SQLite
■ MySQL/MariaDB
■ PostgreSQL
■ MongoDB
○ Perform Database Operations
○ Close the Connection
9. Tkinter
○ Event Handling
Print Function
In Python, the print statement is used to display data to the standard output data to the user via
the terminal.
A variable holds a value. You can change the value of a variable at any point.
Naming rules
● Variables can only contain letters, numbers, and underscores. Variable names can start
with a letter or an underscore, but can not start with a number.
● Spaces are not allowed in variable names, so we use underscores instead of spaces.
For example, use student_name instead of "student name".
● You cannot use Python keywords as variable names.
● Variable names should be descriptive, without being too long. For example mc_wheels is
better than just "wheels", and number_of_wheels_on_a_motorycle.
● Be careful about using the lowercase letter l and the uppercase letter O in places where
they could be confused with the numbers 1 and 0.
Data types
Python has several built-in data types that are commonly used to store and manipulate data
Operators in Python
Arithmetic Operators
- Addition (+): Adds two operands.
- Subtraction (-): Subtracts right operand from the left operand.
- Multiplication (*): Multiplies two operands.
- Division (/): Divides right operand by left operand.
- Modulus (%): Returns the remainder of the division.
- Exponentiation (**): Raises left operand to the power of right operand.
- Floor Division (//): Division that results into whole number adjusted to the left in the number
line.
Comparison Operators
- Equal to (==): Checks if the values of two operands are equal.
- Not equal to (!=): Checks if the values of two operands are not equal.
- Greater than (>): Checks if the value of left operand is greater than the value of right
operand.
- Less than (<): Checks if the value of left operand is less than the value of right operand.
- Greater than or equal to (>=): Checks if the value of left operand is greater than or equal to
the value of right operand.
- Less than or equal to (<=): Checks if the value of left operand is less than or equal to the
value of right operand.
Logical Operators
- AND (and): Returns True if both operands are true.
- OR (or): Returns True if any one of the operands is true.
- NOT (not): Returns True if the operand is false (complements the opera
Assignment Operators
- Assignment (=): Assigns the value of the right operand to the left operand.
- Addition Assignment (+=): Adds right operand to the left operand and assigns the result to
left operand.
- Subtraction Assignment (-=): Subtracts right operand from the left operand and assigns the
result to left operand.
- Multiplication Assignment (*=): Multiplies right operand with the left operand and assigns the
result to left operand.
- Division Assignment (/=): Divides left operand by right operand and assigns the result to left
operand.
- Modulus Assignment (%=): Takes modulus using two operands and assigns the result to left
operand.
- Exponentiation Assignment (**=): Performs exponential (power) calculation on operands and
assigns the result to the left operand.
- Floor Division Assignment (//=): Performs floor division on operators and assigns value to the
left operand.
Identity Operators
- is: Returns True if the operands are identical (refer to the same object).
- is not: Returns True if the operands are not identical (do not refer to the same object).
Membership Operators
- in: Returns True if a sequence with the specified value is present in the object.
- not in: Returns True if a sequence with the specified value is not present in the object.
Comments
As you begin to write more complicated code, you will have to spend more time thinking about
how to code solutions to the problems you want to solve. Once you come up with an idea, you
will spend a fair amount of time troubleshooting your code, and revising your overall approach.
Comments allow you to write in English, within your program. In Python, any line that starts with
a pound (#) symbol is ignored by the Python interpreter.
Conditionals
Conditionals are used to execute different blocks of code based on whether a certain condition
is evaluated as true or false. The most common conditional statements in Python are if, elif
(short for "else if"), and else. They allow you, the programmer, to allow your program to make
decisions: As if your program has the choice between taking the left-hand road or the right-hand
road based upon certain conditions
Notice how you are providing a series of if statements. First, the first if statement is evaluated.
Then, the second if statement runs its evaluation. Finally, the last if statement runs its
evaluation. This flow of decisions is called “control flow.”
This program can be improved by not asking three consecutive questions. After all, not all three
questions can have an outcome of true! Revise your program as follows:
Notice how the use of elif allows the program to make fewer decisions. First, the if statement is
evaluated. If this statement is found to be true, all the elif statements will not be run at all.
However, if the if statement is evaluated and found to be false, the first elif will be evaluated. If
this is true, it will not run the final evaluation.
Or
or allows your program to decide between one or more alternatives. For example, we could
further edit our program as follows:
Notice that the result of our program is the same, but the complexity is decreased. The
efficiency of our code is increased.
At this point, our code is pretty great. However, could the design be further improved? We could
further edit our code as follows:
Notice how we removed the or entirely and simply asked, “Is x not equal to y?” We ask one and
only one question. Very efficient!
And
Similar to or, and can be used within conditional statements.
Execute in the terminal window code grade.py. Start your new program as follows:
Notice that by executing python grade.py, you will be able to input a score and get a grade.
However, notice how there is potential for bugs.
Typically, we do not want to ever trust our users to input the correct information. We could
improve our code as follows:
Notice how Python allows you to chain together the operators and conditions in a way quite
uncommon to other programming languages.
Loops
Essentially, loops are a way to do something over and over again.
Running this code, you’ll notice that the program meows three times.
In developing as a programmer, you want to consider how one could improve areas of one’s
code where one types the same thing over and over again. Imagine where one might want to
“meow” 500 times. Would it be logical to type that same expression of print("meow") over and
over again?
Loops enable you to create a block of code that executes over and over again.
While Loops
A while loop tests an initial condition. If that condition is true, the loop starts executing. Every
time the loop finishes, the condition is reevaluated. As long as the condition remains true, the
loop keeps executing. As soon as the condition becomes false, the loop stops executing.
Notice how even though this code will execute print("meow") multiple times, it will never stop! It
will loop forever. while loops work by repeatedly asking if the condition of the loop has been
fulfilled. In this case, the compiler is asking, “does i not equal zero?” When you get stuck in a
loop that executes forever, you can press control-c on your keyboard to break out of the loop.
To fix this loop that lasts forever, we can edit our code as follows
Notice that now our code executes properly, reducing i by 1 for each “iteration” through the loop.
The term iteration has special significance within coding. By iteration, we mean one cycle
through the loop. The first iteration is the “0th” iteration through the loop. The second is the “1st”
iteration. In programming, we count starting with 0, then 1, then 2.
Notice how changing the operator to i < 3 allows our code to function as intended. We begin by
counting with 0 and it iterates through our loop three times, producing three meows. Also, notice
how i += 1 is the same as saying i = i + 1
For Loops
To best understand a for loop, it’s best to begin by talking about a new variable type called a list
in Python. As in other areas of our lives, we can have a grocery list, a to-do list, etc.
A for loop iterates through a list of items. For example modify your code as follows:
Notice how clean this code is compared to your previous while loop code. In this code, i begins
with 0, meows, i is assigned 1, meows, and, finally, i is assigned 2, meows, and then ends.
While this code accomplishes what we want, there are some possibilities for improving our code
for extreme cases. At first glance, our code looks great. However, what if you wanted to iterate
up to a million? It’s best to create code that can work with such extreme cases. Accordingly, we
can improve our code as follows:
Notice how range(3) provides back three values (0, 1, and 2) automatically. This code will
execute and produce the intended effect, meowing three times.
Our code can be further improved. Notice how we never use i explicitly in our code. That is,
while Python needs the i as a place to store the number of the iteration of the loop, we never
use it for any other purpose. In Python, if such a variable does not have any other significance
in our code, we can simply represent this variable as a single underscore _. Therefore, you can
modify your code as follows:
Notice how changing the i to _ has zero impact on the functioning of our program.
Data Structure
The basic Python data structures in Python include list, set, tuples, and dictionary. Each of the
data structures is unique in its own way. Data structures are “containers” that organize and
group data according to type.
List
A list is a collection of items, that is stored in a variable. The items should be related in some
way, but there are no restrictions on what can be stored in a list. Here is a simple example of a
list, and how we can quickly access each item in the list.
Lists are one of 4 built-in structures in Python used to store collections of data, the other 3 are
Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
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.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
type()
What is the data type of a list?
1. pop():
● pop() removes and returns the element at the specified index (by default, the last
element).
● Syntax: list_name.pop(index).
● If no index is specified, pop() removes and returns the last element of the list.
2. append():
● append() adds an element to the end of the list.
● Syntax: list_name.append(element).
3. clear():
● clear() removes all elements from the list, leaving it empty.
● Syntax: list_name.clear().
4. count():
● count() returns the number of occurrences of a specified element in the list.
● Syntax: list_name.count(element).
5. extend():
● extend() extends the list by appending elements from an iterable (usually another list).
● Syntax: list_name.extend(iterable).
6. index():
● index() returns the index of the first occurrence of a specified element in the list.
● Syntax: list_name.index(element).
7. insert():
● insert() inserts an element at the specified index.
● Syntax: list_name.insert(index, element).
8. remove():
● remove() removes the first occurrence of a specified element from the list.
● Syntax: list_name.remove(element).
9. reverse():
● reverse() reverses the order of elements in the list.
● Syntax: list_name.reverse().
10. sort():
● sort() sorts the elements of a list in ascending order (by default) or according to a
specified custom sorting criteria.
● Syntax:list_name.sort(key=None, reverse=False).
● key is an optional parameter specifying a function to be called on each element for
sorting.
● reverse is an optional boolean parameter. If set toTrue, the list will be sorted in
descending order.
● or
11. copy():
● copy() returns a shallow copy of the list. It creates a new list with the same elements as
the original list.
● Syntax:new_list = list_name.copy().
Tuples
Tuples are basically lists that can never be changed. Lists are quite dynamic; they can grow as
you append and insert items, and they can shrink as you remove items. You can modify any
element you want to in a list. Sometimes we like this behavior, but other times we may want to
ensure that no user or no part of a program can change a list. That's what tuples are for.
Technically, lists are mutable objects and tuples are immutable objects. Mutable objects can
change (think of mutations), and immutable objects can not change.
Notice that we can promise that we will always keep these lists in order. The individual at the
first position of students is associated with the house at the first position of the houses list, and
so on. However, this can become quite cumbersome as our lists grow!
Note that in dict named students “Hermoine”, “Harry”, “Ron”, and “Draco” is the key while
“Gryffindor”, and “Slytherin” are their value.
Dictionary Methods
Python dictionaries offer various built-in methods for performing common operations in a
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.
Nested Dictionaries
Dictionaries can also contain other dictionaries as values, creating a nested structure.
Conclusion
Python dictionaries are essential data structures that offer a convenient way to store and
manipulate key-value pairs. Understanding how to create, access, modify, and iterate through
dictionaries is crucial for any Python programmer. With their versatility and efficiency,
dictionaries play a significant role in various programming tasks and applications.
Set
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 `{}`.
If you have a list and want to convert it to a set to remove duplicates, you can use the `set()`
function.
Since sets are unordered collections, you cannot access elements by index. You can, however,
check for membership using the in keyword.
You can remove elements from a set using the remove() method. If the element is not present,
a KeyError will be raised.
Sets support various operations like union, intersection, difference, and symmetric
difference.
Sets have several useful methods such as union(), intersection(), difference(),
symmetric_difference(), and clear().
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.
This guide should provide beginners with a solid understanding of sets in Python and how to
use them effectively in their programs.
Functions
One of the core principles of any programming language is, "Don't Repeat Yourself". If you have
an action that should occur many times, you can define that action once and then call that code
whenever you need to carry out that action.
We are already repeating ourselves in our code, so this is a good time to introduce simple
functions. Functions mean less work for us as programmers, and effective use of functions
results in code that is less error-prone.
Notice that everything under def hello() is indented. Python is an indented language. It uses
indentation to understand what is part of the above function. Therefore, everything in the hello
function must be indented. When something is not indented, it treats it as if it is not inside the
hello function. Running python hello.py in the terminal window, you’ll see that your output is not
exactly as you may want.
One benefit of this is that if you decide to change the size of the box, you just have to modify the
code in the function, whereas if you had copied and pasted the box-drawing code everywhere
you needed it, you would have to change all of them.
Argument
When we call the print_hello function with the value 3, that value gets stored in the variable n.
We can then refer to that variable n in our function’s code. You can also pass more than one
value to a function
Returning Values
You can imagine many scenarios where you don’t just want a function to perform an action but
also to return a value back to the main function. For example, rather than simply printing the
calculation of x + y, you may want a function to return the value of this calculation back to
another part of your program. This “passing back” of a value we call a return value.
Effectively, x is passed to square. Then, the calculation of x * x is returned back to the main
function. Furthermore, the return statement is used within a function to exit it and pass back a
value to the caller. The value that’s returned can be any data type, including more complex
types like lists, dictionaries, or custom objects.
In this example, the add function adds two numbers and uses return to give back the result. The
sum variable then receives the returned value, which is 8.
If a function doesn’t explicitly return a value, it implicitly returns None. The return statement can
also be used without a value to exit the function early:
In this case, if number is negative, the function prints a message and exits before reaching the
second print statement. Understanding the return statement is crucial for controlling the flow of
your Python programs and for designing functions that interact with other parts of your code.
Lambda function
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:
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.
Multiple Arguments
Lambda functions can take multiple arguments. For instance, multiplying a with b
Use Cases
Lambda functions are 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.
Remember, lambda functions are concise and handy for specific scenarios
(File I/O)
Up until now, everything we’ve programmed has stored information in memory. That is, once the
program is ended, all information gathered from the user or generated by the program is lost.
File I/O is the ability of a program to take a file as input or create a file as output.
Open
open is a functionality built into Python that allows you to open a file and utilize it in your
program. The open function allows you to open a file such that you can read from it or write to it.
To show you how to enable file I/O in your program, let’s rewind a bit and code as follows:
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").
To show you how to enable file I/O in your program.
Notice that the open function opens a file called names.txt with writing enabled, as signified by
the w. The code above assigns that opened file to a variable called file. The line
file.write(name) writes the name to the text file. The line after that closes the file.
Testing out your code by typing python names.py, you can input a name and it saves to the
text file. However, if you run your program multiple times using different names, you will notice
that this program will entirely rewrite the names.txt file each time.
Ideally, we want to be able to append each of our names to the file. Remove the existing text file
by typing rm names.txt in the terminal window. Then, modify your code as follows
Notice that the only change to our code is that the w has been changed to a for “append”.
Rerunning this program multiple times, you will notice that names will be added to the file.
However, notice that the line with file.write has been modified to add a line break at the end of
each name.
This code is working quite well. However, there are ways to improve this program. It so happens
that it’s quite easy to forget to close the file.
With
The keyword with allows you to automate the closing of a file.
Make sure the file exists, or you'll get an error. Notice that readlines have a special ability to
read all the lines of a file and store them in a file called lines.
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:
SQLite
MySQL / MariaDB
PostgreSQL
MongoDB
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.
Tkinter
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:
● Widgets: Widgets are the basic building blocks of a Tkinter application. They include
buttons, labels, entry fields, etc.
● Geometry Managers: Tkinter provides different geometry managers to arrange widgets
within the application window. Common ones include pack(), grid(), and place().
Event Handling
Tkinter applications are event-driven. You can bind functions to events such as button clicks,
mouse movements, etc.
● Custom Widgets: You can create custom widgets by subclassing existing ones.
● Styling: Tkinter supports basic styling options like colors, fonts, etc.
● Dialogs: Tkinter provides built-in dialogs for common tasks like file selection, message
display, etc.
● Threading: Use threading to prevent the GUI from freezing during long-running tasks.
● Integration with Other Libraries: Tkinter can be integrated with other Python libraries
like Matplotlib for data visualization.