Skip to main content

Python Fundamentals

Maths

+ addition
- subtraction
* multiplication
/ Division
//

Floor Division

an operation that divides two numbers and returns the largest integer less than or equal to the quotient.

 

When you divide 7 by 3, you get approximately 2.3333. The floor division 7 // 3 returns 2 because 2 is the largest integer that is less than or equal to 2.3333.

%

Modulus operator

The modulus operation returns the remainder after dividing one number by another.

**

Exponentiation

Exponentiation raises one number (the base) to the power of another number (the exponent).

2 ** 3 means 2 raised to the power of 3, which equals 2 * 2 * 2 = 8.


Logical Operators

Logical operators in Python are used to combine conditional statements. They allow you to perform logical operations on expressions and return a boolean value (True or False). Python has three logical operators:

price = 25
print(price > 10 and price < 30)
print(price > 10 or price <30)

and

Returns True if both statements are true.

or

Returns True if one of the statements is true.

not

Reverses the result, returns False if the result is true.

Comparison Operators

These operators compare two values and return a boolean result (True or False).

price = 25
print(price > 10 and price < 30)

<

less than

> 

greater than

<= 

less than or equal to

>= 

greater than or equal to

== 

equal to

!= 

not equal to


Control Flow Statements

Dictate the flow of execution in your program. They determine which code blocks get executed and when.


IF Statements

An if statement in Python is a control flow statement that allows you to execute a block of code only if a specified condition is true.

temperature = 35
if temperature > 30:
    print ("It's a hot day")

ELSE IF (ELIF) Statements

The elif statement in Python, short for "else if," is used to check multiple conditions in an if statement. It allows you to specify additional conditions if the previous conditions are not true. There's no limit on the number of elif conditions you can add.

temperature = 35
if temperature > 30:
    print ("It's a hot day")
elif temperature > 20:
    print("It's a nice day")

You can also combine ELIF statements:

elif (player_choice == "rock" and computer_choice == "scissors") or \
     (player_choice == "scissors" and computer_choice == "paper") or \
     (player_choice == "paper" and computer_choice == "rock"):
    print("You Win!")

ELSE Statements

The else statement in Python is used in conjunction with if and elif statements to provide a block of code that executes when none of the preceding conditions are true. It acts as a default case for your conditional logic, ensuring that there's always a defined action if none of the specified conditions are met.

temperature = 35
if temperature > 30:
    print ("It's a hot day")
elif temperature > 20:
    print("It's a nice day")
else:
    print("It's probably cold")

WHILE Loops

A while loop in Python is used to repeatedly execute a block of code as long as a specified condition is true. It is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The loop continues to execute until the condition becomes false.

a = 1
while a <= 10:
    print(a)
    a = a + 1

Try statement

This block contains the code that you suspect might raise an exception. An exception is an event that disrupts the normal flow of your program's execution. These can occur due to various reasons, some of which are:

  • User Input Errors: Imagine a program that asks the user for a number but the user enters text instead. This unexpected input can cause an error.
  • File I/O Issues: When your program tries to access a file that doesn't exist or encounters permission issues while reading/writing, it can raise an exception.
  • Mathematical Errors: Division by zero or other mathematically invalid operations can lead to exceptions.
  • Logical Errors: These are errors in your program logic that might not be immediately apparent but can cause unexpected behavior. While not technically exceptions, they can often lead to situations where exceptions are raised.


LISTS

Lists in Python are ordered collections of items that can hold a variety of object types, including other lists. They are one of the most versatile and commonly used data types in Python, allowing you to store, modify, and manipulate sequences of elements.

names = ["John", "Bob", "Dan"] #Create a LIST of names
names[0] = "jon" # Change index 0 in the LIST
print(names[0]) #Print index position 0 from the LIST
print(names[0:3]) #Print the first 3 index (names) from the LIST
numbers = [1, 2, 3, 4, 5] # Creates a list of numbers 1-5
numbers.append(6) #Append number 6 to the end of the list
numbers.insert(6, 7) #Add number 7 to index position 6
print(1 in numbers)#Check for the number 1 in the LIST numbers. Boolean

Functions

A function is a reusable block of code that performs a specific task. You can define functions with the def keyword, followed by the function name, parentheses for arguments (optional), a colon (:), and then the indented code block that represents the function's body.

def greeting(): #Define a function called greeting
    return "Hi" #The function returns the string "Hi"
response = greeting() #set the variable response to: calls the function greeting
print(response) #Prints variable response
Passing data to a function

You can pass data into a function to be used essentially as a variable.

choices = {"player": player_choice, "computer": computer_choice} ##Set a dictionary

def check(player, computer): ##define a function which calls the key values from the dictionary
    # Add your logic here
    print(f"Player chose: {player}")
    print(f"Computer chose: {computer}")

You can pass data into a function that can then be referenced within the function code. in the above, the key values player and computer are passed into the function, allowing for the values to be used by the function code.

Passing data out of a function (return)

You can return multiple values from a function and then set them as their own variables.

def get_choices(): 
    player_choice = str(input("Enter a choice\nrock\npaper\nscissors"))
    list = ["rock", "paper", "scissors"]
    computer_choice = random.choice(list)
    choices = { "player":player_choice, "computer":computer_choice }
    return choices, computer_choice, player_choice
    
choices, computer_choice, player_choice = get_choices() ##create new variables to set based on the return values of the function.

Dictionaries

A dictionary is a powerful data structure that allows you to store collections of key-value pairs. It's like a real-world dictionary where you look up words (keys) to find their definitions (values).

def get_choices(): 
    player_choice = str(input("Enter a choice\nrock\npaper\nscissors)"))
    computer_choice = "paper"
    choices = {"player:" : player_choice, "computer" : computer_choice} ##Creates a dictionary called choices. 2 key pair values: key:"player" value:player_choice (variable), key:"computer" value: computer_choice (vairable)
    return choices
    
choices = get_choices()
print(choices)

Format for defining a dictionary

dictionaryname = { key : value, key : value }

Calling dictionary data:

If you need all of the data in the dictionary, then you can call the whole dictionary:

choices = {"player": "rock", "computer": "scissors"}

def check(choices):
    print(f"Player chose: {choices['player']}")
    print(f"Computer chose: {choices['computer']}")

check(choices)

alternatively, you can call on a key value from a dictionary:

choices = {"player": "rock", "computer": "scissors"}

def check(player, computer):
  print(f"Player chose: {player}")
  print(f"Computer chose: {computer}")

Libraries


Random

import library:

import random
choice()
list = [option1, option2, option3]
variable = random.choice(list)

Returns a random element of a given sequence.







MySQL

import library:

from getpass import getpass
from mysql.connector import connect, Error

Configuring MySQL connection details:

try:
    with connect(
        host="localhost",
        user=input("Enter username: "),
        password=getpass("Enter password: "),
        database="database_name",
    ) as connection:
        print(connection)
except Error as e:
    print(e)

Querying a MySQL database:

Example:


import mysql.connector
from getpass import getpass
from mysql.connector import connect, Error

##User Management Application##
print("User Management")

##User Option Selection##
def option():
    options_list = {1 : "view", 2: "delete", 3: "create"}    
    option_selection = int(input("Select an option\n1. View Users\n2. Delete User\n3. Create User\n"))
    if option_selection in options_list:
        print(f"{options_list[option_selection]} users:")
    else:
        print("Invalid Option")
    return option_selection

option_selection = option()

##DATABASE CONNECTION AND QUERY##
def database_query(option_selection):
    if option_selection == 1:
        connection = None
        cursor = None
        try:
            print("Connecting to database...")
            # Establish a connection to the MySQL database
            connection = mysql.connector.connect(
                host="localhost",
                user="python",
                password="",
                database="user_database"
            )

            if connection.is_connected():
                print("Connection Established...\nQuerying Database...")

                    # Create a cursor object
                cursor = connection.cursor()

                    # Define the SELECT query
                query = "SELECT * FROM users"

                    # Execute the SELECT query
                cursor.execute(query)

                    # Fetch all results
                results = cursor.fetchall()

                    # Process the results
                for row in results:
                    print(row)

        except Error as e:
            print("Error:", e)

        finally:
            if cursor is not None:
                cursor.close()
            if connection is not None and connection.is_connected():
                connection.close()
                print("Connection closed")
    return option_selection        

# Run the function
database_query(option_selection)


Examples

Rock, Paper, Scissors

import random ##import library 'random'

def get_choices(): #define a function called 'get_choices'
    player_choice = str(input("Enter a choice\nrock\npaper\nscissors")) #Set player_choice as user input value
    list = ["rock", "paper", "scissors"] #Create a list of available options
    computer_choice = random.choice(list) #computer choice = random item from list
    choices = { "player":player_choice, "computer":computer_choice } #set variable 'choices' as the list of both choices.
    return choices, computer_choice, player_choice #return the computer_choice, player_choice, and choices variables
    
choices, computer_choice, player_choice = get_choices() #Set choices, computer_choice, player_choice variables based on return value of get_choices function
print("Choices: ",choices) #print choices variable

if (player_choice) == (computer_choice): #Determine whether drawn
    print("DRAW") #print DRAW if so

elif (player_choice == "rock" and computer_choice == "scissors") or \ #Determine player win
     (player_choice == "scissors" and computer_choice == "paper") or \
     (player_choice == "paper" and computer_choice == "rock"):
    print("You Win!") #print 'You Win' if so
    
else:
    print("You Lose") #If not draw or win, print 'You Lose'