![](https://bartek.dk/wp-content/uploads/2024/05/If-1024x585.jpg)
Musical Intro
Introduction
In programming, if
statements help in decision-making by performing different actions based on different inputs.
Now you need to make a choice, how you want to learn it:
- You can use AI to teach you about the different operators. Then you can learn, by your own exploration and in any programming language (scroll down to Using AI)
- You can use the result I got, from using AI. Then you can rely on my experience to filter it.(keep on reading)
- You can also do both in any order :-)
Single-line if Statements
Single-line if
statements provide a concise way to execute a single action based on a condition. They are particularly useful when you want to simplify your code for simple condition checks.
It is written in Python, but you can use AI to translate it to other languages.
# Given a temperature value and dayIsHot is set
temperature = 26
dayIsHot = False
# When checking if the temperature is above 25 degrees
if temperature > 25:
dayIsHot = True # Note: Python boolean should be 'True' with uppercase 'T'
# Then, print and assert that the day is hot
print(f"Day is hot? {dayIsHot}")
assert dayIsHot == True
The result will be:
![](https://bartek.dk/wp-content/uploads/2024/05/image-24.png)
and when we change the temperature to 25:
![](https://bartek.dk/wp-content/uploads/2024/05/image-25.png)
Then it is not hot, and the assertion fails, because we expected it to be hot :-)
Challenge
# given a number
number = 10
isLarger = False
# when checking if the number is larger than 9
# <write your code here>
# then the output should state that the number is larger than 9
print(f"number is larger than 9? {isLarger}")
assert isLarger== True
Result
# given a number
number = 10
isLarger = False
# when checking if the number is larger than 9
if(number > 9): isLarger = True
# then the output should state that the number is larger than 9
print(f"number is larger than 9? {isLarger}")
assert isLarger== True
Nested if statements
In Python, “nested if statements” refer to the practice of placing one if
statement inside another. This allows for more complex decision-making processes by checking for further conditions after a previous condition has already been met.
x=11
y=10
if x > 10:
if y > 10:
print("Both x and y are greater than 10")
else:
print("x is greater than 10, but y is not")
else:
print("x is not greater than 10")
![](https://bartek.dk/wp-content/uploads/2024/05/image-27.png)
Challenge
# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"
# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'
# <write your code here>
# Then output must be "It's a hot sunny day."
print(f"{result}")
# set the temperature to 30 and weatherCondition to "Sunny" to see a different result
# set the temperature to 31 and weatherCondition to "Rainy" to see a 3rd result
# set the temperature to 30 and weatherCondition to "Rainy" to see a 4th result
Result
# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"
# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'
if temperature>30:
if weatherCondition=="Sunny":
result = "It's a hot sunny day."
else:
result = "It's a hot rainy day."
else:
if weatherCondition=="Sunny":
result = "It's a cold sunny day."
else:
result = "It's a cold rainy day."
# Then output must be "It's a hot sunny day."
print(f"{result}")
# set the temperature to 30 and weatherCondition to "Sunny" to see a different result
# set the temperature to 31 and weatherCondition to "Rainy" to see a 3rd result
# set the temperature to 30 and weatherCondition to "Rainy" to see a 4th result
if statements with logical operators
In Python, “if statements with logical operators” refer to using if
statements combined with logical operators (and
, or
, not
) to test multiple conditions at once. For example:
x = 2
if x >= 1 and x <= 9:
print("x is between 1 and 9")
else:
print("x is below 1 or above 9")
And the result will be:
![](https://bartek.dk/wp-content/uploads/2024/05/image-26.png)
“and” means both statements need to be true.
x=2
# the following statement:
if x>=1 and x<=9:
print("x is between 1 and 9")
# could be written as:
if x>=1:
if x<=9:
print("x is between 1 and 9")
“or” means one of the statements need to be true.
x=3
# the following statement:
if x==1 or x==3:
print("x is either 1 or 3")
# could be written as:
if x==1:
print("x is either 1 or 3")
if x==3:
print("x is either 1 or 3")
Challenge
# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"
# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'
# <write your code here>
# Then output must be "It's a hot sunny day."
print(f"{result}")
assert result == "It's a hot sunny day."
Result
# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"
# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'
if temperature>30 and weatherCondition == "Sunny":
result = "It's a hot sunny day."
# Then output must be "It's a hot sunny day."
print(f"{result}")
assert result == "It's a hot sunny day."
if-else one-liner (Ternary Operator)
This operator is typically used to assign a value to a variable based on a condition.
# if you change the score value to 75, then you will get a different result.
score = 76
result = "High" if score > 75 else "Low"
print(result)
assert result == "High"
![](https://bartek.dk/wp-content/uploads/2024/05/image-28.png)
Challenge
# Given a variable 'age' 'adult' are set to 18 and None
age = 18
adult = None
# When determining if the age qualifies someone as an adult
# <write you code here>
# Then print the age and adult result, and assert the adult result
print(f"age: {age}, adult: {adult}")
assert adult == True
Result
# Given a variable 'age' 'adult' are set to 18 and None
age = 18
adult = None
# When determining if the age qualifies someone as an adult
adult = True if age>=18 else False
# Then print the age and adult result, and assert the adult result
print(f"age: {age}, adult: {adult}")
assert adult == True
Pass statement
In Python, the pass
statement is a null operation — when it is executed, nothing happens. It is often used as a placeholder to ensure the syntax of your code is correct, allowing you to maintain the structural integrity of the code while you’re still thinking about the logic or implementing it later.
x = 2
if x>1:
pass # passholder for future code
else:
x+=1
print(f"x is {x}")
assert x==2
In other programming languages, we could just have written a comment.
We can’t do that in Python, because the line after an if statement, needs to be indent, while the else can’t be it. So we need to write pass with an indent.
Challenge
# Given we have a variable price with value 50
price = 50
# When the price is above 40, then we want to make a pass-statement as a placeholder for future code. Else the price must be increased by 10%
if price >40:
# <insert your code here>
else:
price *=1.1
# Then we print and assert the price
print(f"Price: {price}")
assert price==50
Result
# Given we have a variable price with value 50
price = 50
# When the price is above 40, then we want to make a pass-statement as a placeholder for future code. Else the price must be increased by 10%
if price >40:
pass
else:
price *=1.1
# Then we print and assert the price
print(f"Price: {price}")
assert price==50
Conclusion
Today, we embarked on an enlightening journey through various Python programming constructs, those crucial components that guide the flow and decisions within our scripts.
We began by examining single-line if statements, a concise method for executing actions based on conditions. This exploration allowed us to efficiently manage simple checks within our code, reinforcing the ease of conditional programming.
Transitioning to nested if statements, we delved into the realm of complex decision-making. Here, we learned to layer conditions within one another, enhancing our ability to handle more intricate logical sequences based on multiple criteria.
We then ventured into the use of logical operators within if statements, including ‘and’, ‘or’, and ‘not’. This exploration enabled us to evaluate multiple conditions simultaneously, streamlining our code for more sophisticated decision-making processes.
To improve code conciseness and readability, we embraced the if-else ternary operator. This powerful one-liner allowed us to assign values conditionally in a single, elegant statement, further simplifying our conditional assignments.
Delving deeper, we explored the pass statement, a unique Python feature that acts as a placeholder. By using the pass statement, we maintained the structural integrity of our code during the initial stages of development, ensuring that our scripts remained syntactically correct even when specific logic was not yet implemented.
Armed with these skills, we’re better equipped to tackle a wide array of programming tasks and navigate the complex landscape of software development with confidence.
Using AI
All this have been created with the cooperation with AI.
Often it can be more useful just to learn, what is needed in the moment, than to learn everything about a topic. This is where AI is perfect.
We can use the free ChatGPT 3.5 to learn about operators. You are welcome to try other and if you do, please write a comment!
Essential prompts can be:
When we don’t know the name of what we want to learn, then we can ask AI about it:
What is an if statement in Python?
![](https://bartek.dk/wp-content/uploads/2024/05/image-12.png)
![](https://bartek.dk/wp-content/uploads/2024/05/image-11.png)
When we want to learn more about the topic
Are there other types of if-statements in Python?
![](https://bartek.dk/wp-content/uploads/2024/05/image-13.png)
![](https://bartek.dk/wp-content/uploads/2024/05/image-14.png)
You can ask the same question twice and get more results:
are there other?
![](https://bartek.dk/wp-content/uploads/2024/05/image-15.png)
![](https://bartek.dk/wp-content/uploads/2024/05/image-16.png)
Then you can explore each subject with:
I would like to learn more about "if statements with logical operators".
Can you show me:
1. an example of how it works? (in python)
2. a real world application of it? (in python)
I want the code examples to be written with given, when, and then steps.
The then step needs to contain a print and assert (for manual and automatic verification).
![](https://bartek.dk/wp-content/uploads/2024/05/image-17.png)
![](https://bartek.dk/wp-content/uploads/2024/05/image-18.png)
To get an assignment to learn from:
I would like to learn more about "if statements with logical operators".
Can you make a assignment for me to solve?
The assignment needs to be written in Python as comments.
Use only given, when, and then comments. No code.
![](https://bartek.dk/wp-content/uploads/2024/05/image-19.png)
And sometimes you might need to start a new session.
Sometimes the AI makes a mistake like writing Given, Then, When (wrong order) and sometimes starting a new session makes it go away.
And you can get AI to solve it for you:
Can you please solve this assignment for me in Python code?
![](https://bartek.dk/wp-content/uploads/2024/05/image-20.png)
To be sure it works, you can always copy the code into your editor and see if it works!
Web editor: 💻 Python / 💻 JavaScript / 💻 Groovy / 💻 C#
![](https://bartek.dk/wp-content/uploads/2024/05/image-21.png)
And to make sure it works, we can change one of the variables like age, to see if we get one of the other options:
![](https://bartek.dk/wp-content/uploads/2024/05/image-22.png)
Yay! It works!
You can ask for a new assignment – as many times as you want.
You can make the AI solve it for you.
You can make the AI help you solve it.
You can solve it yourself.
Limitless learning with a 24/7 tutor!!!
Bonus!
You can write most code with Given, When, and Then comments and make the AI translate it for you into working code!
You will still need to understand programming, because you need to use the Given, When, and Then as regular code. You just don’t have to learn a programming language to run on a specific hardware or platform, like a phone or in a browser.
Coding is not going away :-)
Congratulations – Lesson complete!
![](https://bartek.dk/wp-content/uploads/2024/03/image-84.jpg)
Want more?
Check out the comments on Linked.