Python Beginners – Combine Everything

python logo - Python Beginners - Combine Everything
python logo

Python Beginners – Combine Everything; in this beginner’s series, we have covered print, taking input, selection, lists and looping and logic. Following on from these, this post is the finale, and we will look at some of the possibilities with the tools now at your disposal. These examples will combine the learning from this series’s previous posts. There is a video version of this tutorial at the bottom of the post or available here.

Continuous Input – Specific Number of Times – Python Beginners – Combine Everything

Initial Program

Ask the user for a name 5 times and then print the results.

listNames = []
for number in range(5):
    listNames.append(input("Please enter a name"))
print(listNames)

Breaking It Down

  • Declare a variable called ‘listNames’ and assign an empty list.
  • Create a loop by looping through the integers 0,1,2,3,4. For each integer, do something.
    • Take a user input.
    • Append the input to the list stored in ‘listNames’.
    • Return to the top until the range is all done.
  • Output the contents of ‘listNames’ to the console.

Expanded Code

In the code below, I have introduced code comments. Anything after a ‘#’ is ignored by the compiler as a comment to help the programmer and not part of the code.

listNames = None
#  Declare a variable called 'listNames'

listNames = []
#  Assign an empty list to the variable 'listNames'

# loop through the numbers zero to 4 inclusives
for number in range(5):
    userInput = None
    #  Declare a variable called 'userInput'

    userInput = input("Please enter a name")
    #  Take user input and assign it to the variable 'userInput'

    listNames.append(userInput)
    #  Append the value in 'userInput to the list 'listNames'

print(listNames)
#  Output the content of 'listNames' to the console.

Continuous Input – User-controlled – Python Beginners – Combine Everything

Initial Program – Can you work out how this works?

Ask the user for a name, add it to a list, and then ask if they want to give more names. If they do, then retake user input.

listNames = []
boolTakeNames = True
print("You are going  to be asked to enter a list of names.")
while boolTakeNames:
    listNames.append(input("Please enter a name"))
    boolTakeNames = input("Add another name?  (y/n)") == "y"
print("Thank you, your list of names is:", listNames)

Breaking It Down

The first three lines are hopefully self-explanatory.

  • Declare a variable called ‘listNames’ and assign an empty list to the variable.
  • Declare a variable called ‘boolTakeNames’ and assign a True boolean value to the variable.
  • Output text to the screen using the ‘print’ statement.

Next, let us look at the while loop. It starts by saying “Keep Doing this” while the variable ‘boolTakeNames’ is True.

We can expand this code to clarify all the steps inside the while loop code block (the indented code).

  • Line 5: Takes input from the user, then appends the input to the end of the list stored in the variable ‘listNames’.
  • Line 6: Takes input from the user, then:
    • Makes a statement user input is exactly the same as the lowercase character ‘y’
    • Checks if that statement is True or False, then stores it in the variable ‘boolTakeNames’.

Expanded Code

listNames = None
# define the variable 'listNames'

listNames = []
# assign an empty list to the variable 'listNames'

boolTakeNames = None
# define the variable 'boolTakeNames'

boolTakeNames = True
# assign the value True to the variable 'boolTakeNames'

print("You are going  to be asked to enter a list of names.")
# Output the string to the console

while boolTakeNames:  # While boolTakeNames is True
    userInput = None
    # Declare a variable called 'userInput'

    userInput = input("Please enter a name")
    # Take user input and assign it to 'userInput'

    listNames.append(userInput)
    # Append the contents of 'userInput' to the end of the list in 'listNames'

    yesNo = None
    # Declare the variable 'yesNo'

    yesNo = input("Add another name?  (y/n)")
    # Ask user for y/n and assign it to 'yesNo'

    boolTakeNames = bool(yesNo == "y")
    # statement yesNo is exactly the same as the character 'y'

    # true or false. loop back and check condition at the top of the while loop again
    # is boolTakeNames True?

print("Thank you, your list of names is:", listNames)
# Output the list of names to the console.

Expand And Include Selection – Python Beginners – Combine Everything

In this example, we take the basis of continuous selection from above. However, it has four lists of names instead of one. Finally, each list will hold names for a specific age group.

  • Declare 4 variables and assign empty lists to them.
  • Declare a boolean variable and assign True.
  • Output a message telling the user what is going to happen
  • Declare a while loop with the condition that it runs while the bool ‘boolTakeNames’ is True
    • Ask the user for a name and assign it to a variable.
    • Ask the user for their age and assign it to a variable.
      • Add the user’s name to the appropriate list based on their age.
      • If the age is 3 or less, assign to preschool.
      • Else if the age is less or less, assign it to school age.
      • Else if the age is less than 66, assign it to work age.
      • Else assign to pension age
    • Ask the user if they want to add another name.
    • Assign the bool ‘boolTakeNames’ based on the response
    • Loop back to the top of the loop to check the conditional.
  • output all four lists using print statements

Program

The code below nests if/elif/else blocks inside the while loop. Notice how the is a second indent level.

listPreSchool = []
listSchoolAge = []
listWorkAge = []
listPensionAge = []
boolTakeNames = True
print("You are going  to be asked to enter a list of names.")
while boolTakeNames:
    inputName = input("Please enter a name")
    inputAge = int(input("Please enter " + inputName + "'s age"))
    if inputAge < 4:
        listPreSchool.append(inputName)
    elif inputAge < 19:
        listSchoolAge.append(inputName)
    elif inputAge < 65:
        listWorkAge.append(inputName)
    else:
        listPensionAge.append(inputName)
    boolTakeNames = input("Add another name? (y/n)") == "y"

print("PreSchool List:", listPreSchool)
print("School Age List:", listSchoolAge)
print("Work Age List:", listWorkAge)
print("Pensioner List:", listPensionAge)

Include ‘AND’ Logic – Expand Things Further – Python Beginners – Combine Everything

What if we wanted a list of pensioners called ‘Mark’? There are two possible approaches. Firstly, If pensioners called Mark should be in both the pensioner list and a new list; all that is needed is one more if statement.

Pensioners Called Mark in Both Lists

The code below adds another level of nesting. There is an if statement nested inside and an else block, which is, in turn, nested inside a while loop.

listPreSchool = []
listSchoolAge = []
listWorkAge = []
listPensionAge = []
listPensionMark = []
boolTakeNames = True
print("You are going  to be asked to enter a list of names.")
while boolTakeNames:
    inputName = input("Please enter a name")
    inputAge = int(input("Please enter " + inputName + "'s age"))
    if inputAge < 4:
        listPreSchool.append(inputName)
    elif inputAge < 19:
        listSchoolAge.append(inputName)
    elif inputAge < 65:
        listWorkAge.append(inputName)
    else:
        listPensionAge.append(inputName)
        if inputName == "Mark":
            listPensionMark.append(inputName)
    boolTakeNames = input("Add another name? (y/n)") == "y"

print("PreSchool List:", listPreSchool)
print("School Age List:", listSchoolAge)
print("Work Age List:", listWorkAge)
print("Pensioner List:", listPensionAge)

However, if we do not want them in both lists, it requires adding an else block or adjusting the elif to use AND.

Pensioners Called Mark Separate Lists

Add an else block to the nested if statement.

listPreSchool = []
listSchoolAge = []
listWorkAge = []
listPensionAge = []
listPensionMark = []
boolTakeNames = True
print("You are going  to be asked to enter a list of names.")
while boolTakeNames:
    inputName = input("Please enter a name")
    inputAge = int(input("Please enter " + inputName + "'s age"))
    if inputAge < 4:
        listPreSchool.append(inputName)
    elif inputAge < 19:
        listSchoolAge.append(inputName)
    elif inputAge < 65:
        listWorkAge.append(inputName)
    else:
        if inputName == "Mark":
            listPensionMark.append(inputName)
        else:
            listPensionAge.append(inputName)
    boolTakeNames = input("Add another name? (y/n)") == "y"

print("PreSchool List:", listPreSchool)
print("School Age List:", listSchoolAge)
print("Work Age List:", listWorkAge)
print("Pensioner List:", listPensionAge)

Use AND Logic

The code below gets rid of the second level nested if/else. Instead, it adds another elif that checks to see if the age is greater than or equal to 65, and their name is Mark. If both conditions are met, then they are added to listPensionMark. Otherwise, it drops to the else statement, and they are added to listPensionAge.

listPreSchool = []
listSchoolAge = []
listWorkAge = []
listPensionAge = []
listPensionMark = []
boolTakeNames = True
print("You are going  to be asked to enter a list of names.")
while boolTakeNames:
    inputName = input("Please enter a name")
    inputAge = int(input("Please enter " + inputName + "'s age"))
    if inputAge < 4:
        listPreSchool.append(inputName)
    elif inputAge < 19:
        listSchoolAge.append(inputName)
    elif inputAge < 65:
        listWorkAge.append(inputName)
    elif inputAge >= 65 and inputName == "Mark":
        listPensionMark.append(inputName)
    else:
        listPensionAge.append(inputName)       
    boolTakeNames = input("Add another name? (y/n)") == "y"

print("PreSchool List:", listPreSchool)
print("School Age List:", listSchoolAge)
print("Work Age List:", listWorkAge)
print("Pensioner List:", listPensionAge)

Video Version

Tutorial Video

Related Articles – Python Beginners – Combine Everything

Final Thoughts

The Python Beginners Series is now complete. There is a lot more that could have been included and a lot more still to learn in Python. It is my hope that between the written version and the video version of these tutorials, everyone will find something useful. There are a lot of reference guides out there for programming. I hope this series provides a little more structure and explanation. I will be doing an intermediate-level series at some point in the future. However, there will be a similar beginner’s series for C# and C++ before then.

Related Post

7 thoughts on “Python Beginners – Combine Everything

Leave a Reply

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