Programming Fundamentals: Functions, Booleans, Loops
Programming Fundamentals
Functions
Functions are a group of instructions that can be grouped together and referred to as a whole. They are small algorithms inside of a big algorithm, have inputs, and produce outputs (a set of instructions).
Format: function name (argument1, argument 2)
Example: print('hello world!')
Functions are a group of instructions that can be grouped together and referred to as a whole. They can have inputs and can produce/return outputs.
- Value-returning functions produce or return some output (something new).
- Example:
user_name = input ('enter name: ')
- Void functions don’t return anything (subroutines).
- Example:
print ('hello')
Defining a function:
def function_name (arg1: type1, arg 2: type 2...) -> return_type:
instructions that use arguments
return something
Void Functions
Void functions have no return statement; print is used instead.
def greeting(name: str) -> None:
print(f'Hello {name}')
user_name = input('enter your name: ')
greeting(user_name)
Value-Returning Functions
Value-returning functions have a return statement at the end, making them value-returning.
def add_two_integers(x: int, y: int) -> int:
the_sum = x + y
return the_sum
sum = add_two_integers(2, 3)
print(sum)
Local and Global Variables
- Local variables are defined inside a function and are only accessible by that function.
- Global variables are defined in the main program and are accessible everywhere.
def add_2_numbers (x: float, y: float) -> none:
sum = x + y <- local variable
print (sum) <- function body
add_2_numbers (2.1, 3.8) <- arguments
Booleans
Booleans represent truth or false values.
Data Types
int
= integersfloat
= real numbersstr
= text
Operators
*
= multiplication/
= division//
= integer division (6 // 4 = 1)%
= remainder/mod (6 % 4 = 2)**
= exponent (2 ** 3 = 8)!=
(not equal)==
(equal)
Logical Operators
and
– True if BOTH operands are true – (3 > 2) and (0 == 1) means falseor
– True if EITHER operand is true – (3 > 2) or (0 == 1) means truenot
– Inversion from true to false or false to true – not true means false
Decisions
If-Else Statements
Run a set of statements if a condition is true, and another set otherwise.
if temperature < 40:
print("A little cold, isn't it?")
else:
print("Nice weather we're having")
If-Elif-Else Statements
Test which of a set of conditions is true, and run the corresponding set of statements.
if temperature > 40:
print('high fever')
elif temperature >= 37:
print('fever')
else:
print('normal')
Loops
Condition-Controlled Loops
Repeat an operation as long as some condition is TRUE.
five_was_found = False
while not five_was_found:
rnd_number = randint(0, 10)
print(rnd_number)
five_was_found = rnd_number == 5
print('5 was found!')
Count-Controlled Loops
Repeat an operation a specified number of times.
iteration_number = 0
# loop 5 times
while iteration_number < 5:
iteration_number += 1
print(f'iteration number: {iteration_number}')
print('done')
Infinite Loops
Occur when the condition cannot be false, which can happen due to logic errors in the condition or if variables are not modified properly.
range(5) = [0, 1, 2, 3, 4]
range(5, 0, -1) = [5, 4, 3, 2, 1]
Example Functions
def compute_HRV(interval1: float, interval2: float, interval3: float) -> float:
diff1 = interval2 - interval1
diff2 = interval3 - interval2
hrv = math.sqrt ((diff1 ** 2 + diff2 ** 2) / 2)
return hrv
def temperature_is_fever(temperature: float, site: str) -> bool:
site = site.lower()
if site == 'oral' and temperature >= 37.8:
return True
elif site == 'underarm' and temperature >= 37.2:
return True
else:
return False
def has_fever() -> bool:
temperature = float(input("Enter your temperature (°C): "))
site = input ('Was the temperature measured Orally (O) or Underarm (U)? (enter O or U):').strip().lower()
if site == 'o':
site = 'oral'
elif site == 'u':
site = 'underarm'
else:
print ("Invalid input. Please enter either 'O' or 'U'")
return has_fever()
return temperature_is_fever(temperature, site)
def has_nausea() -> bool:
nausea = input ('Are you experiencing nausea? (enter y or n):').strip().lower()
while nausea not in ('y', 'n'):
print ("Invalid input. Please enter 'y' or 'n'.")
nausea = input ('Are you experiencing nausea? (enter y or n):').strip().lower()
return nausea == 'y'
def has_low_HRV() -> bool:
print ("Please enter 3 heartbeat intervals in ms:")
interval1 = float(input('Enter first interval: '))
interval2 = float(input('Enter second interval: '))
interval3 = float(input('Enter third interval: '))
hrv = compute_HRV(interval1, interval2, interval3)
return hrv < 50
def has_high_cortisol() -> bool:
cortisol_level = float(input("Enter cortisol level in mcg/dL: "))
return cortisol_level > 25
def main() -> None:
if has_fever():
if has_nausea():
print ('Diagnosis: Flu')
else:
print ('Diagnosis: Infection')
else:
if has_low_HRV():
if has_high_cortisol():
print ("Diagnosis: Stress")
else:
print ('Diagnosis: Healthy')
else:
print ('Diagnosis: Healthy')
main()