Conditions

and some recursion

Reading

5. Conditionals and recursion



Video

Learn to Program (19:20-37:00)

Code and Transcript

Most Important Concepts

  • Put a colon at the end of if statements.

    • Indentation should happen automatically in IDE when syntax is correct.

  • Parentheses after if are optional in Python but required in most languages.

  • Indent code that you only want to happen when the condition is true.

  • Code that you only want to happen when the condition is false is indented under the keyword else followed by a colon.

  • It is good programming practice to have a trailing else to handle all other options.

  • Recursion, in general, means an algorithm that can be applied repeatedly. In software, it is a module (function) that calls itself.

Sample Program

# Prof. Vanselow

# An integration of everything I have learned about programming

print("Welcome to my Integration Project!")

print("Enter the choice for what you would like to see")

print("1. Area calculator")

print("2. Output formatting")

print("5. Quit")

userChoice = int(input())

if userChoice == 1:

# side is a variable

# a variable is a name for a location in memory

side = int(input("Enter the length of the side of a square to get the area:"))

area = side * side

print(area)

# You could also do print(side * side)

elif userChoice == 2:

print("Output can be formatted to two decimal places with format(variableName, '.2f')")

price = 599.9999

print("For example, 599.999 becomes:", format(price, '.2f'))

else:

print("Invalid selection. Exiting.")