Python Basics - if-else Chains; Slicing; Functions; while & for loops; List & Dictionary Methods; try-except Blocks
February 3, 2025
if Statementsif StatementsTrue or False value.if Statementsif StatementsConditions are expressions that evaluate as booleans.
if Statementsboolean_condition1 = 10 == 20
print(boolean_condition1)
boolean_condition2 = 10 == '10'
print(boolean_condition2)The == is an operator that compares the objects on either side and returns True if they have the same values
Q. What does not (not True) evaluate to?
if Statementsname = "Geneseo"
score = 99
if name == "Geneseo" and score > 90:
print("Geneseo, you achieved a high score.")
if name == "Geneseo" or score > 90:
print("You could be called Geneseo or have a high score")
if name != "Geneseo" and score > 90:
print("You are not called Geneseo and you have a high score")if statements.if Statementsname_list = ["Lovelace", "Smith", "Hopper", "Babbage"]
print("Lovelace" in name_list)
print("Bob" in name_list)in.
in. Is “a” in “Anyone”?if Statementsscore = 98
if score == 100:
print("Top marks!")
elif score > 90 and score < 100:
print("High score!")
elif score > 10 and score <= 90:
pass
else:
print("Better luck next time.")if-else chain:We have seen that certain parts of the code examples are indented.
Code that is part of a function, a conditional clause, or loop is indented.
Indention is actually what tells the Python interpreter that some code is to be executed as part of, say, a loop and not to executed after the loop is finished.
Here’s a basic example of indentation as part of an if statement.
The standard practice for indentation is that each sub-statement should be indented by 4 spaces.
With slicing methods, we can get subset of the data object.
Slicing methods can apply for strings, lists, arrays, and DataFrames.
The above example describes indexing in Python
len() command to get their length:In Python, we can access attributes by using a dot notation (.).
Unlike len(), some functions use a dot to access to strings.
To use those string functions, type (1) the name of the string, (2) a dot, (3) the name of the function, and (4) any arguments that the function needs:
string_name.some_function(arguments).split()split() function to break a string into a list of smaller strings based on some separator.
split() uses any sequence of white space characters—newlines, spaces, and tabs:join()join() collapses a list of strings into a single string.We can extract a substring (a part of a string) from a string by using a slice.
We define a slice by using square brackets ([]), a start index, an end index, and an optional step count between them.
The slice will include characters from index start to one before end:
[ start :] specifies from the start index to the end.[: end ] specifies from the beginning to the end index minus 1.[ start : end ] indicates from the start index to the end index minus 1.letters = 'abcdefghij'
letters[2 : 6 : 2] # From index 2 to 5, by steps of 2 characters
letters[ : : 3] # From the start to the end, in steps of 3 characters
letters[ 6 : : 4 ] # From index 19 to the end, by 4
letters[ : 7 : 5 ] # From the start to index 6 by 5:
letters[-1 : : -1 ] # Starts at the end and ends at the start
letters[: : -1 ][ start : end : step ] extracts from the start index to the end index minus 1, skipping characters by step.
[index]A function can take any number and type of input parameters and return any number and type of output results.
Python ships with more than 65 built-in functions.
Python also allows a user to define a new function.
We will mostly use built-in functions.
print("Cherry", "Strawberry", "Key Lime")
print("Cherry", "Strawberry", "Key Lime", sep = "!")
print("Cherry", "Strawberry", "Key Lime", sep=" ")We invoke a function by entering its name and a pair of opening and closing parentheses.
Much as a cooking recipe can accept ingredients, a function invocation can accept inputs called arguments.
We pass arguments sequentially inside the parentheses (, separated by commas).
A parameter is a name given to an expected function argument.
A default argument is a fallback value that Python passes to a parameter if the function invocation does not explicitly provide one.
while and forwhilecount.while loop compared the value of count to 5 and continued if count was less than or equal to 5.count and then incremented its value by one with the statement count += 1.count with 5.count is now 2, so the contents of the while loop are again executed, and count is incremented to 3.count is incremented from 5 to 6 at the bottom of the loop.count <= 5 is now False, and the while loop ends.input() function gets input from the keyboard.input() is called, the program stops and waits for the user to type something on Console (interactive Python interpreter).breakWhile loop is used to execute a block of code repeatedly until given boolean condition evaluated to False.
while True loop will run forever unless we write it with a break statement.break statement.whilecontinueSometimes, we don’t want to break out of a loop but just want to skip ahead to the next iteration for some reason.
The continue statement is used to skip the rest of the code inside a loop for the current iteration only.
whilebreak Use with elsewhile with else when we’ve coded a while loop to check for something, and breaking as soon as it’s found. numbers = [1, 3, 5]
position = 0
while position < len(numbers):
number = numbers[position]
if number > 4: # Condition changed to checking if the number is greater than 4
print('Found a number greater than 4:', number)
break
position += 1
else: # break not called
print('No number greater than 4 found')for and inSometimes we want to loop through a set of things such as a string of text, a list of words or a list of numbers.
When we have a list of things to loop through, we can construct a for loop.
A for loop makes it possible for you to traverse data structures without knowing how large they are or how they are implemented.
for and infor and inbreakbreak in a for loop breaks out of the loop, as it does for a while loop:for and incontinuecontinue in a for loop jumps to the next iteration of the loop, as it does for a while loop.range()The range() function returns a stream of numbers within a specified range, without first having to create and store a large data structure such as a list or tuple.
This lets us create huge ranges without using all the memory in our computers and crashing our program.
range() returns an iterable object, so we need to step through the values with for … in, or convert the object to a sequence like a list.
for … in range()range() similar to how we use slices: range( start, stop, step ).
start, the range begins at 0.stop; as with slices, the last value created will be just before stop.step is 1, but we can change it.for and inbreak Use with elsewhile, for has an optional else that checks whether the for completed normally.
break was not called, the else statement is run.while and for[expression for item in iterable if condition]{key_expression: value_expression for item in iterable if condition} my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in my_dict.items() if v != 2}append(): Adds an item to the end of the list.remove(): Deletes the first occurrence of value in the list.del statement: Deletes an item by index or a slice of items.update(): Adds new key-value pairs or updates existing ones.del statement: Deletes an item by key.try and excepttry and excepttry and exceptIn some languages, errors are indicated by special function return values.
When we run code that might fail under some circumstances, we also need appropriate exception handlers to intercept any potential errors.
try and excepttry and exceptshort_list = [1, 2, 3]
position = 5
try:
short_list[position]
except:
print('Need a position between 0 and', len(short_list)-1, ' but got',
position)try to wrap your code, and except to provide the error handling:try and exceptshort_list = [1, 2, 3]
position = 5
try:
short_list[position]
except:
print('Need a position between 0 and', len(short_list)-1, ' but got',
position)try block is run.
except block runs.except block is skipped.try and exceptexcept typeSpecifying a plain except with no arguments, as we did here, is a catchall for any exception type.
If more than one type of exception could occur, it’s best to provide a separate exception handler for each.
We get the full exception object in the variable name if we use the form:
try and exceptexcept typetry and exceptexcept typeThe example looks for an IndexError first, because that’s the exception type raised when we provide an illegal position to a sequence.
It saves an IndexError exception in the variable err, and any other exception in the variable other.
The example prints everything stored in other to show what you get in that object.
3 raised an IndexError as expected.two annoyed the int() function, which we handled in our second, catchall except code.try and exceptPython is a general-purpose programming language and is not specialized for numerical or statistical computation.
The core libraries that enable Python to store and analyze data efficiently are:
pandasnumpymatplotlib and seabornpandas
pandas provides Series and DataFrames which are used to store data in an easy-to-use format.numpy
numpy, numerical Python, provides the array block (np.array()) for doing fast and efficient computations;matplotlib and seaborn

matplotlib provides graphics. The most important submodule would be matplotlib.pyplot.seaborn provides a general improvement in the default appearance of matplotlib-produced plots.import statementA module is basically a bunch of related codes saved in a file with the extension .py.
A package is basically a directory of a collection of modules.
A library is a collection of packages
We refer to code of other module/package/library by using the Python import statement.
import statementpip tool