## 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:

1. 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)
2. You can use the result I got, from using AI. Then you can rely on my experience to filter it.(keep on reading)
3. 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.

Python
``````# 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:

and when we change the temperature to 25:

Then it is not hot, and the assertion fails, because we expected it to be hot :-)

### Challenge

Python
``````# given a number
number = 10
isLarger = False

# when checking if the number is larger than 9

# then the output should state that the number is larger than 9
print(f"number is larger than 9? {isLarger}")
assert isLarger== True``````
Result
Python
``````# 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.

Python
``````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")``````

### Challenge

Python
``````# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"

# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'

# 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
Python
``````# 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:

Python
``````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:

and” means both statements need to be true.

Python
``````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.

Python
``````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

Python
``````# Given variables 'temperature' and 'weatherCondition'
temperature = 31
weatherCondition = "Sunny"
result = "not yet set"

# When 'temperature' is above 30 degrees and 'weather_condition' is 'Sunny'

# Then output must be "It's a hot sunny day."
print(f"{result}")
assert result == "It's a hot sunny day."``````
Result
Python
``````# 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.

Python
``````# 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"``````

### Challenge

Python
``````# Given a variable 'age' 'adult' are set to 18 and None
age = 18

# 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
Result
Python
``````# Given a variable 'age' 'adult' are set to 18 and None
age = 18

# 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

## 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.

Python
``````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

Python
``````# 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:
else:
price *=1.1

# Then we print and assert the price
print(f"Price: {price}")
assert price==50``````
Result
Python
``````# 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?``

``Are there other types of if-statements in Python?``

### You can ask the same question twice and get more results:

``are there other?``

### 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).``````

### 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.``````

### 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?``

### 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#

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:

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 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 :-)

## Introduction

In programming, operators are symbols that perform operations like mathematical calculations.

Now you need to make a choice, how you want to learn it:

1. 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)
2. You can use the result I got, from using AI. Then you can rely on my experience to filter it.(keep on reading)
3. You can also do both in any order :-)

## Arithmetic operators: + , – , * , / , // , %

Arithmetic operators are used to perform mathematical operations on numerical values.

It is written in Python, but you can use AI to translate it to other languages.

Python
``````# Given two numbers
num1 = 10
num2 = 3

# When using arithmetic operators
subtraction = num1 - num2
multiplication = num1 * num2
division = num1 / num2
divisionRoundDown num1 // num2
modulus = num1 % num2  # Returns the remainder of the division

# Then the results should be as expected

print(f"Subtraction: {subtraction}")
assert subtraction== 10-3

print(f"Multiplication: {multiplication}")
assert multiplication== 10*3

print(f"Division: {division}")
assert division == 10/3

print(f"divisionRoundDown: {divisionRoundDown}")
assert divisionRoundDown== 10//3 # is 3.333... rounded down is 3

print(f"Modulus: {modulus}")
assert modulus== 10%3 # 10 will be split into three 3's and 1 will remain ``````

The result will be:

In case you wonder over why 10/3 equals 3.3333333333333335, it is because of a floating error (lack of precision). We will go into it on a later stage.

### Challenge

Python
``````# given we want to arrange team activities for attendies
menAttendees = 27
womenAttendees = 25
childrenAttendees = 11
groupSize = 5

# when we calculate the number of total attendees
totalAttendees = # please fill this out

# then it must match the expected result
print(f"Total attendees: {totalAttendees}")
assert totalAttendees == 63

# when we calculate the number of groups
numbeOfGroups = # please fill this out

# then it must match the expected result
print(f"Number of groups: {numbeOfGroups}")
assert numbeOfGroups == 12

# when we calculate the number of people without a groups
attendeesWithoutAGroup = # please fill this out

# then it must match the expected result
print(f"Attendeeswithout a group: {attendeesWithoutAGroup}")
assert attendeesWithoutAGroup == 3

print("All calculations are correct!")``````
Hint

use + for totalAttendees
use // for numberOfGroups
use % for attendeesWithoutAGroup

Result
Python
``````# when we calculate the number of total attendees
totalAttendees = menAttendees + womenAttendees + childrenAttendees

# when we calculate the number of groups
numbeOfGroups = totalAttendees // groupSize

# when we calculate the number of people without a groups
attendeesWithoutAGroup = totalAttendees % groupSize
``````

## Assignment Operators: = (and not ==)

When we use = then we assign a value to a variable.
When we use == then we verify if something is equal or not. The result is either true or false

Python
``````# When we assign three values to three variables with an =
a = 1
b = 1
c = 2

# Then we can verify the values with an ==
print(a==b)
print(a==c)``````

And the result will be:

### Challenge

Python
``````# please fix the followin code, so it works
a = 1
b == 1

assert a=b
print("you did it!")``````
Hint

look for = where we need to assign a value
look for == where we need to verify a value

Result
Python
``````# please fix the followin code, so it works
a = 1
b = 1

assert a==b
print("you did it!")``````

## Comparison operators: == , > , >= , <= , < , !=

We can also verify other than just equal

Python
``````print("greater than >")
print(f"4>3 -> {4>3}")
print(f"3>3 -> {3>3}")

print("----")
print("greater equal than >=")
print(f"4>=3 -> {4>=3}")
print(f"3>=3 -> {3>=3}")
print(f"2>=3 -> {2>=3}")

print("----")
print("lesser equal than <=")
print(f"4<=3 -> {4<=3}")
print(f"3<=3 -> {3<=3}")
print(f"2<=3 -> {2<=3}")

print("----")
print("lesser than <")
print(f"3<3 -> {3<3}")
print(f"2<3 -> {2<3}")

print("----")
print("not equal !=")
print(f"3!=4 -> {3!=4}")
print(f"3!=3 -> {3!=3}")
print(f"4!=3 -> {4!=3}")``````

### Challenge

Python
``````# please fix the followin code, so it works
assert 3>4
assert 4<4
assert 5<4
assert 5=="abc"
print("you did it!")``````
Hint

use >, <, ==, and !=

Result
Python
``````# please fix the followin code, so it works
assert 3<4
assert 4==4
assert 5>4
assert 5!="abc"
print("you did it!")``````

## Compound assignment operators: += , -= , *= , /=

To make code shorter, we can use:

Python
``````# When we have a number variable
number = 1
print(number)

# Then we want to increase a number by 3 we can write:
number = number + 3
print(number)
assert number == 4

# Or
number += 3
print(number)
assert number == 7``````
Python
``````# When we have a number variable
number = 5
print(number)

# Then we want to decrease a number by 3 we can write:
number = number - 3
print(number)
assert number == 2

# Or
number -= 3
print(number)
assert number == -1``````
Python
``````# When we have a number variable
number = 1
print(number)

# Then we want to multiply a number by 3 we can write:
number = number * 3
print(number)
assert number == 3

# Or
number *= 3
print(number)
assert number == 9``````
Python
``````# When we have a number variable
number = 8
print(number)

# Then we want to multiply a number by 2 we can write:
number = number / 2
print(number)
assert number == 4

# Or
number /= 2
print(number)
assert number == 2``````

### Challenge

Python
``````# refactor the following code to use +=, -=, *=, /=
number1 = 3

number1 = number1 + 3
number1 = number1 - 2
number1 = number1 * 3
number1 = number1 / 2

assert number1 == 6
print("you did it!")``````
Result
Python
``````# refactor the following code to use +=, -=, *=, /=
number1 = 3

number1 += 3
number1 -= 2
number1 *= 3
number1 /= 2

assert number1 == 6
print("you did it!")``````

## Rounding operators: round, flour, celling

A number can be rounded to a specific decimal by using a Math library:

Python
``````# given we have a number variable
number1 = 1.4999999
number2 = 1.5000000

# when we round it in multiple ways:
roundedDown = round(number1)
roundedUp = round(number2)

# then it will be rounded up or down, based on if it's half way or not.
print(f"roundedDown: {number1}->{roundedDown}")
assert roundedDown == 1

print(f"roundedUp:   {number2}->{roundedUp}")
assert roundedUp == 2``````

To always round down we can use math.floor():

Python
``````import math

# given we have a number variable
number1 = 1.0000000
number2 = 1.9999999
number3 = 2.0000000

# when we round it in multiple ways:
floor1 = math.floor(number1)
floor2 = math.floor(number2)
floor3 = math.floor(number3)

# then it will be rounded up or down, based on if it's half way or not.
print(f" {number1}-> {floor1}")
assert floor1 == 1

print(f" {number2}-> {floor2}")
assert floor2 == 1

print(f" {number3}-> {floor3}")
assert floor3 == 2``````

To always round down we can use math.ceil():

Python
``````import math

# given we have a number variable
number1 = 1.0000000
number2 = 1.0000001
number3 = 1.9999999

# when we round it in multiple ways:
floor1 = math.ceil(number1)
floor2 = math.ceil(number2)
floor3 = math.ceil(number3)

# then it will be rounded up or down, based on if it's half way or not.
print(f" {number1}-> {floor1}")
assert floor1 == 1

print(f" {number2}-> {floor2}")
assert floor2 == 2

print(f" {number3}-> {floor3}")
assert floor3 == 2``````

### Challenge

Python
``````import math

# given you have the following numbers
number1a = # insert a correct value here
number1b = # insert a correct value here
number2a = # insert a correct value here
number2b = # insert a correct value here
number3a = # insert a correct value here
number3b = # insert a correct value here

# when you apply math.round math.floor, and math.ceil:
rounded1a = math.round(number1a)
rounded1b = math.round(number1b)
rounded2a = math.floor(number2a)
rounded2b = math.floor(number2b)
rounded3a = math.ceil(number3a)
rounded3b = math.ceil(number3b)

# then you must get the expected values
assert rounded1a == 1, f"{number1a} -> {rounded1a}"
assert rounded1b == 2, f"{number1b} -> {rounded1b}"
assert rounded2a == 3, f"{number2a} -> {rounded2a}"
assert rounded2b == 4, f"{number2b} -> {rounded2b}"
assert rounded3a == 5, f"{number3a} -> {rounded3a}"
assert rounded3b == 6, f"{number3b} -> {rounded3b}"

print("you did it!")``````
Result
Python
``````import math

# given you have the following numbers
number1a = 1.499999
number1b = 1.500000
number2a = 3.999999
number2b = 4.000000
number3a = 5.000000
number3b = 5.000001

# when you apply math.round math.floor, and math.ceil:
rounded1a = math.round(number1a)
rounded1b = math.round(number1b)
rounded2a = math.floor(number2a)
rounded2b = math.floor(number2b)
rounded3a = math.ceil(number3a)
rounded3b = math.ceil(number3b)

# then you must get the expected values
assert rounded1a == 1, f"{number1a} -> {rounded1a}"
assert rounded1b == 2, f"{number1b} -> {rounded1b}"
assert rounded2a == 3, f"{number2a} -> {rounded2a}"
assert rounded2b == 4, f"{number2b} -> {rounded2b}"
assert rounded3a == 5, f"{number3a} -> {rounded3a}"
assert rounded3b == 6, f"{number3b} -> {rounded3b}"

print("you did it!")``````

## Exponentiation operators: 2Β³ , pow(2,3) , 2**3 , β9 , sqrt(9) , 9**.5

If we want write 3Β², which is 3*3 = 9
or 2Β³, which is 2*2*2 = 8

We can do that with math.pow()

Python
``````import math

# when we user mat.pow() method
number1 = math.pow(2,3)
number2 = math.pow(3,2)

# and the ** can also be user
number3 = 2**3

# then we can see the power of the values
print(f" pow(2,3) = 2*2*2 -> {number1}")
assert number1 == 8

print(f" pow(3,2) = 3*3 -> {number2}")
assert number2 == 9

print(f" 2**3 = 2*2*2 -> {number3}")
assert number3 == 8
``````

when we want the opposite of power we can either use math.sqrt() (square root) or fractions in math,pow()

Python
``````import math

# when we user math.sqrt() method
number1 = math.sqrt(9)

# and we can use the math.power() with fractions
number2 = math.pow(9, 1/2)

# and we can use the math.power() with fractions
number3 = 9**(1/2)

# then we can see the power of the values
print(f" sqrt(9) -> {number1}")
assert number1 == 3

print(f" pow(9, 1/2) -> {number2}")
assert number2 == 3

print(f" 9**(1/2) -> {number3}")
assert number3 == 3
``````

### Challenge

Python
``````import math

# change the numbers to make the math work:
result1 = math.pow(1,1)
result2 = math.sqrt(4)
result3 = 1**2
result4 = 4**(1/2)
result5 = 9**(.5)

# then you must get the expected values
assert result1 == 25, f"{result1} != 25"
assert result2 == 4, f"{result1} != 4"
assert result3 == 16, f"{result1} -!= 16"
assert result4 == 6, f"{result1} != 6"
assert result5 == 8, f"{result1} != 8"

print("you did it!")``````
Result
Python
``````import math

# change the numbers to make the math work:
result1 = math.pow(5,2)
result2 = math.sqrt(16)
result3 = 2**4
result4 = 36**(1/2)
result5 = 64**(.5)

# then you must get the expected values
assert result1 == 25, f"{result1} != 25"
assert result2 == 4, f"{result1} != 4"
assert result3 == 16, f"{result1} -!= 16"
assert result4 == 6, f"{result1} != 6"
assert result5 == 8, f"{result1} != 8"

print("you did it!")``````

## Logical operators: & , |

& and | is more about logic.

3 == 3 gives true, while 3==4 gives false

we can combine the the output with & and | operators.

Beware that in Python it is True and False, with UPPER CASE
In Groovy, JavaScript and C# it is true an false with lower case
In other languages it can be TRUE and FALSE.

The following gives an overview. It will make more sense with if-statements, that will come in a later lesson..

Python
``````print("and &")
print(f"True & True   -> {True & True}")
print(f"True & False  -> {True & False}")
print(f"False & True  -> {False & True}")
print(f"False & False -> {False & False}")

print("----")
print("and |")
print(f"True | True   -> {True | True}")
print(f"True | False  -> {True | False}")
print(f"False | True  -> {False | True}")
print(f"False | False -> {False | False}")``````

True and false can also be written as 1 (true) and 0 (false)

Python
``````print("and &")
print(f"1 & 1 -> {1 & 1}")
print(f"1 & 0 -> {1 & 0}")
print(f"0 & 1 -> {0 & 1}")
print(f"0 & 0 -> {0 & 0}")

print("----")
print("and |")
print(f"1 | 1 -> {1 | 1}")
print(f"1 | 0 -> {1 | 0}")
print(f"0 | 1 -> {0 | 1}")
print(f"0 | 0 -> {0 | 0}")``````

## Data consistency operators: Math.abs()

Math.abs() makes all values positive.

Python
``````import math
print(-5)
print(math.abs(-5))
print(math.abs(5))
print(5)``````

### Challenge

Python
``````import math

# given you have the following values
number1 = -2
number2 = -3

# when you add them together correctly
result = number1 + number2

# then you must get the expected values
assert number1 == -2, f"number1 must be -2, but is {number1}"
assert number2 == -3, f"number1 must be -3, but is {number2}"
assert result == 5, f"result must be 5, but is {result}"

print("you did it!")``````
Hint

Remember that math.abs(-3) is 3

Result
Python
``````# when you add them together correctly
result = math.abs(number1) + math.abs(number2)``````

There are many other operators like: `sin()`, `cos()`, `tan()`, `asin()`, `acos()`, `atan()`, `atan2()`, `log()`, `log10()`, `log2()`, `mean()`, `median()`, `variance()`, `std()`, etc.

We will cover these in a later lesson.

## Conclusion

Today, we embarked on an adventurous journey into the realm of operators, those magical symbols that enable us to manipulate data in programming.

We began by mastering arithmetic operators like addition, subtraction, multiplication, division, and modulus, empowering us to perform fundamental mathematical calculations effortlessly.

Transitioning to assignment operators, we learned to assign values to variables with “=“, and verify equality with “==“, streamlining our code for efficient data management.

We then ventured into comparison operators, including greater than (>), greater than or equal to (>=), lesser than (<), lesser than or equal to (<=), and not equal (!=), enabling us to make logical decisions based on variable comparisons.

To enhance code readability and efficiency, we embraced compound assignment operators like increment (+=), decrement (-=), multiply (*=), and divide (/=), simplifying variable modifications.

Delving deeper, we explored mathematical rounding techniques such as round(), math.floor(), and math.ceil(), ensuring precision in numerical calculations.

We harnessed the power of exponentiation with the ** operator and math.pow() function, facilitating easy calculation of powers and square roots math.sqrt().

Additionally, we harnessed logical operators like AND (&) and OR (|), enabling us to evaluate complex logical expressions with ease.

Ensuring data consistency operator, we utilized the Math.abs() function to transform negative numbers into positive ones, maintaining uniformity in data processing.

While we’ve only scratched the surface of operators in programming, today’s journey has provided us with a solid foundation to build upon. Armed with these newfound skills, we’re better equipped to tackle a wide array of computational tasks and navigate the diverse landscapes of programming 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 do we call + - * and / in Python?``

``What other operators are there?``

### You can ask the same question twice and get more results:

``Are there others?``

### Then you can explore each operator with:

``````I would like to learn more about Floor Division Operator //.

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.``````

### To get an assignment to learn from:

``````I would like to learn more about Floor Division Operator //.

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)``````

### 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?
--
# Given:
# Assume you are organizing a marathon event.
# You have a total of 152 registered participants.
# Each starting block can accommodate a maximum of 40 runners.

# When:
# Calculate the total number of starting blocks needed for the marathon.
# Use the floor division operator (//) to ensure that any partial block
# needed is rounded up to the nearest whole block.

# Then:
# Print the total number of starting blocks required for the marathon.
# Assert that the calculated total matches the expected value.
--``````

### 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#

### You can ask for a new assignment – as many times as you want.

You can make the AI solve it for you.
You can solve it yourself.
Limitless learning with a 24/7 tutor!!!

## Introduction

In programming, a “string” is simply text data – like words in a book or letters in your name.
Technically it is a variable, where you store text in it.

Python
``````# when we have a text string
aTextString = "hello world"

# then we can print it to show it's content
print(aTextString)``````

Now you need to make a choice, how you want to learn it:

1. You can use AI to teach you. Then you can learn, by your own exploration and in any programming language (scroll down to Using AI)
2. You can use the result I got, from using AI. Then you can rely on my experience to filter it.(keep on reading)
3. You can also do both in any order :-)

## Joining Strings Together (Adding / Concatenation)

Python
``````# given we have two texts
var1 = "hello"
var2 = "world"

# when we add them together
result = var1 + var2

# then they put together
print(result)
assert result == "helloworld"``````

Python
``````# given we have two numbers
var1 = 1
var2 = 2

# when we add them together
result = var1 + var2

# then they give the sum
print(result)
assert result == 3``````

If we put the numbers as text (with quotation marks), then they will add as strings and not numbers:

Python
``````# given we have two numbers
var1 = "1"
var2 = "2"

# when we add them together
result = var1 + var2

# then they put together (and not the sum)
print(result)
assert result == "12"``````

Also if you want to have a space between to words, that you add together, then you need to remember to also add a space:

Python
``````# given we have two texts
text1 = "hello"
text2 = "world"
space = " " # the space

# when we add them together
result = text1+ space + text2

# then they put together
print(result)
assert result == "hello world"``````

### Challenge, weather report

Try to write a code, where you

Python
``````# given the weather is describe with the following parts:
city = "Praestoe"
temperature = "22Β°C"

# When we concatenate them to form a weather report

# Then the result should exactly match the expected report.
print(result)
assert result == "The current weather in Praestoe is 22Β°C"``````
Hint / Result
Python
``result = "The current weather in " + city + " is " + temperature``

## G-, F-, Template- and interpolated-strings

G-Strings are a special kind of strings that are used in Groovy. They have other names in other languages:

They seem much more complex that a regular string, except they make our lives much easier.

Which one of these text addition do you find easiest to use?

Python
``````# example 1 (the regular string)
result = "Mr. "+ name

# example 2 (the f-string)
result = f"Mr. {name}"``````

When we write a f in front of a “
Then we can just add { } with a variable name inside the text.

This makes it much easier with much more complicated strings, where we can use spaces inside the string, instead of adding extra spaces or adding them as variables:

Python
``````# example 1 (the regular string)
result = title + " " + firstName + " " + lastName

# example 2 (the regular string with space variables)
result = title + space + firstName + space + lastName

# example 3 (the f-string)
result = f"{title} {firstName} {lastName}"``````

### Challenge, F-weather

Rewrite the previous challenge by using f-strings

Python
``````# given the weather is describe with the following parts:
city = "Praestoe"
temperature = "22Β°C"

# When we concatenate them to form a weather report

# Then the result should exactly match the expected report.
print(result)
assert result == "The current weather in Praestoe is 22Β°C"``````
Hint / Result
Python
``result = f"The current weather in {city} is {temperature}"``

## Slicing

Since we can add strings together, then we can also slice them up into smaller parts and only keep the important part.

Python
``````# given we have a text string
greeting = "Hello world"

# when we slice off the first letter
without_first = greeting[1:]

# then we only have the rest left
print(without_first)
assert without_first == "ello world"``````

And the same can be done on the other side of the string:

Python
``````# given we have a text string
greeting = "Hello world"

# when we slice of the 2 last letters
without_last = greeting[:-2]

# then we only have the rest left
print(without_first)
assert without_first == "hello wor"``````

We use negative numbers, to count letters from the back of the string
We use positive numbers, to count letters from the front of the string

### Challenge, slicing the world

Python
``````# given we have a text string
greeting = "12345"

# when the ? is replaced with a positive number
result_1_1 = greeting[?:]
result_1_2 = greeting[:?]
result_1_3 = greeting[?:?]

# and the ? is replaced with a negative number
result_2_1 = greeting[:-?]
result_2_2 = greeting[-?:]
result_2_3 = greeting[-?:-?]

# then the strings are sliced to
assert result_1_1 == "2345"
assert result_1_2 == "12"
assert result_1_3 == "2"

assert result_2_1== "1234"
assert result_2_2== "45"
assert result_2_3== "4"
``````
Hint / Result
Python
``````result_1_1 = greeting[?:] # [1:] from after letter 1
result_1_2 = greeting[:?] # [:2] until after letter 2
result_1_3 = greeting[?:?] # [1:2] from after letter 1 until after letter 2

result_2_1 = greeting[:?] # [:-1] until before letter 1 from behind
result_2_2 = greeting[?:] # [-2:] from before letter 2 from behind
result_2_3 = greeting[?:?] # [-2:-1] from before letter 2 from behind until

result_3_1 = greeting[?:?] # [1:-2]from after letter 1 until before letter -2 from behind
result_3_1 = greeting[?:?] # [-3:1]from after letter 1 until before letter -2 from behind``````

## Length of a string

We can also measure the length of a string, which can be important if we want a password to have a minimum length.

Python
``````# when we have two passwords

# then password1 is long enough (this will pass)

# and password2 is not long enough (this will fail)

## Replace parts of a string

When we have a string, then we can replace a part of it with something else.

Python
``````# given we have a greeting
greeting = "Hello Jan Wallace"

# when we replace the name
greeting = greeting.replace("Jan", "Peter")

# then the complete greeting will change
print(greeting)
assert greeting == "Hello Peter Wallace"``````

We simply write the word or letters we want to replace, and the second word is what we want to replace it with.

### Challenge, remove/replace a name

Python
``````# given we have a letter, where a person is named
letter = "Hello Jan Wallace. We want to inform you, that your name Jan Wallace, will now be annonymized in the whole string."

# when we replace "Jan Wallace" with "J"
# write your own code here
letter = letter .replace("Jan Wallace", "J")

# then all
print(letter )
assert letter == "Hello J. We want to inform you, that your name J, will now be annonymized in the whole string."``````
Hint / Result
Python
``greeting = greeting.replace("Jan Wallace", "J")``

## UPPER CASE and lower case

Computers are always sensitive with UPPER CASE and lower case characters.
When we write a variable name with an upper case letter, then we need to remember that upper case letter.

Python
``````# when we have a variable called fullName
fullName = "Jan Wallace"

# then we need to use the capital N otherwise
print(fullName)

# and if we don't use the capital N, then it will fail
print(fullname)``````

Sometimes we make it easier for the users to only use lower case letters, like we do with emails. The following emails are the same “spam@bartek.dk”, “SPAM@BARTEK.DK” and “SpAm@BaRtEk.Dk”.

To control the upper or lower case we can use the a commando:

Python
``````# when we have 3 emails
email1 = "spam@bartek.dk"
email2 = "SPAM@BARTEK.DK"
email3 = "SpAm@BaRtEk.Dk"

# then we can turn all of them into the same email with lower case
print(email1.lower())
print(email2.lower())
print(email3.lower())
assert email1.lower() == "spam@bartek.dk"
assert email2.lower() == "spam@bartek.dk"
assert email3.lower() == "spam@bartek.dk"

# and we can do it with UPPER CASE too
print(email1.upper())
print(email2.upper())
print(email3.upper())
assert email1.upper() == "SPAM@BARTEK.DK"
assert email2.upper() == "SPAM@BARTEK.DK"
assert email3.upper() == "SPAM@BARTEK.DK"``````

### Challenge, split and uppercase and add

We want the following 3 names to start with a uppercase letter and the rest be lower case. You will have to split your string make the first letter capital and add the new letter to the rest of the name.

Python
``````# given we have 3 names
name= "eLISAbeTH"

# when we split it into first letter and the rest

# and make the first letter upper case

# and the rest lower case

# and add them all together (You may also use an f-string)

# then our name will start with an upper case letter and the rest will be lower case letters
print(name)
assert name == "Elisabeth"``````
Hint / Result
Python
``````# given we have 3 names
name= "eLISAbeTH"

# when we split it into first letter and the rest
firstLetter = name[:1]
restOfName = name[1:]

# and make the first letter upper case
firstLetter = firstLetter.upper()

# and the rest lower case
restOfName = restOfName.lower()

# and add them all together (You may also use an f-string)
name = f"{firstLetter}{restOfName}"

# then our name will start with an upper case letter and the rest will be lower case letters
print(name)
assert name == "Elisabeth"``````

## Trim or strip

Sometimes Strings are written with spaces before and after the text: ” hello world “

The easiest way to remove the spaces is to use the command strip() in Python, trim() in JavaScript and Groovy, and Trim() in C#.

Python
``````# Given the original text with leading and trailing space
originalText = " hello world "
print(f"original: \${originalText }")

# When we apply strip in it's 3 variations:
text1 = originalText.lstrip()
text2 = originalText.rstrip()
text3 = originalText.strip()

# Then text1 should be with no leading whitespace
print(f"lstrip:  |{text1}|")
assert text1 == "hello world "

# And text2 should be with no trailing whitespace
print(f"rstrip:  |{text2}|")
assert text2 == " hello world"

# And text3 should be with no leading or trailing whitespace
print(f"strip:   |{text3}|")
assert text3 == "hello world"``````

To add spaces, or any other symbol, before a text can be done with rjust() in Python, padStart() in JavaScript, padLeft() in Groovy, PadLeft() in C#.

To add spaces, or any other symbol, after a text can be done with ljust() in Python, padEn() in JavaScript, padRight() in Groovy, PadRight() in C#.

Python
``````# Given product names and prices
product1 = "Orange"
price1 = "25 EUR"

product2 = "Computer"
price2 = "1000 EUR"

# When combining product names and prices with normal addition
productText1a = product1 + " " + price1
productText2a = product2 + " " + price2

# Then the product text is not formatting in a pretty way
print(productText1a)
print(productText2a)
print("---------  ---------")

# When aligning product names with spaces as padding
productText1b = product1.ljust(10, " ") + price1.rjust(10, " ")
productText2b = product2.ljust(10, " ") + price2.rjust(10, " ")

# Then the product text should have a pretty formatting
print(productText1b)
print(productText2b)
print("---------  ---------")

# When aligning product names with dots as padding
productText1c = product1.ljust(10, ".") + price1.rjust(10, ".")
productText2c = product2.ljust(10, ".") + price2.rjust(10, ".")

# Then the product text should have even prettier formatting
print(productText1c)
print(productText2c)
print("---------  ---------")``````

Which will give the following output:

## Escape sequences to make line breaks, tabulators, and quotes within quotes

To have a line break in a string, then a \n can be put into it. Because we can’t write:

Python
``````print("line 1
line 2")
# creates an error``````

To have a tab a \t can be use, even though we sometimes can add tabs, but not always. Sometimes they are added as 2 or 4 spaces instead of a tab:

Python
``````print("word 1  word 2")
# creates an error``````

To have a quote within a quote requires an \”, because we can’t write the following without creating an error:

Python
``````print("word 1 "word 2" word 3")
# creates an error``````

And because we use \ to write special characters, we need to write \\ to tell the computer we want to write an \, otherwise it will expect an special character.

To write it correctly please do:

Python
``````print("----linebreak----")
print("line 1\nline 2")

print("----tab----")
print("word 1\tword 2")

print("----quoate----")
print("word 1\"word 2\"word 3")

print("----backslash----")
print("before\\after")``````

and it gives the following output:

There are even more tools like Regex, but we need to learn more like Arrays, indexing, functions, etc. We will come back to those later.

## Conclusion

Today, we took a fun dive into the colorful world of strings, discovering that strings are like little containers for textβholding everything from single words to lengthy paragraphs.

We kicked things off by learning how to add strings together, transforming “hello” and “world” into “hello world.”

We then looked into f-strings (Python), G-strings (Groovy), template-strings (JavaScript) and interpolated strings (C#).

We also got crafty with slicing strings, which is a bit like sculpting: you chisel away the parts you donβt need or shuffle them around to create something entirely new.

And we played around with replacing a word in a string with another word. Quite fancy when you want to anonymize a text.

We also looked into the length of strings. Itβs like having a tiny ruler at your fingertips, perfect for checking the length of a text, ensuring passwords meet security standards, or just satisfying your curiosity about how much you’ve actually typed.

We played with to uppercase and lowercase, which helps keep everything looking neat and tidy, no matter how chaotic the input might be.

We ended with a fun exercise where we had to combine all what we learned together, by making “eLISAbeTH “into “Elisabeth”

We looked into trim/strip to remove spaces.

Escape sequences such as line breaks, tabulators, and quotes within quotes.

By now, you should feel pretty equipped to handle text in your programming projects. Whether you’re crafting messages, tidying up data, or just indulging your inner nerd, the skills you’ve embraced today are essential tools in your programming kit. Letβs keep that inner child curious and eager to learn more as we continue exploring the vast and vibrant world of coding!

## 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:

``````I would like to learn about Strings (text) in Python.
What things are critical to learn?``````

``I would like to learn more about Escape Sequences, what should I be able to do?``

It answered much more, but there is no need to show it all, because the amount of data can be overwhelming: (Multiline Strings, Unicode Character, Escape Sequence as Literal, Control Characters, Hexadecimal and Octal Escapes)

Take one of them and go further into it.

### Then you can explore each theme with:

``````I would like to learn more about Special Characters such as '\n', '\t', and '\\'.

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)``````

And we can always test the code in our web editors: π» Python / π» JavaScript π» Groovy / π» C#

### To get an assignment to learn from:

``````
Can you make a assignment for me to solve?
It has to be about using Special Characters such as '\n', '\t', and '\\'.

The assignment needs to be written in Python as comments.
Use only given, when, and then comments. No code.``````

### 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?
--
# Given a string containing multiple lines of text separated by '\n' characters,
# where some words are separated by '\t' characters,
# and some backslashes are used to escape special characters.

# When the string is given as input,
# Then write a Python program to perform the following tasks:

# 1. Split the string into individual lines using the '\n' character as the delimiter.
# 2. For each line, split the line into words using the '\t' character as the delimiter.
# 3. If a word contains the sequence '\\', replace it with a single backslash character '\'.
# 4. Print each word on a new line.

# For example:
# Given input string:
# "Hello\tworld!\nThis\tis\tan\texample\nString\twith\\tSpecial\tCharacters\n"

# The output should be:
# Hello
# world!
# This
# is
# an
# example
# String
# with\tSpecial
# Characters
--``````

And we can run it in our web editor:

### You can ask for a new assignment – as many times as you want.

You can make the AI solve it for you.
You can solve it yourself.
Limitless learning with a 24/7 tutor!!!

## Why variables?

Ever wonder how your favorite video games come to life?

Picture invisible shelves filled with jars, each holding pieces of the game world.

One jar might decide the name of your character, , while another controls the speed of your racing car.

JavaScript
``````const charachterName = "Bartek";
let maxSpeedOfCar =  200;``````

In the example above we set the characterName to be “Bartek” and the maxSpeedOfCar to 200.

These jars or variables are at work behind the scenes, making digital experiences thrilling and interactive. They’re the unseen magic that breathes life into pixels and bytes, transforming them into adventures and stories that enthrall us.

## Naming variables

The name of a variable has 2 important parts:

1. Computer friendly name: The computer needs to be able to read the name.
2. Human friendly name: We coders need to know, what the variable contains

## Computer friendly name

For the computer to read it, it needs to be a single text without spaces:

There is also PascalCase, snake_case, UPPER_SNAKE_CASE, kebab-case, etc. but we will cover them, when the need arise.

## Human friendly name

It is also a good idea to give it a name, that we humans can understand, because it will be difficult to understand what this code do:

fn = t + n1 + n2

While this is much easier to read:

fullName = title + firstName + lastName

because we can read, that we take the title putting it together with the first name and the last name and store it as the full name.

Which variables are ok, and which are not?

JavaScript
``````const playerName = "Bartek"
const player name = "Bartek"
const player-name = "Bartek"
const pn = "Bartek"
const PlayerName = "Bartek"
``````

playerName is ok!

player name is not ok! Because the computer don’t like the space.

player-name is not ok! Because the computer don’t like the dash.

pn is not ok! Because we can’t guess what the pn stands for.

PlayerName is not ok! Because variables names must start with a non-capital letter.

## Assigning a variable

We assign variables in different ways in different languages.
Just select the language, that you would like to learn. No need to learn all of them.
We use constants, when we don’t want the value to change in the future.
We use variable, when we want the value to change in the future.

### Python

Assign a variable: just assign it a value. Use camelCase.
Reassign a variable: Just give a variable a new value.
Assign a constant: just assign it a value. Python don’t support constant, but we can use CAPITAL letters, so we know it is a constant later in the code.
Reassign a constant: Avoid this. If a variable is written in CAPITAL letters, then it is a constant, and should not be changed.

Python
``````GREETING = "hello"
name = "Bartek"
name = "Patrick"
GREETING = "hi"``````

### JavaScript

Assign a variable: Use let to assign a variable.
Reassign a variable: Just give it a new value (without let)
Assign a constant: Use const to assign a constant. Use also CAPITAL letters, so we know it is a constant later in the code.
Reassign a constant: This will give an error.
Old school variable: There is also an old version called var. Don’t use it.

JavaScript
``````const GREETING = "hello";
let name = "Bartek";

name = "Patrick";
GREETING = "hi"; // this will throw an error``````

### Groovy

Assign a variable: use def to assign it a value.
Reassign a variable: Just give it a new value (without def).
Assign a constant: just assign it a value. Groovy don’t support constant, but we can use CAPITAL letters, so we know it is a constant later in the code.
Reassign a constant: Avoid this. If a variable is written in CAPITAL letters, then it is a constant, and should not be changed.

Groovy
``````def GREETING = "hello"
def name = "Bartek"
name = "Patrick"
GREETING = "hi"``````

### C#

To assign a constant in C#, we need write const to begin with. Then we need to specify, what type of variable we want. To write text, we need to define it as string and to write a number we write int (more on string and int in later lessons).
We again use CAPITAL letters for constants, to know later in the code, that they are constants.
To assign a variable, we just use string or int.
To reassign a variable, we just give it a new value.
Trying to reassign a constant will give an error.

Assign a variable: use string for text and int for numbers to assign it a value
(more on string and int in later lessons).
Reassign a variable: Just give it a new value, but you can’t change text to number or back.
Assign a constant: use const in front of string or int. Use CAPITAL letters, so we know it is a constant later in the code.
Reassign a constant: This will give an error.

C#
``````const string GREETING = "hello";
int name = 2;

name = 3;
GREETING = "hi" // this will throw an error
name = "Bartek" // will also throw an error``````

## Challenges introduction

You can use free ChatGPT 3.5 to translate it from Python to other languages (read how)

And use the Web editors: π» Python / π» JavaScript / π» Groovy / π» C#

We have this working code example for inspiration, to solve the challenges:

Python
``````# Given we have 2 numbers: 1 and 2
number1 = 1
number2 = 2

# When we add them together
result = number1 + number2

# Then the result will be printed and asserted
print(result)
assert result == 3``````

### Challenge 1

Can you add the required details, to make the code work?

Python
``````# Given we have 3 numbers: 1, 2, 3
number1 = 1
number2 = 2

# When we add them together
result = number1 + number2

# Then the result will be printed and asserted
print(result)
assert result == 6``````

### Challenge 2

Can you add the required details, to make the code work?

Python
``````# Given we have 4 numbers: 1, 2, 3, 5

# When we add them together

# Then the result will be printed and asserted
print(result)
assert result == 11``````

### Challenge 3

Can you add the required details, to make the code work?

Python
``````# Given we have 5 numbers: 1, 2, 3, 5, 7

# When we add them together

# Then the result will be printed and asserted``````

## Conclusion

In the journey through the realms of coding, we’ve seen how variables act as the fundamental building blocks, allowing us to store, manipulate, and retrieve data with ease.

Just as jars can hold anything from spices to cookies in the kitchen, variables in programming hold the pieces that bring digital experiences to life, from the names of characters in a video game to the speeds of racing cars.

We learned to name variables, so we know what they actually mean, because anyone can understand ourAge = yourAge + myAge, while nobody can guess what oa = ya + ma means.

We learned to use camelCase for variables, and CAPITAL for constants. And remember not to use spaces, because computers don’t get understand it.

You have also solved 3 challenges – congratulations!

Remember, the power of coding is at your fingertips, and variables are one of the first keys to unlocking that potential. Happy coding!

And you can always create your own challenges, with multiple variables, different values or even using minus, multiplication, or division, instead of plus.

## Spice it up with TDD

Need a better translation or explanation?
(Opens in a new window)

## Intro

Let’s dive into the world of Test Driven Development (TDD) together, shall we? π

So, what exactly is TDD? Well, it’s a way to describe things in a programming language.. Imagine it’s like telling a story, but instead of using words, we’re using code!

Here’s how it works: when we want to describe something using English, we focus on describing one thing at a time.

It’s like building with Lego bricks – we start with one piece and add more as we go along!

But here’s the cool part: just like in science like physics, we can even test our code, to see if it behaves the way we expect it to. It’s all about making sure our code is usable and understandable, just like in a science experiment!

So, think of TDD as our own little computer-science experiment. We write down our specifications and then make sure the computer behaves the way we want it to π€β¨

## Lets do some coding!

First we split our code into 3 parts: “given”, “when”, and “then”

Python
``````# Given (where we set our preconditions)
number1 = 1
number2 = 2

# When (where the action happens)
result = number1 + number2

# Then (where we assert/return our output)
print(result)``````
π» Code

With the print in the end, we can verify the result manually:

``````Python3 2024-06-03 on Linux x86_64)
----
3``````
π» Terminal result

You can always use our web editors: π» Python / π» JavaScript / π» Groovy / π» C#

The “given”, “when”, and “then” is usually known in TDD as the triple A’s: “Arrange”, “Act”, and “Assert” and they do the same, except given, when, then is easier to read and arrange, act, assert is more technical.’

Python
``````# Given two numbers are defined
# When the numbers are added together into the result
# Then the result must be verified to be the sum

# Arrange: two numbers are defined
# Act: the numbers are added together to get the result
# Assert: verify the result is the sum of the numbers``````
π» Code

What we can do instead, is to assert it automatically, by replacing print with assert:

Python
``````# Given
number1 = 1
number2 = 2

# When
result = number1 + number2

# Then
assert(result == 3)``````
π» Code

The == means that we want the computer to verify if the equal is actually equal.
It responds with either true (the equal is equal) or false (the equal is not equal).
The assert consumes the true or false and if it’s true, then it does nothing, because everything is fine:

``````Python3 2024-06-03 on Linux x86_64)
----``````
π» Terminal result

If it’s true, then it the codes passes and everything is fine (even though we can’t see it, but no news is good news!).

Need help?
Click anyone of them to get a guide, on how AI can help you.
(Opens in a new window)

## Assert & print

If we want a result we can print it:

Python
``````# Given
number1 = 1
number2 = 2

# When
result = number1 + number2

# Then
print(f"result: {result}")
assert(result == 3)``````
π» Code

The f in the f”…” means it is a text with parameters, where we can take the value of result.
It has different names in different programming languages:

## Negative test

To see a negative result, we need to replace the 3 with a 4 (because 1+2 is not 4):

Python
``````# Given
number1 = 1
number2 = 2

# When
result = number1 + number2

# Then
assert(result == 4)``````
π» Code

Then we will see an assertion error, where the result is not 4:

``````Python3 2024-06-03 on Linux x86_64)
----
Traceback (most recent call last):
File "apps/console-python/", line 9, in <module>
assert(result == 4)
AssertionError``````
π» Terminal result

## Better error messages

To give it a better error message, we could add an actual error message:

Python
``````# Given
number1 = 1
number2 = 2

# When
result = number1 + number2

# Then
assert(result == 4), f"(actual) {result} != 4 (expected)"``````
π» Code

Which gives:

``````Python3 2024-06-03 on Linux x86_64)
----
Traceback (most recent call last):
File "apps/console-python/", line 9, in <module>
assert(result == 4), f"(actual) {result} != 4 (expected)"
AssertionError: (actual) 3 != 4 (expected)``````
π» Terminal result

and put it inside the text. So, f”{result} =! 4″ becomes: “3 != 4”

You can see, some languages are more fun than others π

## Why use an assert, when print makes it much easier?

In a simple program like that, we can use a print.

A more complex program may have 20 kinds of outputs, depending on the inputs.
It is much easier, faster and more precise to automate all the outputs, instead of testing them manually:

Python
``````# Imagine we have already a complex program called buyTicket(numberOfZones, travelerType)

# here would the tests be:
# etc... ``````
π» Code

No need to run the buyTicket manually 20 times and checking all the values are correct.
A machine can run a 1000 test cases per minute, and we humans can’t.
And there is also no need to remember all the results, when the machine can do it for us.

## Testing before coding

TDD is not only about testing the code.
It’s more about writing down our assumptions that we have in our head.

So, often we need to start with the given’s (where we start) and the then’s (where we need to end):

Python
``````# Given
# write your code before writing the when code

# When
# write your code after writing the given and then code

# Then
# write your code before writing the when code``````
π» Code

The when code is written last, for the given and then are the specification of the wanted system behavior. The when code is the required logic that makes the given and then to connect.

And whenever we want to change the specification, we just need to change the given and the then code. Then we will see the existing when code will fail, and therefore needs to be refactored (updated).

## Exercise:

Write the needed when code, so all the asserts pass. Please don’t change the code in the given and then.

Python
``````# Given (writen before when)
number1 = 1
number2 = 2
number3 = 3
number4 = 5

# When (written after given and then)

# Then (written before when)
assert(result1 == 3), f"{result} =! 3"
assert(result2 == 4), f"{result} =! 4"
assert(result3 == 5), f"{result} =! 5"
assert(result4 == 6), f"{result} =! 6"
assert(result5 == 7), f"{result} =! 7"
assert(result6 == 8), f"{result} =! 8"``````
π» Code
Hint or Check if your result is correct)
Python
``````# Given
number1 = 1
number2 = 2
number3 = 3
number4 = 5

# When we add 2 numbers together to get the result1-6
result1 = number1 + number2
result2 = number1 + number3
result3 = number2 + number3
result4 = number1 + number4
result5 = number2 + number4
result6 = number3 + number4

# Then
assert(result1 == 3), f"{result} =! 3"
assert(result2 == 4), f"{result} =! 4"
assert(result3 == 5), f"{result} =! 5"
assert(result4 == 6), f"{result} =! 6"
assert(result5 == 7), f"{result} =! 7"
assert(result6 == 8), f"{result} =! 8"``````

## What’s next?

In the next lessons, we will do some coding exercises.

I would like you to use the assert, so you don’t have to remember the results from all the exercises.

You are welcome to add a print, if you want to. It can be very useful, to use a print, get a view inside to see what the code is doing.

In the web editor (in case you want to use that to begin with), there is no option to save your code, but what you can do is to copy & paste your code into a notepad for future use.

Then you can always copy & paste it back into a web editor, if you want to use it again.
It is also possible to have multiple web editors open, without them interfering with each other.

## Exercise:

Add an assert after the print. And make sure the whole code passes.

Python
``````# Given name and a greeting is defined (you can use any name)
name = "Bartek"
greeting = "Hello"

#When the greeting, a space, and the name is combined into the text.
text = greeting + " " + name

# Then the text can be printed as output and be verified by us
print(text)``````
π» Code
Hint or Check if your result is correct)

assert(text == “Hello Bartek”)

Then update the code, to make it fail with an AssertionError.

Extra: if you want more challenge, you can try to add an improved error message.

## Spilting:

Sometimes it is not possible to write code in the given, when, then format.
This is a sign, that we should split the code into smaller parts (like methods/functions or classes).

A piece of code should often only do a single thing, even though the outputs can be different.

## Conclusion

Let’s wrap up our journey into Test-Driven Development (TDD), shall we? π

So, here’s the scoop: Test-Driven Development (TDD) offers a structured approach akin to the scientific method, providing a framework for software development that prioritizes clarity, predictability, and reliability.

Picture this: before we even start writing the actual code, we write tests to describe how we want our software to behave. It’s like drawing a map before going on a big adventure – it helps us know where we’re going!

And here’s where things get really cool: we use something called assertions to check if our code works the way we want it to. It’s like having a super fast and precise robot double-checking our work to make sure everything’s OK! π€β

TDD not only makes testing super fast and easy, but it also helps us understand our coding problems better. It’s like putting together a puzzle – each piece fits together perfectly to create something awesome!

So, as we dive deeper into coding and keep exploring TDD, let’s make assertions our best friend. They’ll help us build super strong, super reliable software that can handle anything life throws our way! πͺπ

## Hello world

So, you’ve got this awesome idea to dive into the world of coding? That’s seriously awesome! π

Now, I know there’s this fear floating around that programming might become obsolete with all this talk about AI, but trust me – that’s not the case at all! Sure, some parts of programming might change, but that’s just part of the journey.

Back in the old days, programming languages were super specific to hardware. But guess what? Today, they’re becoming more abstract, letting us describe processes and system behaviors in a whole new way!

I’m super confident that the programming languages of the future will be like our own personal translators, helping us communicate exactly what we want. And guess what? We’re gonna dive into the basics together, almost like learning new words to describe really cool stuff! π

## Selecting a tool

Please use a web-editor for any language that you want:

Web editor: π» Python / π» JavaScript π» Groovy / π» C#

I’ve got four awesome code examples for each language above. They’re all kinda similar, so just pick one and dive in! And remember, you can always expand your horizons later on when you’re ready for more!

## Writing a comment

Let’s kick things off with your very first program, shall we?

We’re gonna start by writing some comments in the code. Comments are like little notes that the computer ignores, but we programmers can see them and get extra info.

I prefer to write code split into 3 phases with comments, so it is like building with Lego:

• Given you have these Lego pieces
• When you put them together in a specific way.
• Then you should get a specific figure.

Simple, right?

## How to write a comment:

Python
``# This is a comment in Python``
JavaScript
``// This is a comment in Python``
Groovy
``// This is a comment in Python``
C#
``// This is a comment in Python``

As you can see, it’s only Python who uses #, while the other use // for comments.

So, for the first program:

Python
``````# Given name and a greeting is defined (you can use any name)
name = "Bartek"
greeting = "Hello"

#When the greeting, a space, and the name is combined into the text.
text = greeting + " " + name

# Then the text can be printed as output and be verified by us
print(text)``````
JavaScript
``````// Given name and a greeting is defined (you can use any name)
const name = "Bartek";
const greeting = "Hello";

// When the greeting, a space, and the name is combined into the text.
const text = greeting + " " + name;

// Then the text can be printed as output and be verified by us
console.log(text);``````
Groovy
``````// Given name and a greeting is defined (you can use any name)
def name = "Bartek"
def greeting = "Hello"

// When the greeting, a space, and the name is combined into the text.
def text = greeting + " " + name

// Then the text can be printed as output and be verified by us
println(text)``````
C#
``````using System;
using System.Diagnostics;

public class Program
{
public static void Main()
{
// Given name and a greeting is defined (you can use any name)
var name = "Bartek";
var greeting = "Hello";

// When the greeting, a space, and the name is combined into the text.
var text = greeting + " " + name;

// Then the text can be printed as output and be verified by us
Console.WriteLine(text);
}
}
``````

Now, I’ve got a little exercise for you: type this code into your web editor of choice:
π» Python / π» JavaScript π» Groovy / π» C#

If it doesn’t work, no worries! Just use the copy-paste method I’ve included below.

Then, hit run and see the magic happen!

The result of the program should give you a friendly “Hello Bartek,” but feel free to change it up with your own name or different greetings!

## Conclusion

Congratulations – you’ve just written your first program! π Let’s keep this coding adventure going! πͺβ¨

## What is a programming language

Let’s talk about something super cool: languages. No, not just the ones we speak, but the ones we use to create, talk, save stuff, find stuff, and even give stuff a makeover!

Think of languages like the colors in your crayon box. Just as you mix and match to create your masterpiece, we’ve got lots of languages doing the same thing in the big wide world. They’re always growing and getting better, like a never-ending adventure!

Here’s the really neat part: sometimes we need more than one language to say what we mean. Take programming languages, for example. They’re like the brainy ones that talk about logic and tech stuff, but they might need a little help from other languages to talk about feelings and emotions.

So, get ready to explore the colorful world of languages, where every word is a brushstroke in the masterpiece of life! π¨π