Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views28 pages

Day 1 Python With Gen AI Notes

Uploaded by

abhyyy559
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views28 pages

Day 1 Python With Gen AI Notes

Uploaded by

abhyyy559
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Python Essentials: A Two-Day Beginner Course

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.

We will cover Python fundamentals in two days:

• 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.

Day 1: Python Essentials – Getting Started (1.5 hours)


Introduction to Python

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.

5. Google Colab: Google Colaboratory (Colab) is an online, cloud-based Jupyter environment:

www.studenttribe.in 1 Python with Gen AI


6. Go to colab.research.google.com (requires a Google account). Create a new Python 3 notebook.
7. Colab runs your code on Google’s servers. It’s great because you don’t need to install anything, and you even get
free access to GPUs which is useful later for AI projects.
8. You can write and execute Python code in a Colab notebook just like in Jupyter. Try adding a code cell in Colab and
running print("Hello from Colab!") as a quick test.

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.

Basic Syntax: Indentation and Comments

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:

# Correct indentation example


if 5 > 2:
print("5 is greater than 2") # This line is indented, so it's inside the
if-block print("This line is outside the if-block") # No indentation, not part
of the if

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:

# This is a comment and will be ignored by Python


print("Hello, World!") # This prints a greeting to the screen

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.

www.studenttribe.in 2 Python with Gen AI


With these basics, you’re ready to write simple Python statements and understand how code blocks are formed.

Variables and Data Types

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 assign variables using . For example:

You can use the function to output variable values, and the function to check a
variable’s type:

Running the above code would display:

Notice that returns a type object that is displayed as for integer,


for float, and so on.

www.studenttribe.in 3 Python with Gen AI


Dynamic Typing: In Python, the same variable can be reassigned to values of different types during execution. For example, you
could do:

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:

print("a//b =", a // b) # 3 (floor division discards the fractional part)


print("a%b =", a % b) # 3 (remainder of 15/4)
print("a**b =", a ** b) # 50625 (15 to the power of 4)

Expected output:

For strings, the operator concatenates (joins) strings, and can repeat them:

Booleans support logical operations: , , . For example, is ,


is , and is . We often get boolean values as results of
comparisons, which leads us to control flow.

www.studenttribe.in 4 Python with Gen AI


Practice Exercises – Variables and Types:
Try these exercises to practice using variables and basic operations. Predict the output, then run the code to check:

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.

Expected outputs: (exercise solutions)

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: if Statements and Loops

Control flow statements allow you to branch (make decisions) and loop (repeat actions) in your code. Python’s control flow

keywords are intuitive: if , elif , else – Conditional Branching

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

www.studenttribe.in 5 Python with Gen AI


Important points:
- A colon : follows each condition line.
- The code block under each branch is indented.
- The elif and else parts are optional. You can have just a single if , or if ... else , etc.
- Conditions use comparison operators ( ==, !=, >, <, >=, <= ) and logical operators ( and, or, not ). Remember:
use == for equality comparison (e.g., x == 5 ), not a single = which is assignment.

Example: Determine if a number is positive, negative, or zero.

If , this will output:

Try changing to a negative value or zero to see the other branches in action.

Another example, using boolean logic:

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:

for variable in sequence:

www.studenttribe.in 6 Python with Gen AI


# code to execute for each element

• 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.

Example: Print numbers 0 through 4.

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:

www.studenttribe.in 7 Python with Gen AI


(Each character printed on a new line.)
Loops

A loop repeats a block of code as long as a condition remains true. The syntax is:

Example: Print numbers 1 to 5 using a while loop.

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.

Using break and continue (Optional)

• 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.

www.studenttribe.in 8 Python with Gen AI


(These are not required in basic scenarios, but good to know they exist. For example, you might break out of a loop early if a
condition is met.)

Practice Exercises – Control Flow:


Try writing the following programs using if statements and loops:

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:

www.studenttribe.in 9 Python with Gen AI


Try modifying the values (e.g., change in exercise 1, or the list in exercise 3) to test your understanding.
Make sure the logic still holds for different inputs.

www.studenttribe.in 10 Python with Gen AI


Hands-On Practice (Day 1) – Putting It All Together

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.

We use the modulo operator to test divisibility. Here’s the code:

Running this code will output:

www.studenttribe.in 11 Python with Gen AI


Take a moment to verify that this output meets the stated requirements (e.g., 3 -> "Fizz", 5 -> "Buzz", 15 -> "FizzBuzz"). You can
see, for example, 3 is replaced with "Fizz", 5 with "Buzz", 15 with "FizzBuzz", and numbers like 1, 2, 4 which are not multiples of
3 or 5 remain unchanged.

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!

Day 2: Python Data Structures & Functions (1.5 hours)


In Day 2, we will cover some of Python’s built-in data structures (which allow you to group and organize data) and how to
write your own functions for reusable code. We’ll also highlight some useful built-in functions.

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.

Basic Operations on Lists:

www.studenttribe.in 12 Python with Gen AI


# Creating a list
fruits = ["apple", "banana", "cherry"] print(fruits)
# ['apple', 'banana', 'cherry']

# Accessing elements by index


print(fruits[0]) # 'apple' (first item)
print(fruits[2]) # 'cherry' (third item)
# print(fruits[3]) # This would cause an IndexError, as there is no index
3

# Modifying elements
fruits[1] = "blueberry"
print(fruits) # ['apple', 'blueberry', 'cherry'] (banana changed to
blueberry)

# Add elements to the list


fruits.append("orange")
print(fruits) # ['apple', 'blueberry', 'cherry', 'orange']

# Remove elements
fruits.remove("blueberry")
print(fruits) # ['apple', 'cherry', 'orange']

# Check length of list print("Number of fruits:", len(fruits))


# Number of fruits: 3

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):

www.studenttribe.in 13 Python with Gen AI


Experiment further by, say, sorting lists or combining them. For instance, would sort
the list alphabetically (in this case, ['a','b','c','d'] which is already sorted). Keep in mind adds
one item; to extend a list with another list or multiple items, you could use or .
Tuples

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 .

Example usage of tuples:

www.studenttribe.in 14 Python with Gen AI


Tuples support most operations that do not modify the data: you can concatenate tuples, iterate over them, check if a value
exists in them, etc. Just no methods like append or remove.

• 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.

Practice Exercises – Tuples:

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.)

www.studenttribe.in 15 Python with Gen AI


Expected outputs/observations:

(If you run the above, you'll see something like:

.)

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:

In this dictionary, keys are , , , and their respective values are , ,


. You can also create an empty dictionary with and add entries later.

www.studenttribe.in 16 Python with Gen AI


• Keys and Values: Keys are typically strings or numbers, and must be unique in a dictionary. Values can be any data
type (and can repeat). Keys should be an immutable type (you can use ints, strings, tuples as keys, but not lists since
lists are mutable and unhashable).

• 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.

Basic Dictionary Operations:

# Check if a key exists


if "Japan" in capitals:
print("Japan is in the dictionary.")

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(): ... .

www.studenttribe.in 17 Python with Gen AI


• When to use dictionaries: Use a dict when you have a set of unique keys that map to values and you want to
retrieve/update by key quickly. Examples: a phone book (name -> number), student records (ID -> data), counting
occurrences of items, etc.

Practice Exercises – Dictionaries:

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 .

Solutions (expected outputs):

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.

www.studenttribe.in 18 Python with Gen AI


• Definition: Sets are created using curly braces {} or the set() constructor. For example: numbers = {1, 2,
3} creates a set with elements 1,2,3. An empty set must be created with set() (since {} creates an empty dict by
default).
• Uniqueness: Sets automatically eliminate duplicate entries. If you try to create a set with duplicates, they will be
stored only once. e.g. s = {1, 2, 2, 3} will result in {1, 2, 3} .
• Mutability: Sets are mutable (you can add or remove elements), but the elements themselves must be immutable
(you can have ints, strings, tuples in a set, but not lists or dicts).

Basic Set Operations:

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).

Practice Exercises – Sets:

www.studenttribe.in 19 Python with Gen AI


1. Create a set prime_set containing prime numbers under 10: {2, 3, 5, 7} . Then add a couple of non-prime
numbers (like 4, 6) to the set. What does the set contain now? (Expected: {2, 3, 4,
5, 6, 7} – note that 4 and 6 will be added, and the set will have six elements.)
2. Given two sets A = {1, 2, 3, 4} and B = {3, 4, 5, 6} , calculate:
3. The union of A and B. (Expected: {1, 2, 3, 4, 5, 6} )
4. The intersection of A and B. (Expected: {3, 4} )
5. The difference A - B. (Expected: {1, 2} because those are in A but not in B)
6. Use a set to remove duplicates from the list vals = [5, 3, 5, 2, 3, 1] . (Expected unique values: {1, 2,
3, 5} though as a set, order is not important.) Solutions (expected outputs):

print("A intersect B:", A & B) # Expected: {3, 4} print("A -


B:", A - B) # Expected: {1, 2} print("B - A:", B - A) #
Expected: {5, 6}

# 3. Removing duplicates using a set


vals = [5, 3, 5, 2, 3, 1]
unique_vals = set(vals)
print("Unique values:", unique_vals)
# Expected output (order not guaranteed): {1, 2, 3, 5}

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.

www.studenttribe.in 20 Python with Gen AI


In Python, we define a function using the keyword:

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) .

Let’s see a simple example: a function that adds two numbers.

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:

www.studenttribe.in 21 Python with Gen AI


In the above, if no name is provided, it defaults to "stranger". (We won’t delve too deep into default parameters here, but be
aware of the possibility.)

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.

Practice Exercises – Functions:

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.)

www.studenttribe.in 22 Python with Gen AI


3. fahrenheit_to_celsius(f) – a function that converts a temperature in Fahrenheit to Celsius using the
formula C = (F - 32) * 5/9 . It should return the Celsius value. (E.g.,
fahrenheit_to_celsius(32) should return 0.0 ; fahrenheit_to_celsius(100) returns
37.777... ) Solutions:

www.studenttribe.in 23 Python with Gen AI


# 2. is_palindrome(s) def is_palindrome(s):
# We compare string to its reverse
return s == s[::-1] # s[::-1] is a quick way to reverse a string in Python

print(is_palindrome("level")) # Expected True print(is_palindrome("hello")) #


Expected False print(is_palindrome("racecar")) # Expected True

# 3. fahrenheit_to_celsius(f) def fahrenheit_to_celsius(f): c = (f - 32) * 5/9


return c

print(fahrenheit_to_celsius(32)) # Expected 0.0


print(fahrenheit_to_celsius(100)) # Expected 37.77777777777778
(approximately)

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.

Introduction to Built-in Functions

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):

• abs(x) – returns the absolute value of a number x . E.g., abs(-5) is 5 .


• min(iterable) and max(iterable) – return the smallest or largest element from a collection (like a list). E.g.,
min([4,7,1]) is 1 , max("banana") is "n" (because "n" is the highest character lexicographically). They also
can take multiple arguments: min(5, 9, 3) -> 3 .
• sum(iterable) – returns the sum of all elements in a collection of numbers. E.g., sum([1,2,3]) is 6 .
• sorted(iterable) – returns a new sorted list from the iterable’s elements. E.g., sorted([3,1,2]) ->
[1,2,3] . (There’s also list.sort() method which sorts in-place.) • round(number, ndigits) –
rounds a number to a given precision. E.g., round(3.14159, 2) > 3.14 .
• enumerate(iterable) – useful in loops, it yields (index, value) pairs as you iterate. E.g., for i, v
in enumerate(['a','b','c']): then i will be index and v the value.
• zip(iter1, iter2, ...) – to iterate in parallel. E.g., zip([1,2,3], ['a','b','c']) yields pairs
(1,'a') , (2,'b') , (3,'c') .

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() ,

www.studenttribe.in 24 Python with Gen AI


str() to convert between types (for example, converting input strings to numbers or vice versa). - sum() , min() , max()
in our practice or as potential tools to solve problems.

Practice Exercises – Built-in Functions:

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:

nums = [4, 1, 7, 0, -3]


print("Min:", min(nums)) # Expected: -3 print("Max:",
max(nums)) # Expected: 7 print("Sum:", sum(nums)) #
Expected: 9

# 3. list() on a string and join


s = "Python"
letters = list(s)
print(letters) # Expected: ['P', 'y', 't', 'h', 'o', 'n']
print("".join(letters)) # Expected: "Python"

# 4. Using enumerate animals = ['cat',


'dog', 'bird'] for idx, animal in
enumerate(animals):
print(f"{idx}: {animal}")
# Expected output:
# 1: dog
# 2: bird

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.

Hands-On Practice (Day 2) – Using Data Structures and Functions

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.

Exercise 1: Statistics with a List.

www.studenttribe.in 25 Python with Gen AI


Write a function get_stats(numbers) that takes a list of numbers and returns a dictionary with some summary
statistics: the mean (average), max, and min of the list. For example, calling get_stats([4, 1,
7, 10]) should return a dictionary like {"mean": 5.5,
"max": 10, "min": 1} . Then, test your function on a couple of lists and print out the results.

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.

Exercise 2: Finding the Longest String.


Write a function find_longest(words) that takes a list of strings and returns the longest string in the list. If there are
multiple with the same length, returning any one of them is fine. For example, find_longest(["cat", "elephant",
"dog", "tiger"]) should return "elephant" since that has the most characters. Test your function with an example
list and print the result.

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:

www.studenttribe.in 26 Python with Gen AI


These exercises demonstrate using lists and dictionaries together (in

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.

www.studenttribe.in 27 Python with Gen AI


Congratulations! You’ve covered a lot of Python fundamentals in these two sessions: - Day 1: You set up your environment,
learned about Python’s syntax (indentation, comments), used variables of different types, and wrote conditional statements
and loops. - Day 2: You learned about essential data structures (lists, tuples, dictionaries, sets) and when to use them, practiced
manipulating these structures, and wrote your own functions to perform specific tasks. We also touched on useful built-in
functions that can save you time.

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/

2 Why Python is Good for AI and ML: The Major 8 Reasons


https://djangostars.com/blog/why-python-is-good-for-artificial-intelligence-and-machine-learning/

3 Python Syntax
https://www.w3schools.com/python/python_syntax.asp

www.studenttribe.in 28 Python with Gen AI

You might also like