Day 1 Python With Gen AI Notes
Day 1 Python With Gen AI Notes
This guide is designed for college students with some basic programming knowledge, to be covered in two 1.5hour sessions. It
is structured as a Jupyter Notebook with explanations, examples, and exercises.
• Day 1: Getting Started with Python – Python basics, environment setup, syntax, simple data types, and control flow.
• Day 2: Data Structures & Functions – Core built-in data structures (lists, tuples, dictionaries, sets) and how to define
and use functions.
Each section includes examples and practice exercises (with expected outputs) to reinforce learning. You can run the Python
code blocks in a Jupyter Notebook or Google Colab to follow along.
Python is a popular high-level programming language known for its simple syntax and versatility. It’s widely used in web
development, automation, data analysis, and especially in artificial intelligence (AI) and machine learning. Here are a few reasons
Python is great for both AI and general development:
• Easy to Learn and Read: Python’s syntax is clear and beginner-friendly, making it easier to learn than many
languages. Code written in Python is often closer to plain English, improving readability and collaboration.
• Large Ecosystem of Libraries: Python has a rich set of libraries and frameworks. For AI and data science, libraries like
NumPy, Pandas, scikit-learn, TensorFlow, and PyTorch provide powerful tools so you don’t have to reinvent the
wheel.
• Community and Support: Python has a massive community. This means plenty of tutorials, forums, and resources to
help when you’re learning or troubleshooting code.
• Industry Adoption: Python is used by many companies and research labs. Google, for example, uses Python in many
applications (YouTube, Google Search, etc.), and other big names like Instagram, Pinterest, and Reddit have also built
key parts of their platforms with Python 1 . In the AI realm, Python is considered the most popular language for AI and
2
ML according to an expert at IBM , thanks to its ecosystem and ease of use.
Python’s flexibility and power make it a top choice for developers in many domains, which is why it’s an excellent language
to learn early in your programming journey.
Setting Up the Development Environment (Anaconda & Google Colab)
Before coding in Python, you need an environment to write and run your code. Two beginner-friendly options are:
1. Anaconda Distribution: Anaconda is a popular Python distribution that comes with many scientific libraries and tools
pre-installed. It includes Jupyter Notebook, an interactive coding environment ideal for learning and data science. To
set up:
2. Download Anaconda (Python 3.x version) from the official site and install it for your OS (Windows, Mac, or Linux).
3. Launch the Anaconda Navigator or open a terminal/Anaconda Prompt. From there, you can start a Jupyter Notebook:
this will open a browser interface where you can create notebooks and run Python code in cells.
4. Tip: In Jupyter, create a new Python notebook and try running a simple code cell (for example, print("Hello,
Python!") ) to verify everything is working.
Both Anaconda and Colab will let you execute the example code and exercises in this guide. For beginners, Colab is convenient
(no setup hassles), whereas Anaconda gives you a full Python environment on your local machine. Feel free to use either. The
code provided will work in both.
Python’s syntax has some distinctive features that are important to know from the start:
• Indentation: Python uses indentation (spaces or tabs at the beginning of a line) to define code blocks. Unlike many
languages that use braces {} or keywords, Python relies on indentation to group statements. All code inside a loop,
function, or if-statement must be indented equally. If you misalign indentation, you’ll get an
IndentationError . For example:
In the above code, the print("5 is greater...") runs only if the condition is true (because it’s indented under the
if ). The second print always runs after, since it’s not indented under the if .
3
Consistent indentation is crucial . By convention, we use 4 spaces per indent level (Jupyter/Colab will do this automatically
when you press Tab).
• Comments: Comments are notes in the code that the Python interpreter ignores. They are used to explain what the
code is doing or to leave reminders. In Python, any text after a # on a line is a comment. For example:
Using comments is good practice to make your code understandable. You can also create multi-line comments by using triple
quotes """ ... """ as a documentation string (often at the start of functions or scripts), but for simple notes, # is sufficient.
• Line Breaks: Python generally uses the end of line to mark the end of a statement. You don’t need a semicolon
( ; ) at the end of each line (unlike C/C++/Java). Simply press Enter and start a new line. If you do want to break a long
statement into multiple lines, you can use a backslash \ or just wrap the expression in parentheses. But as a beginner,
you can usually keep one statement per line.
• Case Sensitivity: Python is case-sensitive. For example, a variable named Data is different from data . Keep this
in mind when naming and calling variables or functions.
Variables are used to store data in Python. You can create a variable by assigning a value to a name using the = operator. Unlike
some languages, Python doesn’t require you to declare the type of a variable upfront – the type is inferred from the value
you assign (Python is dynamically-typed).
Let’s look at some basic data types in Python and how to work with them:
•Integer ( ) – whole numbers, e.g., , , .
•Float ( ) – decimal (floating-point) numbers, e.g., , , .
•String ( ) – sequence of characters (text) enclosed in quotes, e.g., , .
•Boolean ( ) – logical True/False values, written as or .
You can use the function to output variable values, and the function to check a
variable’s type:
This flexibility is powerful, but be careful: changing types can lead to errors if not intended.
Basic Operations: Python supports the usual arithmetic operations on numeric types: addition ,
subtraction , multiplication , division , integer floor division , modulo (remainder) , and
exponentiation . For example:
Expected output:
For strings, the operator concatenates (joins) strings, and can repeat them:
1. Create variables a = 10 , b = 3 . Print their sum, difference, and product. What are the results?
2. Define text = "Hello" and text2 = "World" . Print the concatenation of text and text2 with a space in
between. (Hint: you can do text + " " + text2 )*.
3. What is the type of 3.0 ? And what about the result of 3 + 0.0 ? Use print(type(...)) to find out.
a = 10
b = 3
print(a + b) # Expected output: 13
print(a - b) # Expected output: 7
Run these in a code cell to verify the results and make sure you understand why each output is as shown.
Control flow statements allow you to branch (make decisions) and loop (repeat actions) in your code. Python’s control flow
Use an if statement to execute code only if a certain condition is true. Optionally, use elif (else-if) and else to check multiple
conditions or provide a fallback. The syntax is:
if condition1:
# code to execute if condition1 is True
elif condition2:
# code to execute if condition1 was False but condition2 is True
else:
# code to execute if none of the above conditions were True
Try changing to a negative value or zero to see the other branches in action.
This prints given the values above, because the person is 18 or older and a citizen
(both conditions must be true for the to pass). If either condition were false (e.g., age = 16 or citizen =
False), the output would be .
for Loops
A for loop in Python is used to iterate over a sequence (such as a list or a range of numbers) and execute a block of code for
each element in the sequence. The syntax is:
• Iterating a range of numbers: Use the built-in range() function. For example, range(5) generates the sequence
0,1,2,3,4 (five numbers, up to but not including 5). You can also call range(start, stop) or range(start,
stop, step) for custom sequences.
Output:
• Iterating over a list (or any iterable): If you have a list of elements, you can loop through them directly.
Example:
Output:
During each loop iteration, the variable takes the value of the next element in the list. The loop
ends when all items have been processed.
You can even loop over the characters in a string (since strings are sequences of characters):
Output:
A loop repeats a block of code as long as a condition remains true. The syntax is:
This loop will run as follows: it checks , and if true, prints the message and increments
. Once becomes 6, the condition is False and the loop stops. The output will be:
Be careful with while loops to avoid infinite loops. If the loop’s condition never becomes False, the loop will
run forever. For instance, if we forgot to increment , the condition would stay True
and the loop wouldn’t stop. Always ensure something in the loop updates a variable so that the condition
will eventually fail.
• break can be used inside loops to exit the loop immediately. e.g., you find what you’re looking for and break out.
• continue skips the rest of the loop block and moves to the next iteration.
1. Even or Odd? – Write a program that sets an integer n . Use an if statement to print "Even" if n is even, and "Odd"
if n is odd. (Hint: use the modulo operator % . n % 2 is 0 when n is even.)
2. Looping with a condition: – Using a for loop, print the squares of numbers from 1 to 5. The output should be: 1, 4,
9, 16, 25 each on a new line.
3. Sum of a list: – Given a list of numbers, e.g. nums = [3, 8, 2, 5] , write a loop (for or while) to calculate the
total sum of all numbers in the list, and print the result. (Expected result for this example list: 18.)
4. Countdown using while: – Use a while loop to print a countdown from 5 to 1, then print "Blast off!" .
Expected outputs:
Now that we’ve covered variables, basic data types, and control flow, let’s do a more involved exercise that combines these
concepts.
Project: FizzBuzz (Classic Problem) – This is a common beginner problem that uses loops and conditionals:
Print the numbers from 1 to 20, but with a twist. For multiples of 3, print " Fizz " instead of the number. For
multiples of 5, print " Buzz``. For numbers which are multiples of both 3 and 5,
print " FizzBuzz`". For other numbers, just print the number itself.
This problem tests your understanding of if/elif/else and looping. Try to write it on your own first.
Solution approach:
We need to loop from 1 to 20 and check each number: - If a number is divisible by 3 and 5 (i.e., by 15), print "FizzBuzz".
- Else if divisible by 3, print "Fizz".
- Else if divisible by 5, print "Buzz".
- Otherwise, print the number.
Feel free to experiment by changing the range or the conditions to get comfortable with loops and ifstatements. This concludes
Day 1 content – you’ve learned the essential building blocks of Python programming!
Lists
A list in Python is an ordered, mutable collection of items. Lists are very versatile and one of the most commonly used data
structures.
• Definition: Lists are created using square brackets [] , with elements separated by commas. e.g. numbers = [1,
2, 3, 4] or mixed = [10, "hello", 3.5] . A list can hold items of any
type (even mixed types as shown), though often you’ll keep them homogeneous.
• Order: Lists maintain the order of insertion. You can access elements by their index (position).
Python uses zero-based indexing, meaning the first element is index 0 .
• Mutability: Lists are mutable, meaning you can change their content (add, remove, or modify elements) after creation.
# Modifying elements
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry'] (banana changed to
blueberry)
# Remove elements
fruits.remove("blueberry")
print(fruits) # ['apple', 'cherry', 'orange']
Explanation: We created a list of fruits. We accessed elements by index (0 and 2). We then changed the item at index 1 ("banana")
to "blueberry". We used append() to add a new item to the end. We removed an item by value using remove() . Finally, we
used the built-in len() function to get the number of items in the list.
Lists have many useful methods (like append , remove , sort , etc.), but these are a few basics. You can also concatenate
lists with + and repeat them with * similarly to strings. e.g. [1,2] + [3,4] gives [1,2,3,4] .
• When to use lists: Use a list to store a collection of items when order matters or when you might need to change the
contents. For example, a list of sensor readings, a list of student names, etc., where you may add/remove or iterate in
order.
Practice Exercises – Lists:
1. Create a list nums containing the numbers [10, 20, 30] . Append the number 40 to the list, then change the
second element (index 1) to 25 . Print the final list. (Expected result:
[10, 25, 30, 40] .)
2. Given the list words = ["red", "green", "blue"] , write code to add "yellow" to the end of the list and
remove "green" from the list. Print the resulting list. (Expected output: ['red',
'blue', 'yellow'] .)
3. Use a loop to iterate over the list letters = ['a', 'b', 'c', 'd'] and print each element in uppercase.
(Expected output: A B C D on separate lines.) Solutions (with expected outputs):
A tuple is very similar to a list in that it is an ordered collection of elements. The key difference is that tuples are immutable –
once created, the elements of a tuple cannot be changed (no item assignment, append, etc.).
• Definition: Tuples are created using parentheses () , e.g. point = (3, 4) or values = ("Alice", 25,
5.0) . You can also create a tuple without parentheses by just separating values with commas (e.g. t = 1, 2,
3 ), but using () is clearer. For an empty tuple use () , and for a single-element tuple, include a trailing comma like
(5,) (to distinguish from just an expression in parentheses).
• Order and Access: Tuples maintain order and you can access elements by index just like lists (e.g., point[0] gives
the first element).
• Immutability: You cannot add, remove, or modify elements once the tuple is created. Attempting point[0] = 5
for a tuple would result in a TypeError .
• When to use tuples: Use a tuple for a collection of items that shouldn’t change throughout the program. Tuples are
great for representing fixed collections of attributes (like a coordinate (x,y), or a database record). They are also used
when you need to ensure data integrity (accidental changes avoided). Additionally, Python functions often return tuples
when you need to return multiple values.
1. Create a tuple rgb representing an RGB color, e.g. (255, 0, 128) . Print the first value (red component) of the
tuple.
2. Given person = ("John", 30, "New York") , unpack this tuple into three variables name, age, city
and print them in a sentence: e.g., "John is 30 years old and lives in New York." .
3. Try creating a tuple and then attempting to change one of its elements (e.g., t = (1,2,3) and then t[0] = 99 ).
What error do you get? (You should get a TypeError, because tuples do not support item assignment.)
.)
Reflect on how tuples differ from lists. If you find you need to change data, use a list; if your data is fixed and just needs to be
grouped, a tuple is a perfect choice.
Dictionaries
A dictionary in Python is a collection of key-value pairs. It allows you to map arbitrary keys (like names or IDs) to values (like
phone numbers or student grades). Dictionaries are extremely useful for fast lookups and organizing data by named attributes.
• Definition: Dictionaries are created with braces {} containing key-value pairs separated by colons. Example:
• Accessing Values: Use dict_variable[key] to get the value associated with a key. For example,
student["name"] would give "Alice" . If a key is not found, Python raises a KeyError , so you might use
dict_variable.get(key) which returns None (or a default value you provide) if the key isn’t present.
• Mutability: Dictionaries are mutable. You can add, modify, or remove key-value pairs.
Explanation: We created a dictionary of country capitals. We accessed the capital of Japan using the key
"Japan" . We then added a new entry for Germany. We updated the capital of India. We removed France from the dictionary
using pop(key) . Finally, we showed how to check for a key’s existence with the in operator.
You can iterate over dictionaries as well: - Looping through keys: for country in capitals: ... will iterate through
keys.
- Looping through values: for city in capitals.values(): ... .
- Looping through key-value pairs: for country, city in capitals.items(): ... .
1. Create a dictionary scores with three entries: e.g., "Alice": 95, "Bob": 78, "Charlie":
87 . Retrieve and print Alice’s score. Then add a new entry for "Dave": 92 and print the updated dictionary.
2. Given a dictionary inventory = {"apple": 5, "banana": 2} , write code to update the count of "apple"
to 3 (someone bought 2 apples), and add a new item "orange" with count 10. Print the final dictionary.
3. Use a loop to print all key-value pairs in the inventory dictionary from the previous exercise in the format "item
-> count" . For the given example, the output lines should be: apple -> 3 , banana -> 2 , orange ->
10 .
Notice that the order of keys in the printed dictionaries might not exactly match the insertion order in versions of Python before
3.7. In Python 3.7+, insertion order is preserved in dictionaries. Regardless, when printing a dict or looping without sorting, the
order might appear arbitrary, so focus on whether the keyvalue pairs are correct.
Sets
A set is an unordered collection of unique elements. If you want to store a bunch of items but are only interested in each item
appearing once (no duplicates) and you don’t care about order, a set is the appropriate data structure.
In the above, after adding "bird", the set contains {'bird','cat','dog','elephant'} (though it might print in a different order since sets
are unordered). Adding "cat" again did nothing because "cat" was already present (no duplicates allowed). Removing "dog"
deletes that element. Membership tests with in and not in are very fast with sets, which is useful for lookup operations.
Sets also support mathematical set operations like union, intersection, difference: - set_a | set_b for union (all elements
in either), - set_a & set_b for intersection (elements common to both), - set_a - set_b for difference (elements in
set_a but not in set_b).
• When to use sets: Use a set when you need to maintain a collection of unique items and order doesn’t matter.
Common use cases: removing duplicates from a list, membership testing (checking if an item is present), or
performing mathematical set operations (like finding common elements between two lists).
One thing to note: converting a list to a set (as in exercise 3) loses the original order, since sets are unordered. If you need to
preserve order while removing duplicates, a common trick is to use a dictionary or OrderedDict, but that’s beyond our current
scope. For now, know that sets are optimal for uniqueness and membership checks.
Functions
Functions allow you to reuse code and make programs modular. A function is a block of code that executes when you call it, and
it can optionally take inputs (parameters) and return an output.
Key points:
- Function definition starts with followed by the function name and parentheses . Any parameters
go inside the parentheses. End the line with a colon .
- The function body is indented.
- You can use a return statement to send a result back to the caller. If a function reaches the end without a return , it
returns None by default.
- Functions are "called" by using their name followed by parentheses, with any required arguments inside.e.g., result =
function_name(arg1, arg2) .
Here, takes two parameters and , and returns their sum. We call
, which should return 12, and we store that in . The function’s docstring (in triple quotes) is optional
but recommended to describe the function’s purpose.
Another example: a function with no parameters and no return (just performs an action): without arguments.
This function simply prints a message. It doesn’t return anything (so it implicitly returns ). It’s called
Functions can also have default parameter values, allowing some arguments to be optional. For instance:
Parameters vs Arguments:
- Parameters are the variable names in the function definition (e.g., a and b in def add_numbers(a, b): ).
- Arguments are the actual values you pass to the function when calling it (e.g., 5 and 7 when calling add_numbers(5, 7) ).
Return Values:
When a function uses return , it hands back a value. You can capture that value in a variable or use it directly. If a function
does not explicitly return, the value None is returned. For example:
We could also write this function more concisely as since the expression itself
evaluates to True/False, but the above shows the structure clearly.
Scope: Variables created inside a function are local to that function (they disappear after the function returns). The function can
access variables from the outer scope if not shadowed, but it’s best practice to pass in everything needed via parameters, and
return results rather than relying on or modifying global variables.
• Why use functions? Functions help organize code into logical pieces, avoid repetition (write once, use many times),
and make code easier to test and maintain. In larger programs and in AI projects, you’ll write functions for tasks like
preprocessing data, training a model, etc., to reuse those steps with different data.
Write the following simple functions and test them with a few examples:
1. square(n) – a function that takes a number n and returns its square. (e.g., square(5) should return 25 .)
2. is_palindrome(s) – a function that takes a string s and returns True if the string is a palindrome (reads the
same forwards and backwards) and False otherwise. (Test examples: is_palindrome("level") -> True,
is_palindrome("hello") -> False.)
Take a close look especially at the palindrome function. We used slicing s[::-1] to reverse the string (this is an idiom in
Python). There are other ways to check for a palindrome (like loop from start to end), but this one-liner is neat. If it’s
confusing, remember you can always write it using a loop or other methods with the knowledge you have.
Python comes with a large number of built-in functions that you can use without any import. We’ve already used several:
print() , len() , type() , range() , int() , str() , etc. Built-in functions provide convenient ways to perform
common tasks. Here’s a quick overview of some useful ones (beyond those we have seen):
And many more. You can see the full list by typing dir(__builtins__) in a Python session, or refer to Python’s
documentation.
Conversion functions: int() , float() , str() , list() , tuple() , dict() can convert values from one type to
another when possible. For example, int("42") converts the string "42" to the integer 42 , and list("hello") would
convert to ['h','e','l','l','o'] .
Using help() : In Python, you can use the built-in help() function to get information about other functions. For example,
help(len) will display the documentation for the len function. This can be very handy to learn about new functions or remind
yourself of usage. (In Jupyter/Colab, you can also type len? in a cell to get help for len .)
We have already used some of these built-ins in our examples and exercises: - len(some_list) to get length of a list or
string. - range(n) to get a range of numbers for looping. - print() to output to console. - type() to check type. - int() ,
1. Use min and max on a list of numbers. For example, given nums = [4, 1, 7, 0, -3] , find the minimum and
maximum values. (Expected: min is -3, max is 7.)
2. Use sum to compute the total of the same nums list. (Expected sum: 4+1+7+0+(-3) = 9.)
3. Given a string s = "Python" , use list() on it. What is the result? Then use "".join() on the resulting list to
get back the string. (Expected: list("Python") gives
['P','y','t','h','o','n'] ; joining that list with "".join(...) returns "Python" .)
4. Try the enumerate function in a loop over a list animals = ['cat', 'dog', 'bird'] to print index and
animal, e.g., "0: cat", "1: dog", etc.
Solutions:
After practicing with built-in functions, you should have an appreciation for how much they can simplify tasks (imagine summing
a list without sum , you’d write a loop as we did earlier – which is fine, but sum is concise and likely optimized in C). As you
continue learning Python, you will discover many more built-ins and library functions that will make your programs shorter and
more efficient.
To wrap up Day 2, let’s do some hands-on exercises that utilize data structures and functions together. These exercises will
demonstrate how these concepts can be combined to solve slightly more complex tasks, similar to small real-world problems.
Hints:
- Mean can be calculated as sum(numbers) / len(numbers) (ensure len(numbers) is not zero to avoid division by
zero).
- Use the built-in max() and min() for simplicity.
- The returned dictionary can have keys "mean", "max", "min" with corresponding values.
Hint:
- You can iterate through the list and track the longest word found so far (and its length). Alternatively, youcould use the max()
function with a custom key: max(words, key=len) will return the longest word by length. But try the manual approach
for practice.
Solutions:
When you run the tests above, you should see that returns the correct dictionaries and
returns for the example list. We included handling for edge cases like
empty lists (returning an empty dict or accordingly). In real-world scenarios, you might want to
handle such cases more robustly (e.g., raise an exception or return with a warning), but this is fine
for our practice.
get_stats ) and writing functions that operate on data structures. In AI and data science, you will often write functions to
compute statistics or transform data (like this stats function) and work with collections of data (lists, dicts, etc.). For instance,
computing mean, max, min is a basic task in exploratory data analysis, and finding longest string might be analogous to finding
a max value under some criterion.
With these basics, you have a solid foundation to explore more advanced topics. From here, you can move on to libraries like
NumPy for numerical computing, Pandas for data analysis, or even dive into machine learning with libraries like scikit-learn or
TensorFlow/PyTorch. The concepts you learned (loops, conditionals, functions, data structures) will all be directly applicable
when writing code in those areas.
Keep practicing by building small projects or solving coding challenges. Happy coding with Python!
1 Python vs PHP for Web Development: What to Choose for Custom Backend - Skywell Software
https://skywell.software/blog/python-vs-php-for-web-development/
3 Python Syntax
https://www.w3schools.com/python/python_syntax.asp