Part 1: “if/else”¶
Lets talk about logic flow and start with the simplist example
# Get input from the user
number = int(input("Enter a number: "))
# Check if the number is even or odd
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
5 is an odd number.
this is the simple syntax of the if
and else
statements we can to make to decide if a number is odd or even. Notice the indentation for each statment!
# Get input from the user
number = int(input("Enter a number: "))
# Check if the number is even, odd, or zero
if number == 0:
print("You entered zero.")
elif number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
You entered zero.
you can add to this scheme using the elif
call which works as another possible “bucket” for your number to land in.
You can have as many elif
statements as you want but you only get one else
statement.
Part 2: “Try/Except”¶
Okay but you might be wondering: what if the user doesn’t input a number? what if the user accidently types in a letter or symbol instead?
# Get input from the user, handling non-numeric input
try:
number = int(input("Enter a number: "))
# Check if the number is even, odd, or zero
if number == 0:
print("You entered zero.")
elif number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
except ValueError:
print("Error: Please enter a valid numeric input.")
Error: Please enter a valid numeric input.
Importantly, this try
and except
statement is specific to the ValueError
error message and would not work for other common error messages. Again, notice the indentation scheme!
This is an incredibly useful way of writing code since it lets your user know exactly where they have made some mistake!
Here is another example in which you expect different error messages:
try:
# Attempt to open a file for reading
file_path = input("Enter the path to a file: ")
with open(file_path, 'r') as file:
# Read and print the contents of the file
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except PermissionError:
print(f"Error: You don't have permission to read the file '{file_path}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Error: The file 'sa' was not found.
Part 3: Error Messages!¶
This brings us nicely to our next topic: error messages.
Yes they can be intimidating but if you look past your intial feeling of (embarresment/anxiety/guilt/rage) you can find some pretty useful stuff hidden in the red writing!
In the loop lecture we tried to do the following:
list_Mon = [5, 12, 3, 5, 67, 1, 2, 34, 2, 89]
list_Tues = [15, 45, 21, 2, 8, 9, 54, 99, 17, 51]
list_Wed = [32, 65, 11, 9, 5, 75, 21, 14, 39, 71]
list_Mon = [5, 12, 3, 5, 67, 1, 2, 34, 2, 89]
list_Tues = [15, 45, 21, 2, 8, 9, 54, 99, 17, 51]
list_Wed = [32, 65, 11, 9, 5, 75, 21, 14, 39, 71]
min_age = 2023 - 2001
list_Mon > min_age
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb Cell 14 line 8
<a href='vscode-notebook-cell:/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb#X64sZmlsZQ%3D%3D?line=4'>5</a> list_Wed = [32, 65, 11, 9, 5, 75, 21, 14, 39, 71]
<a href='vscode-notebook-cell:/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb#X64sZmlsZQ%3D%3D?line=6'>7</a> min_age = 2023 - 2001
----> <a href='vscode-notebook-cell:/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb#X64sZmlsZQ%3D%3D?line=7'>8</a> list_Mon > min_age
TypeError: '>' not supported between instances of 'list' and 'int'
So here the error message is a TypeError
and it clearly states that this operation is not supported because you are trying to compare a list
to an int
conviently, it also tells you the line that threw the TypeError
(in this case line 8)
more often that not, you will be working with other people’s code (via packages or public tools) and often the error you get might be local! for example
import cosmolopy
cosmolopy.perturbation.fgrowth(5,"bet")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb Cell 16 line 3
<a href='vscode-notebook-cell:/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb#X65sZmlsZQ%3D%3D?line=0'>1</a> import cosmolopy
----> <a href='vscode-notebook-cell:/Users/jsmonzon/Research/materials-development/Week3/logic_lecture.ipynb#X65sZmlsZQ%3D%3D?line=2'>3</a> cosmolopy.perturbation.fgrowth(5,"bet")
File /opt/homebrew/Caskroom/miniconda/base/envs/subhalos/lib/python3.10/site-packages/cosmolopy/perturbation.py:183, in fgrowth(z, omega_M_0, unnormed)
152 r"""Cosmological perturbation growth factor, normalized to 1 at z = 0.
153
154 Approximate forumla from Carol, Press, & Turner (1992, ARA&A, 30,
(...)
178
179 """
180 #if cden.get_omega_k_0(**) != 0:
181 # raise ValueError, "Not valid for non-flat (omega_k_0 !=0) cosmology."
--> 183 omega = cden.omega_M_z(z, omega_M_0=omega_M_0, omega_lambda_0=1.-omega_M_0)
184 lamb = 1 - omega
185 a = 1/(1 + z)
TypeError: unsupported operand type(s) for -: 'float' and 'str'
See now this error message is the same as before, but it shows that the error doesn’t oginate in this local file, instead it was thrown in line 183 of the cosmolopy.perturbation
code
locally, the error can be traced to line 3, but it orginated elsewhere. These error messages are big reason why Python is so user friendly. Make sure to take a second to understand them!
here are some common ones!
SyntaxError
:
Description: This error occurs when the Python interpreter encounters a syntax that is not valid in the language.
Example: SyntaxError
: invalid syntax
IndentationError
:
Description: Python relies on indentation to define blocks of code. This error occurs when there’s an issue with the indentation level.
Example: IndentationError
: expected an indented block
NameError
:
Description: This error occurs when a variable or name is used before it’s defined.
Example: NameError
: name ‘variable_name’ is not defined
TypeError
:
Description: This error occurs when an operation is performed on an object of an inappropriate type.
Example: TypeError
: unsupported operand type(s) for +: ‘int’ and ‘str’
IndexError
:
Description: This error occurs when trying to access an index that is outside the bounds of a sequence (e.g., list, tuple).
Example: IndexError
: list index out of range
FileNotFoundError
:
Description: This error occurs when trying to open or manipulate a file that doesn’t exist.
Example: FileNotFoundError
: [Errno 2] No such file or directory: ‘filename.txt’
ValueError
:
Description: This error occurs when a function receives an argument of the correct type but an invalid value.
Example: ValueError
: invalid literal for int() with base 10: ‘abc’
KeyError
:
Description: This error occurs when trying to access a dictionary key that doesn’t exist.
Example: KeyError
: ‘key_name’
ZeroDivisionError
:
Description: This error occurs when attempting to divide by zero.
Example: ZeroDivisionError
: division by zero
ModuleNotFoundError
:
Description: This error occurs when trying to import a module that cannot be found.
Example: ModuleNotFoundError
: No module named ‘module_name’