Examples Of (Numbers, Dictionary, For Loop, And If Statement) In Python

In this article, we are going to provide you with simple Python examples using only these basic Python concepts:

Examples like these are important for beginners because they help them open their minds and be creative to solve other programming problems that will require them to use programming concepts.

A lot of people who are learning to code know about the basic concepts of a programming language but they can’t start to write at least simple codes or project with it. If you didn’t make the first step and make a small example with what you have already learned, you won’t be able to build a project on your own.

Let’s dive into these unique examples using concepts that are easy to learn and anyone can understand them. You have to know that big programming projects are built with small concepts so don’t skip this first practice phase.

Before we begin, try to learn these Python concepts if you want to understand our examples:

  • To learn numbers in Python, visit our article here.
  • To learn dictionary in Python, visit our article here.
  • To learn for loop in Python, visit our article here.
  • To learn decision-making (if-elif-else) in Python, visit our article here.

Example 1

Get the score of every student and show results if he/she succeed or fail.

Code

#____ProgrammerCodes.com____
students_score = {"Eva":9,"Charlotte":8,"James":7,"Evan":5,"Suzan":8}
print("Students Score:")
for student in students_score:
    print(student , "=" ,students_score[student])
    if (students_score[student] >= 7):
        print("Congratulations! You Succeed")
    else:
        print("Fail! Good Luck")
#____ProgrammerCodes.com____

Code’s explanation

#____ProgrammerCodes.com____
students_score = {"Eva":9,"Charlotte":8,"James":7,"Evan":5,"Suzan":8}
#____ProgrammerCodes.com____

In this line, we have filled the dictionary with the names and scores of students. Every student has a score.

#____ProgrammerCodes.com____
print("Students Score:")
#____ProgrammerCodes.com____

In this line, we have displayed a title.

#____ProgrammerCodes.com____
for student in students_score:
    print(student , "=" ,students_score[student])
    if (students_score[student] >= 7):
        print("Congratulations! You Succeed")
    else:
        print("Fail! Good Luck")
#____ProgrammerCodes.com____

In our example, students who will score more than or equal to 7 will pass this exam successfully. We used for loop in order to access every key in the dictionary. We used if because when the for loop start, it will check if the student has more than or equal to 7 so we will display the text that contains the student score according to the condition.

Result

Students Score:
Eva = 9
Congratulations! You Succeed
Suzan = 8
Congratulations! You Succeed
Charlotte = 8
Congratulations! You Succeed
Evan = 5
Fail! Good Luck
James = 7
Congratulations! You Succeed
python basic example 1 result

Video

Example 2

Add new foods to the store and check how many you currently have in the stock.

Code

#____ProgrammerCodes.com____
foods_stock = {"Tomatoes":3,"Eggs":2,"Potatoes":7}
print("Current Stock:")
for element in foods_stock:
    print(element, ":", foods_stock[element])
print("_______________________________________________")
add = input("What do you want to add in the stock?")
add = add.capitalize()
if (add == "Tomatoes"):
    tomatoes = input("How many tomatoes you have?:")
    foods_stock["Tomatoes"] = foods_stock["Tomatoes"] + int(tomatoes)
elif (add == "Potatoes"):
    potatoes = input("How many potatoes you have?:")
    foods_stock["Potatoes"] = foods_stock["Potatoes"] + int(potatoes)    
elif (add == "Eggs"):
    global eggs
    eggs = input("How many eggs you have?:")
    foods_stock["Eggs"] = foods_stock["Eggs"] + int(eggs)
print("_______________________________________________")
print("Updated Stock:")
for element in foods_stock:
    print(element, ":", foods_stock[element])
#____ProgrammerCodes.com____

Code’s explanation

#____ProgrammerCodes.com____
foods_stock = {"Tomatoes":3,"Eggs":2,"Potatoes":7}
print("Current Stock:")
for element in foods_stock:
    print(element, ":", foods_stock[element])
#____ProgrammerCodes.com____

We created a dictionary that contains foods and we did a for loop in order to show every value that is in the dictionary.

#____ProgrammerCodes.com____
add = input("What do you want to add in the stock?")
add = add.capitalize()
#____ProgrammerCodes.com____

In this part of the code, we ask the user to write the food in order to add it to stock. When the user writes the food, the program will store that food in a variable called ‘add’ then it will capitalize the first letter.

#____ProgrammerCodes.com____
if (add == "Tomatoes"):
    tomatoes = input("How many tomatoes you have?:")
    foods_stock["Tomatoes"] = foods_stock["Tomatoes"] + int(tomatoes)
elif (add == "Potatoes"):
    potatoes = input("How many potatoes you have?:")
    foods_stock["Potatoes"] = foods_stock["Potatoes"] + int(potatoes)    
elif (add == "Eggs"):
    global eggs
    eggs = input("How many eggs you have?:")
    foods_stock["Eggs"] = foods_stock["Eggs"] + int(eggs)
#____ProgrammerCodes.com____

In this part of the code, we checked what kind of food the user want to add to the stock then according to that kind of food the program will add the number of quantities to the quantity that is already in the stock.

int(variable): we used it to convert from string type of variable to integers so we can be able to do the addition.

#____ProgrammerCodes.com____
print("Updated Stock:")
for element in foods_stock:
    print(element, ":", foods_stock[element])
#____ProgrammerCodes.com____

In this part of the code, we show the new stock with the new quantity.

Result

Current Stock:
Eggs : 2
Potatoes : 7
Tomatoes : 3
_______________________________________________
What do you want to add in the stock?Eggs
How many eggs you have?:4
_______________________________________________
Updated Stock:
Eggs : 6
Potatoes : 7
Tomatoes : 3

Video

Example 3

Write the title of the blog post then the program will display it.

Code

#____ProgrammerCodes.com____
blogposts = {
    "Lorem ipsum dolor sit amet":"adipisibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec fcing elit. Cras non tortor ex. In dignissim at eros ut maximus. Mauris faucibus dapibus augue, eu pellentesque tellus viverra ac",
    "Vestibulum dapibus faucibus finibus":"bulum dapibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, ibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec frutrum",
    "Nunc sodales tellus id efficitur viverra":"que vel velit sit amet, malesuada consequat sapien. Curabitur malesuada urna eget turpis bibendum convallis. Vestibuibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec flum maximus ",
    "Nulla at tellus enim":"l turpis, fermentum id fringilla nec, porttitor vel enim. Maecenas porttitor augue ut arcu pharetra, non condimentum risusibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec f sodales. Nulla"
    }
for each_title in blogposts:
    print("=> ", each_title)
print("==================================================================")
title = input("Write the title of the blog post that you want to read:")
print("==================================================================")
print(blogposts[title])
print("==================================================================")
#____ProgrammerCodes.com____

Code’s explanation

#____ProgrammerCodes.com____
blogposts = {
    "Lorem ipsum dolor sit amet":"adipisibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec fcing elit. Cras non tortor ex. In dignissim at eros ut maximus. Mauris faucibus dapibus augue, eu pellentesque tellus viverra ac",
    "Vestibulum dapibus faucibus finibus":"bulum dapibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, ibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec frutrum",
    "Nunc sodales tellus id efficitur viverra":"que vel velit sit amet, malesuada consequat sapien. Curabitur malesuada urna eget turpis bibendum convallis. Vestibuibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec flum maximus ",
    "Nulla at tellus enim":"l turpis, fermentum id fringilla nec, porttitor vel enim. Maecenas porttitor augue ut arcu pharetra, non condimentum risusibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec f sodales. Nulla"
    }
#____ProgrammerCodes.com____

We have created a dictionary and we stored the title of the blog post as key and the content of the blogpost as value.

#____ProgrammerCodes.com____
for each_title in blogposts:
    print("=> ", each_title)
#____ProgrammerCodes.com____

We did this line of code in order to show the four titles of the blog posts that we have in the dictionary.

#____ProgrammerCodes.com____
title = input("Write the title of the blog post that you want to read:")
#____ProgrammerCodes.com____

In this part of the code, we ask the user to write the title of the blog post then we will store that title as a variable in order to use it later.

#____ProgrammerCodes.com____
print(blogposts[title])
#____ProgrammerCodes.com____

This part of the code is responsible for displaying the blog post content. We accessed the content by accessing the dictionary key that is similar to what the user asked for (title of the blog post) in order to show the exact content.

Result

=>  Nunc sodales tellus id efficitur viverra
=>  Nulla at tellus enim
=>  Lorem ipsum dolor sit amet
=>  Vestibulum dapibus faucibus finibus
==================================================================
Write the title of the blog post that you want to read:Lorem ipsum dolor sit amet
==================================================================
adipisibus faucibus finibus. Nam et maximus lorem, eget sollicitudin turpis. Proin consequat nibh turpis. Aenean velit dui, rutrum non finibus nec, ullamcorper vel enim. Aliquam viverra placerat viverra. Praesent malesuada viverra justo, at congue lacus sagittis vitae. Donec fcing elit. Cras non tortor ex. In dignissim at eros ut maximus. Mauris faucibus dapibus augue, eu pellentesque tellus viverra ac
==================================================================

Video

Example 4

Start the numbers game and you will win points depends on what random number you will get.

Code

#____ProgrammerCodes.com____
import random
print("=============================================================")    
print("""
             Numbers Game
             ____________
             
             Numbers <10: 5 Points
             Numbers <50: 15 Points
             Numbers >=50: 30 Points
          """)
print("=============================================================")    
while True:
    print("=============================================================")    
    print("The Random Numbers Are(3, 41, 8, 22, 84, 90)")
    print("==============================================")    
    input("Press (START) To Begin The Game:")
    number = random.choice([3,41,8,22,84])
    print("==============================================")    
    if (number <10):
        print("The Random Number is: ", number)
        print("You Win 5 Points!")
    elif (number <50):
        print("The Random Number is: ", number)
        print("You Win 15 Points!")
    else:
        print("The Random Number is: ", number)
        print("You Win 30 Points!")
    print("=============================================================")    
#____ProgrammerCodes.com____

Code’s explanation

#____ProgrammerCodes.com____
import random
print("=============================================================")    
print("""
             Numbers Game
             ____________
             
             Numbers <10: 5 Points
             Numbers <50: 15 Points
             Numbers >=50: 30 Points
          """)
#____ProgrammerCodes.com____

We imported the random module because we need to use the choice function then we displayed some information about the game.

#____ProgrammerCodes.com____
    print("=============================================================")    
    print("The Random Numbers Are(3, 41, 8, 22, 84, 90)")
    print("==============================================")    
    input("Press (START) To Begin The Game:")
    number = random.choice([3,41,8,22,84])
#____ProgrammerCodes.com____

In these lines of the code, we ask the user to press start in order to begin the game. We used the choice number that will take a random number from that list and store it in the number variable.

#____ProgrammerCodes.com____
    if (number <10):
        print("The Random Number is: ", number)
        print("You Win 5 Points!")
    elif (number <50):
        print("The Random Number is: ", number)
        print("You Win 15 Points!")
    else:
        print("The Random Number is: ", number)
        print("You Win 30 Points!")
#____ProgrammerCodes.com____

The rule of this game is to choose a random number from a list and give the user the points according to the random number so that is why we used the if statement to make a decision.

#____ProgrammerCodes.com____
while True:
#____ProgrammerCodes.com____

This is another type of while loop. This kind of loop will keep repeating the code forever until the condition is false or not true.

We did this kind of loop to keep repeating the game and when the user finishes the game and gets the points, the user can play the game again.

Result

=============================================================

             Numbers Game
             ____________
             
             Numbers <10: 5 Points
             Numbers <50: 15 Points
             Numbers >=50: 30 Points
          
=============================================================
=============================================================
The Random Numbers Are(3, 41, 8, 22, 84, 90)
==============================================
Press (START) To Begin The Game:
==============================================
The Random Number is:  41
You Win 15 Points!
=============================================================
=============================================================

Video

Example 5

The user will write the name of the day, and the program will show the plan for that day.

Code

#____ProgrammerCodes.com____
weekly_plan = {
    "Monday":"Business Work",
    "Tuesday":"Meeting",
    "Wednesday":"Work",
    "Thursday":"Work",
    "Friday":"Interview",
    "Saturday":"Event",
    "Sunday":"Sport"
    }
day = input("Choose Day Of The Week:")
print("On", day, "You Have", weekly_plan[day])
#____ProgrammerCodes.com____

Code’s explanation

#____ProgrammerCodes.com____
weekly_plan = {
    "Monday":"Business Work",
    "Tuesday":"Meeting",
    "Wednesday":"Work",
    "Thursday":"Work",
    "Friday":"Interview",
    "Saturday":"Event",
    "Sunday":"Sport"
    }
#____ProgrammerCodes.com____

We created a dictionary that contains the name of the day as a key and the plan for that day as a value.

#____ProgrammerCodes.com____
day = input("Choose Day Of The Week:")
#____ProgrammerCodes.com____

In this line of the code, we asked the user to write the name of the day so that the program will show this user what will be the plan for that day.

#____ProgrammerCodes.com____
print("On", day, "You Have", weekly_plan[day])
#____ProgrammerCodes.com____

In this line, the program will display the day plan by accessing the exact key in the dictionary.

Result

Choose Day Of The Week:Tuesday
On Tuesday You Have Meeting
python basic example 5 result

Video

Leave a Comment

Your email address will not be published. Required fields are marked *