Module 4: Conditions and Decisions in Python
Conditions and decisions are a crucial part of game development. You win a fight when your opponent’s health hits zero. You can carry items if you’re inventory isn’t full. There are a lot of similar decisions you have to include if you want a playable game. Today, we’ll look at how to create these decisions. We’ll also see how we can optimise our code to perform repetitive tasks using loops.
But first, here are the answers to the previous module.
Practice Question #1 Answer:
This is a sample.Continuing the message.
This is the end
Practice Question #2 Answer:
first_name=input("Enter your first name: ")
last_name=input("Enter your last name: ")
full_name=first_name+" "+last_name
print("Number of letters in your first name:",len(first_name))
print("Your full name with space:",full_name)
Practice Question #3 Answer:
Runtime error (name error)
Usually, an interpreter follows a single path of execution. What if you want to define multiple paths? For example, instead of choosing Path 1, it will select Path 2 if a condition is satisfied. This is why we use branching, grouping statements that execute based on a condition.
People often ask yes/no questions. The response to these is what’s called a Boolean value in Python. The bool data type represents a binary value of either True (1) or False (0). You can convert other data types to Boolean. The function for that is bool(). Any non-zero number or non-empty string becomes True, and 0 or an empty string becomes False.
print(bool(0))
print(bool("a"))
False
True
You will often need to compare multiple values and verify if a predefined condition is true. For this, Python provides six comparison operators:
- Equal to: ==
- Not equal to: !=
- Greater than: >
- Less than: <
- Greater than or equal to: >=
- Less than or equal to: <=
You often need a program to execute certain statements if a condition is satisfied. If not, it will execute another set of statements. A condition is an expression that evaluates to true or false. An if statement is a decision-making structure that contains a condition and a set of statements. If the condition is true, the body is executed. If false, the body is ignored. The body must be grouped and have one level (four spaces or one tab) of indentation.
If we want another set to be executed if the condition is false, we use an else statement. This cannot be used if we don’t have an if before it. It doesn’t have any condition to it; it just gets executed if the condition of the if block is not satisfied.
x=40
if x>30:
y=x-10
else:
y=x+10
print(y)
30
Decisions are often based on multiple conditions. For example, you may need to check if a is less than b and greater than c at the same time. A logical operator takes condition operands and produces True or False. There are three logical operators:
- and: This takes two condition operands and returns True if both conditions are true. Even if one condition is true and the other is false, it’ll return False.
- or: This will return True even if just one condition is true. Only when both are false will it return False.
- not: Unlike the previous two, this works on just one condition. It will return True if the condition is false, and vice versa.
We can also use elif statements for making decisions when there are multiple conditions. Take the following example:
score=int(input())
if score<70:
score+=10
if 70<=score<85:
score+=5
Here, if the input is between 60 and 69, both if statements get executed, and 15 gets added to the initial score. Chaining decision statements with elif allows the programmer to check for multiple conditions. An elif (else if) checks a condition when the previous decision statement’s condition is false. It always follows an if or another elif. An else always goes below all the elifs.
score=int(input())
if score<70:
score+=10
elif 70<=score<85:
score+=5
Suppose you are writing a program that reads in a game ID and player count and prints whether the user has the right number of players for the game. You may write:
if game==1 and players<2:
print("Not enough players")
if game==1 and players>4:
print("Too many players")
if game==1 and (2<=players<=4):
print("Ready to start")
if game==2 and players<3:
print("Not enough players")
if game==2 and players>6:
print("Too many players")
if game==2 and (3<=players<=6):
print("Ready to start")
But this is inefficient. It checks through all the if statements, which will make the program slower. This is where nested ifs come in. Taking the example of the above code, we can decide the game ID first, then check the number of players based on that. Nesting allows a decision statement to be inside another decision statement, and is indicated by an indentation level.
if game==1:
if players<2:
print("Not enough players")
elif players>4:
print("Too many players")
else:
print("Ready to start")
elif game==2:
if players<3:
print("Not enough players")
elif players>6:
print("Too many players")
else:
print("Ready to start")
A conditional expression is a simplified, single-line version of an if-else statement. A conditional expression is evaluated by first checking the condition. If condition is true, expression_if_true is evaluated, and the result is the resulting value of the conditional expression. Else, expression_if_false is evaluated, and the result is the resulting value of the conditional expression.
expression_if_true if condition else expression_if_false
Practice Question #!:
Write a program to calculate the grade of students based on their marks as follows:
A: 91-100
B: 81-90
C: 71-80
D: 61-70
E: 51-60
F: <=50
If you’ve played any idle games, you must have seen that the characters attack automatically. This is done with the help of loops. A loop is a code block that runs a set of statements while a given condition is true. It is used for performing repetitive tasks. We’ll learn about the for and while loops.
A while loop is a code construct that runs a set of statements, known as the loop body, while a given condition, known as the loop expression, is true. At each iteration, once the loop statement is executed, the loop expression is re-evaluated. If true, the loop body will execute at least one more time. If false, the loop’s execution will terminate, and the next statement after the loop body will execute.
i=10
while(i<20):
i+=1
A while loop can also be used to keep counts. A counter variable can be used in the loop expression to determine the number of iterations executed. In each iteration, the counter’s value is increased by one, and a condition can check whether the counter’s value is an even number or not. The change in the counter’s value in each iteration is called the step size. The step size can be any positive or negative value. If the step size is a positive number, the counter counts in ascending order, and if the step size is a negative number, the counter counts in descending order.
c=1
i=2
while(i<=20):
c+=1
i+=2
A container can be a range of numbers, a string of characters, or a list of values. To access objects within a container, an iterative loop can be designed to retrieve objects one at a time. A for loop iterates over all elements in a container. The range() function is a common way of implementing counting in a for loop. A range() function generates a sequence of integers between the two numbers, given a step size. This integer sequence is inclusive of the start and exclusive of the end of the sequence.
for i in range(2,50,3):
print("Hi")
Loops can be nested, too, just like decision blocks. The two loops are referred to as the outer loop and the inner loop. The outer loop controls the number of times the inner loop is fully executed. More than one inner loop can exist in a nested loop. Nested loops can be used for advanced counting, making patterns, and more.
for i in range(5):
for j in range(i):
print("*")
*
**
***
****
Practice Question #2:
Write a program to print the following pattern using nested for loops:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
A break statement is used within a loop to allow the program to exit the loop as soon as it is executed. It can be used to improve runtime efficiency when further loop execution is not required. On the other hand, a continue statement allows for skipping the execution of the remainder of the loop without exiting the loop entirely. After the continue statement’s execution, the loop expression will be re-evaluated, and the loop will continue from the loop expression.
A loop else statement runs after the loop’s execution is completed without being interrupted by a break statement. A loop else is used to identify if the loop is terminated normally or the execution is interrupted by a break statement. For example, this:
numbers=[2,5,7,11,12]
for i in numbers:
if i==10:
print("Found 10!")
break
else:
print("10 is not in the list.")
Is the same as:
numbers=[2,5,7,11,12]
seen=False
for i in numbers:
if i==10:
print("Found 10!")
seen=True
if seen==False:
print("10 is not in the list.")
Previously, we went through the basics of strings. Let’s study them in more detail. As we know, a string is a sequence of characters. Python provides many functions to process strings. You can compare strings by using logical operators. For example, > checks if the ASCII value of the first string is greater than that of the second. in checks if the second string contains the first string. And, not in checks for the reverse.
To convert all the characters of a string to uppercase, we use upper(). To make them lowercase, we can use lower() instead. You can also slice strings. We’ve seen that a string can be indexed from both left to right and right to left. Slicing is used when you want access to a sequence of characters. Here, a string slicing operator can be used. When [a:b] is used with the name of a string variable, a sequence of characters starting from index a (inclusive) up to index b (exclusive) is returned. Both a and b are optional. If a or b is not provided, the default values are 0 and len(string), respectively.
print(upper("hello"))
print(lower("HELLO"))
time="13:46"
minutes=time[3:5]
print(minutes)
HELLO
hello
46
The count() method counts how many times a substring occurs in a string. If it doesn’t exist, 0 is returned. The find() method returns the index of the first occurrence of a substring in a given string. If the substring does not exist in the given string, the value of -1 is returned.
print("aaa".count("a"))
print("banana".find("a"))
3
1
A string can be broken into parts using a delimiter or a separator. The split() function does exactly that.. In case no delimiters are provided, blank spaces are used as delimiters. Contrary to that is the join() function, which concatenates substrings to form one string separated by delimiters.
Let’s end here today. We’ll learn about functions and lists in the next module. Make sure you try the practice questions and ask in the comments if you have any doubts.
Discover more from Ge-erdy Verse
Subscribe to get the latest posts sent to your email.
June 12, 2025 @ 1:13 am
Nice post. I learn something totally new and challenging on websites
June 12, 2025 @ 8:16 am
Thanks a lot, we’ll keep making posts like this so stay tuned!