**[work in progress](<../work%20in%20progress.md>)**

An "if statement" is a way to choose to perform a different action based on a condition (which is written using boolean logic).

writing conditions for if statements

An if statement looks like this:

if <some condition>: <take some action>

In this section we'll work out how to add the missing <some condition>. Let's imagine that we're checking that a username is correct before writing it to a database. Usernames should start with a capital letter and contain only letters in the range "a"-"z" and "A"-"Z". We start with a function.

def check_username(username): # condition 1 if <some condition>: return False # condition 2 if <some condition>: return False return True

This is a function that takes a username (a string) and returns a boolean – so it maps strings to booleans. Let's think about how we can check that the start of the string is a capital letter.

How do we get the start of the string. Using indexing, we know that the start of a string will be some_string[0]. In our case, the variable storing our string is username, so to get the start of the string we want to pick username[0].

# condition 1 if username[0] # some expression here: return False

For this condition, we will return false (i.e. that the username is invalid) when the condition is true. So our condition must be false when the condition is valid (i.e. when the first character in the string is upper case – which is when a username would be valid – we want to return false) and true when the condition is invalid (i.e. when the first character is not capital letter our condition should be true). If you think this is confusing you are not alone. Everyone makes mistakes doing this (and many professional computer scientists have experienced the horror of having to debug a live computer system in the middle of the night, having been woken up because faulty boolean logic caused a malfunction). To mitigate this, we use testing in order to catch faulty boolean logic before it becomes a problem.

This means that the boolean expression we want is not username[0].isupper(). This is the same as username[0].islower() (because we will check in the next condition that the string does not contain any non-latin alphabet characters).

def check_username(username): # condition 1 if username[0].islower(): return False # condition 2 if <some condition>: return False return True

For condition (work in progress, I have not uploaded this section yet).

practice questions

  1. Write an algorithm that will allow the user to input two numbers. The algorithm should then compare these two numbers, and output the larger one. You can check your answer here
  2. Write a program that inputs a string and outputs "yes" (case-sensitive) if the string is equal to "discombobulated" and outputs "no" if it is not equal. You can check your answer here if answers