Python Programmer Logo Python Programmer Python Programmer Logo


Python Basics Series: Tutorials for Beginners

Below are the python files I used in these videos and the actual videos


The video files

File Download Date Modified
Tutorial - part 1 Download File 7 Feb 2024
Tutorial - part 2 Download File 10 Feb 2024
Tutorial - part 3 Download File 22 Feb 2024
Tutorial - part 4 Download File 17 Mar 2025
Tutorial - part 5 Download File 12 Nov 2025

The actual code in each file

Tutorial - part 1


"""This tutorial will show a lot of basic input/output functions and methods so that
you can start your python programming journey. It wil focus on efficiency and won't
be too complex, there will be more advanced tutorials on my channel in future, so be
sure to like and subscribe."""

#The first in-built function you need to know is print
print("Hello world")
"""This will allow you to display a piece of text of your choosing to the screen,
in this app it will display to the window on the right -->"""

#Now I will run the program

#So now let's do something a bit more advanced

#let's say we want to store something in memory then print it

#We use a variable, you can name it whatever you want, but it should be descriptive

name = "John"
"""That is one example of a variable, now we can use it to print the name of someone,
however, it doesn't need to be the only thing in the print statement, you can use a comma,
to seperate the name and any text you want to put in as well"""

print("My name is:",name)

#Okay, so we printed out some text, we can also print out numbers

age = 7

#Now let's try to print this age directly

print("My age is:",age)

#However, what if we want to add 2 numbers and print the result

num1 = 23
num2 = 5

print(num1+num2)

#This time the numbers will be in quotes

num3 = "3"
num4 = "5"

#Write in the comments what you think will happen

#Anyways, let's print out the 2 numbers
print(num3+num4)

#We can use another function 'int' to convert them to numbers
print(int(num3)+int(num4))

#So that was output, what about input, when we want to enter a value

#There is another function for this, 'input'

text = input("Enter something: ")
print("you entered:",text)

#We can also put some text inside the input function

"""There are also other ways of inputting text and you can input mnore than just text,
however that is more advanced and requires more tools, we will explore them in
future tutorials, anyways let's try to input a number"""

num = int(input("Enter a number: ")) #We can use int to convert them to numbers
otherNum = int(input("Enter another number: "))
print("The sum of the numbers is:",(num+otherNum))

"""However, a comma is usually better as it automatically adds a space between text in
quotation marks and a variable"""

"""Now we can put everything together to make something"""

name = input("Enter your name: ")
age = int(input("Enter your age: "))
anotherAge = int(input("Enter someone else's age: "))

print("Your details are:\nYour name is:",name,"\nYour age is:",age,
      "\nYou are",(age-anotherAge),"years older than this other person")

Tutorial - part 2


#Today we will be looking at String methods and conditional statements

"""This program will closely examine some of the various string methods and also
will look at conditional statements (if, elif, else) and also the boolean operators"""

#below is an example of a string
myString = "Hello, This is a string!"

#First we'll start with string slicing
print(myString[:5]) #This will print out the first 5 characters of 'myString'
print(myString[10:]) #This will print from character 10 till the end
print(myString[6:11]) #This will print from character 6 until character 10 (not including 11)

#You can also get a single character from a string, this time we'll ask the user
character = int(input("Enter a character number (index) to retrieve from string: "))
print("The character is:",myString[character])

#Okay, so now we will use one of the many string methods

print(myString.count('s'))
#This will print out the amount of times a certain character appears in our string

#Now we can use a different method
newString = myString.replace('Hello', 'Bye')
print(newString)
#So this will replace any substring with another substring, you have to store it as a new string

#There is also a 'lower' method and 'upper' method
print(myString.lower())
print(myString.upper())

#Now moving onto if statements (conditional statements)
if myString.islower() | myString.isupper():
    print("String is uniform")
else:
    print("String is irregular")

#Let's do an example with numbers
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))

if (num1 > 5) & (num2 <= 5):
    print("Success")
elif (num1 == 5) | (num2 > 5):
    print("Neither a fail nor a success")
else:
    print("Fail")

otherString = input("Enter a string to compare to myString: ")

if (myString.islower() | myString.isupper()) & (otherString.islower() | otherString.isupper()):
    print("Both strings are regular")
elif not (myString.islower() | myString.isupper()) and not (otherString.islower() | otherString.isupper()):
    print("Both strings are irregular")
else:
    print("The strings aren't similar in terms of case")

if myString[:5].lower() in otherString.lower():
    print("Both are greetings!")
else:
    print("One of the strings is not a greeting")

if myString == otherString:
    print("The strings match!")
else:
    print("The strings don't match")

Tutorial - part 3


  """Ok so I've explained a bit about iteration loops and file handling, now we will
move on into the coding examples, be sure to follow along if you're watching
from home and want to learn python"""

"""#In a for loop, we don't need any pre-defined variables
for num in range(5):
    print("The number is:",num)
    #This will print out the numbers from 0 to 4 (not including 5)

#For loops are very useful, but only if we know the amount of times we're looping
for i in range(1,6):
    #here we are looping from 1 to 5 (not including 6)
    print("I have",i,"apples")

#Anyway now let's look at counting backwards
for count in range(5, 0, -1):
    #-1 will allow us to go backwards by 1 each time
    print("Numbers till countdown ends:",count)

#We can also loop in increments, for example every even number (up to a point)
for number in range(0, 22, 2):
    #This will print out every even number from 0 to 20
    print("The even number is:",number)

#The final thing we can do with for loops is loop over data structures such as lists

#First we will create the list
myList = list(range(0,10)) #This is a handy trick for creating a list quickly

#Now we will print each number in the list
for item in myList:
    print("The item is:",item)

#Now moving onto while loops, for these we do need pre-defined variables

continueLoop = True

while continueLoop:
    continueLoop = input("Should the loop continue? ")
    if continueLoop.lower() == "yes":
        continueLoop = True
    else:
        continueLoop = False
    #Here we took a user input then assigned values to it using an if statement
    #If you haven't already, check out the previous tutorial where we went over if statements and string methods

#Now we move onto file handling, this also uses loops

#First we will read a file using a for loop

#We need to open the file and we use the "open" command for this
thisFile = open("new.txt")
#This will open the file in read mode that is called "new.txt", the file format does have to be there

#Now we can print each line of the file
for line in thisFile:
    print(line)

#Another way to open a file is to store its name in a variable
fileName = "newer.txt"
file = open(fileName)

#There are also other methods to read from the file
fileContents = file.readlines()

for line in fileContents:
    #There is also another method (split) which can split a line by any character
    line = line.split(",") #In this example, we have a comma seperated list on each line
    #This method will return an array
    #Now we can use a for loop to iterate through each item in the line list/array
    for item in line:
        print(item.strip())"""

#Now we will write to a new file, you don't need an existing file for this
fileName = input("Enter a name for the file: ")
#We have to append the txt extension to the filename, otherwise it won't work
fileName += ".txt"

#Whoops, almost forgot to open the file
myFile = open(fileName, 'w') #We need the 'w' to be able to write to the file

#Now we can use a while loop to let the user keep adding to the file
moreLines = True #remember, we need a pre-defined variable

while moreLines:
    line = input("Enter a line to add to the file: ")
    moreLines = input("Do you wish to add more lines(Y/N)? ")
    if moreLines.upper() != "N":
        moreLines = True
    else:
        moreLines = False
    #Now we can write the line to the file
    myFile.write(line)
    myFile.write("\n")
#Finally, we have to close the file
myFile.close()

Tutorial - part 4


"""We'll begin by creating a few functions or procedure for functional programming
Here's a simple example"""

def add(num1: int, num2: int) -> int: #over here we've declared a function with type hints (variable types)
    total = num1 + num2
    return total #the return keyword is key in functions

def subtract(num1: int, num2: int) -> int: #this is a subtract function similar to the add one above
    difference = num1 - num2
    return difference

def main(): #this one is a procedure so won't return anything
    num1 = int(input("Enter a number: ")) #here we take the first number as a user input (covered in episode 2)
    num2 = int(input("Enter another number: "))
    total = add(num1, num2)
    difference = subtract(num1, num2)
    #above we just called the 2 functions we defined above with the numbers, now we can output the results
    print("The total of the 2 numbers is:",total)
    print("The difference between the 2 numbers is:",difference)

#now we'll use the main statement and call our procedure
if __name__ == "__main__":
    main() #now we run it

"""So in this example, we have the add and subtract functions
that perform basic arithmetic operations and then the main procedure
calls these functions after taking user inputs and presents the results in
an orderly and user friendly manner. It's an easy model to follow and straightforward for simple tasks.
However, in a real world situation, it isn't always ideal and that's where OOP comes in."""

# Now in OOP we'll use classes to build the calculator and define it in code

class calculator():
    def __init__(self): #this is the constructor method, it's needed in all classes
        #we'll use this to 'save' variables
        self.num1 = 0 #this is a public attribute (can be accessed anywhere)
        self.__num2 = 0 #the 2 underscores transform it into a private attribute (can only be accessed within this class)
        #now we've set up variables as attributes

    def __add(self): #here we've setup a private method
        return self.num1 + self.__num2
    
    def __subtract(self):
        return self.num1 - self.__num2
    
    def calculate(self, num1, num2):
        self.num1 = num1
        self.__num2 = num2
        total = self.__add()
        difference = self.__subtract()
        #above here, we've called the 2 private methods wee defined before and set the attributes to the passed in variables
        return total, difference

if __name__ == "__main__":
    thisCalculator = calculator() #this is where we instantiate the class
    num1 = int(input("Enter a number: "))
    num2 = int(input("Enter another number: "))
    total, difference = thisCalculator.calculate(num1, num2) #the method is then called here
    print("The total of the 2 numbers is:",total)
    print("The difference between the 2 numbers is:",difference)

"""In this OOP example, we defined a Calculator class with methods add and subtract. 
We then created an instance of the Calculator class and call its method. 
This modular approach is great for more complex projects where you want to encapsulate data and behavior.
It also allows for methods that can't be accessed anywhere else, minimising unintended side effects"""

Tutorial - part 5


from colorama import init, Fore

#This class will be used to load the flashcards from the file and includes all associated methods
class FlashCardLoader():
    def __init__(self, initial_filepath):
        self.__cards = [] #List that will store the flashcards after loading
        self.__filepath = initial_filepath #Filepath for the text file that stores the questions and answers
        self.__delimiter = "," #Delimiter that is used in the file to separate questions from answers

    def load_cards(self): #This method will load the cards from our text file
        try: #Here we're using exception handling - this enables us to catch potential runtime errors before they happen
            with open(self.__filepath, "r") as file: #This is a set construct used to read a file (without having to use file.close() afterwards)
                self.__cards = file.read().splitlines() #The file is read and each 'card' is put into a separate index in the cards list
                for i in range(0,len(self.__cards)): #We use a for loop to iterate through the cards list
                    current_card = self.__cards[i] #We store the current card in a variable for easier access
                    #We split the current card into question and answer using the delimiter and update the cards list accordingly
                    self.__cards[i] = current_card.strip().split(self.__delimiter) #We use the strip method also to remove any leading or trailing whitespace from each card
            print(self.__cards) #For testing purposes we print out the cards list to verify it's loaded correctly
        except FileNotFoundError: #Here we catch the error if the file isn't found and define what to do next
            print("Flashcards file not found.") #We just simply print out a relevant statement in this case

    def get_cards(self): #An accessor method is used here to retrieve the cards list from the class
        return self.__cards

    def get_filepath(self): #An accessor method is used here to retrieve the file path from the class
        return self.__filepath

    def get_delimiter(self): #An accessor method is used here to retrieve the delimiter from the class
        return self.__delimiter

    def set_delimiter(self, new_delimiter): #A mutator method is used here to change the delimiter used within the class
        self.__delimiter = new_delimiter
        
    def set_filepath(self, new_filepath): #A mutator method is used here to change the file path used within the class
        self.__filepath = new_filepath

#This class will be used for the main flashcard logic and will encompass the following functions:
"""
1. Looping through flashcards when revising
2. Quizzing yourself on existing flashcards
3. Adding new flashcards temporarily (to the list at runtime but not to the saved text file)
4. Evaluating answers from the flashcards quiz
5. Tracking your score when attempting a quiz
"""
class FlashCardEngine():
    def __init__(self):
        self.__cards = [] #Store the cards that are loaded in a list
        self.__user_choice = 0 #Update this when the user choice input is taken
        self.__score = 0 #Store the score for the quiz
        #Use a dictionary to store the menu options that the user can select
        self.__menu = {1: "1. Loop through flashcards", 2: "2. Add new flashcards temporarily", 3: "3. Quiz yourself on the current flashcards", 4: "4. Quit"}

    #Method to display the different menu items
    def display_menu(self):
        for item in self.__menu.items(): #Uses a for loop and dictionary items method to loop through the menu
            print(item[1]) #print the relevant menu item

    #Method to take user input and verify it
    def get_user_choice(self):
        print("Choose an option from the menu above")
        max_choice = max(list(self.__menu.keys())) #Uses the max, list and dictionary keys method to find the highest choice number available
        choice = input(f"Enter your choice as a number between 1 and {max_choice}: ") #Takes the choice as a number between 1 and max_choice
        choice_valid = self.check_user_choice(choice) #Calls the below method to check if the user choice is a valid number
        if choice_valid: #An if statement to activate when the choice is valid
            self.__user_choice = int(choice) #sets the user_choice attribute that's mentioned in class constructor
            return True #returns True to signify that the choice is valid
        else: #If the choice isn't valid - handles it likewise
            print("Please enter a valid choice") #Issues a user warning via print statement
            return False #returns False to signify that the choice isn't valid

    #Method to check if the user's choice is a valid number
    def check_user_choice(self, choice):
        try: #Here we use exception handling once again - we need to check if the choice is a number
            user_choice = int(choice) #To achieve this we use type casting (explored in episode 2 or 3) and convert it to a number
        except ValueError: #If the type casting failed we'll receive this error and can catch it
            return False #We return False if it can't be converted to signify that the choice is invalid
        # Now we need to check if the choice is part of our available options - we can use the menu dictionary for that
        if user_choice not in list(self.__menu.keys()): #Specifically the .keys method allows us to check the menu options
            return False #We return False as even though the number conversion check passed, the menu option is invalid e.g. 5
        else: #Otherwise, all checks have passed and we can assume the user entered a correct number for their menu choice
            return True #We return True to signify that the user input is valid and can then progress to setting the user_choice attribute (in the above method)

    #Method to call the different menu options depending on the user's choice
    def use_menu(self):
        if self.__user_choice == 1: #If the choice is 1, we activate this statement
            self.display_flashcards() #We can call the method to display the flashcards (defined below)
        elif self.__user_choice == 2: #If the choice is 2, we activate this statement
            self.add_new_flashcards() #We can call the method to add new flashcards (defined below)
        elif self.__user_choice == 3: #If the choice is 3, we activate this statement
            self.attempt_quiz() #We can call the method to attempt the flashcards quiz (defined below)
        else: #Otherwise we know that the user wants to quit - as there's no other options - for more options, more statements could be added as above
            print(Fore.YELLOW + "Thanks for using the Python Programmer Flashcards System!")
            quit() #This method stops the programme from running and ends the process automatically

    #Method to display all flashcards currently stored in memory
    def display_flashcards(self):
        for card in self.__cards: #We use a for loop to read all the flashcards from the cards list (stored as private attribute)
            print(f"Question: {card[0]}") #Prints out the question (stored as the first part of the flashcard)
            input("Press Enter to view answer: ") #We allow the user to press enter before viewing the answer instead of giving it straight away
            print(f"Answer: {card[1]}") #Prints out the answer of the flashcard (stored as the second part)

    #Method that allows users to add new flashcards temporarily
    def add_new_flashcards(self):
        cards_to_add = 0 #We set this variable to 0 to begin with
        try: #Once again we use exception handling - this time to make sure that cards_to_add is a number that can be used in the for loop
            cards_to_add = int(input("Enter the number of flashcards to add to the list: ")) #We take this as user input and cast to integer directly
        except ValueError: #If a ValueError occurs (i.e. it's not an integer) then we can handle it here
            print("Please enter a valid integer.")
            self.add_new_flashcards() #Here we call this method again to take the input again and then progress
        for num in range(cards_to_add): #We use a for loop to keep allowing the user to enter new cards for as many cards as they said before
            print("Question",num+1) #We print the question number that the user is adding (e.g. 1 if on the first one)
            question = input("Enter your question: ") #We use a user input to get the question
            answer = input("Now enter your answer: ") #Aother user input is used to get the answer to the question
            self.__cards.append([question, answer]) #The question and answer are appended to the cards list
        if cards_to_add != 0: #If there were cards added then we can proceed with this part
            print(f"All {cards_to_add} flashcards have been added to the list.")
            view_list = input("Do you wish to view the full cards list now (Y/N)? ") #We allow the user to view the cards list via user input
            if view_list.lower() == "y": #If they chose to view the cards we can progress with this part
                print("All cards in the list are displayed below:")
                for card in self.__cards: #We use a for loop to read the cards list
                    print(f"Question: {card[0]}") #We print out the question as the first part of the flashcard
                    print(f"Answer: {card[1]}") #We print out the answer as teh second part of the flashcard
        else: #Otherwise there either weren't any cards added or there was an error and we can handle that here
            print("No flashcards added")

    #Method to allow the user to quiz themselves on the flashcards
    def attempt_quiz(self):
        #This will mostly be where we will use the special colours from colorama to make it look nice
        self.__score = 0 #We set the score to 0 first for every new quiz
        for card in self.__cards: #We use a for loop to read the cards for the quiz
            print(f"Question: {card[0]}") #We print out the question first (as first part of the card)
            answer = input("Enter your answer: ") #Then we take the user's answer as user input
            if answer.lower() == card[1].lower(): #If the answer matches (we use .lower to ignore the case) we can progress here
                print(Fore.GREEN + "Correct! " + card[1] + " is the correct answer.")
                self.__score += 1 #We increase the score by 1
            else: #If the answer is incorrect we can progress here
                print(Fore.RED + "Incorrect. " + card[1] + " is the actual correct answer.")
            print("Your current score is:",self.__score) #After each question we print the score
        #After the quiz finishes we can print this 
        print(f"Quiz finished! You scored {self.__score} out of {len(self.__cards)} flashcards!")

    #Method to get the current score (accessor method)
    def get_score(self):
        return self.__score

    #Method to get the current cards list (accessor method)
    def get_cards(self):
        return self.__cards

    #Method to set the current cards list (mutator method)
    def set_cards(self, new_cards):
        self.__cards = new_cards

# Main programme logic to run the flashcards system
def main():
    init(autoreset=True) #Initialises colorama with autoreset to avoid color issues in terminal
    print(Fore.CYAN + "Welcome to the Python Programmer Flashcards System!") #Prints a welcome message in cyan color
    flashcard_loader = FlashCardLoader("flashcards.txt") #Creates an instance of the FlashCardLoader class with the specified file path
    flashcard_loader.load_cards() #Calls the load_cards method to load the flashcards from the file
    cards = flashcard_loader.get_cards() #Retrieves the loaded cards using the accessor method
    flashcard_engine = FlashCardEngine() #Creates an instance of the FlashCardEngine class
    flashcard_engine.set_cards(cards) #Sets the loaded cards into the flashcard engine using the mutator method
    while True: #Main loop to keep displaying the menu until the user decides to quit
        flashcard_engine.display_menu() #Displays the menu options
        choice_valid = flashcard_engine.get_user_choice() #Gets and validates the user's choice
        if choice_valid: #If the choice is valid, proceed to use it
            flashcard_engine.use_menu() #Calls the method to execute the chosen menu option

# Run the main programme logic
if __name__ == "__main__":
    main()

"""
Ok, so now we've got a fully working app.
However, there's still one little part left. 
Remember we pip installed colorama at the start of this episode.
Now we'll add different colors to our print statements to make the app look a bit more visually appealing.
"""