Python Programing
Programming Python Basics

Python Tutorial – 2 : Learn the Fundamentals

Introduction:
Python is a high-level, interpreted programming language that is easy to learn and widely used in various fields. This course is designed to help you learn the fundamentals of Python programming. It covers essential topics such as manipulating lists, dictionaries, tuples, strings, list comprehension, enumerate and zip, and functional programming using map, filter, and reduce.

  • Lesson 01: Manipulating Lists
  • Lesson 02: Dictionaries
  • Lesson 03: Tuples I
  • Lesson 04: Strings
  • Lesson 05: List Comprehension
  • Lesson 06: Enumerate and Zip
  • Lesson 07: Map, Filter, and Reduce

By the end of this course, you will have a solid foundation in Python programming and be able to solve basic programming problems.

For installation of Python – How to Install Python?

For 1st step in Learning Python – Python Tutorial 1

Lesson 01: Manipulating Lists
In this lesson, you will learn how to create and manipulate lists in Python. You will learn how to access elements in a list, slice a list, add or remove elements, sort a list etc. You will also be given assignments and solutions to practice your skills.

Lists are a collection of items in a specific order. Python lists can store any type of data, including numbers, strings, and other lists. This lesson will focus on manipulating lists by adding, removing, and modifying items.

Part 1: Creating and Accessing Lists To create a list in Python, use square brackets [] and separate each item with a comma. For example:

my_list = ['apple', 'banana', 'orange']

To access an item in a list, use its index number in square brackets []. Index numbers start at 0, so the first item in a list has an index of 0. For example:

print(my_list[0])  # Output: 'apple'

You can also use negative index numbers to access items from the end of the list. For example:

print(my_list[-1])  # Output: 'orange'

Part 2: Adding and Removing Items from Lists To add an item to the end of a list, use the append() method. For example:

my_list.append('grape')
print(my_list)  # Output: ['apple', 'banana', 'orange', 'grape']

To insert an item at a specific index in a list, use the insert() method. For example:

my_list.insert(1, 'kiwi')
print(my_list)  # Output: ['apple', 'kiwi', 'banana', 'orange', 'grape']

To remove an item from a list, use the remove() method and specify the item to be removed. For example:

my_list.remove('banana')
print(my_list)  # Output: ['apple', 'kiwi', 'orange', 'grape']

To remove the last item from a list, use the pop() method. For example:

last_item = my_list.pop()
print(my_list)     # Output: ['apple', 'kiwi', 'orange']
print(last_item)   # Output: 'grape'

Part 3: Modifying Items in Lists To change an item in a list, use its index number and assign a new value to it. For example:

my_list[1] = 'pear'
print(my_list)  # Output: ['apple', 'pear', 'orange']

You can also change a range of items in a list by using slicing. For example:

my_list[1:3] = ['grape', 'banana']
print(my_list)  # Output: ['apple', 'grape', 'banana']

Assignments:

  • Create a list of your favorite foods and print the first and last items.
  • Add a new food to your list and print the updated list.
  • Remove a food from your list and print the updated list.
  • Modify a food in your list and print the updated list.

Solutions:

favorite_foods = ['pizza', 'sushi', 'ice cream']
print(favorite_foods[0])    # Output: 'pizza'
print(favorite_foods[-1])   # Output: 'ice cream'
favorite_foods = ['pizza', 'sushi', 'ice cream']
favorite_foods.append('tacos')
print(favorite_foods)   # Output: ['pizza', 'sushi', 'ice cream', 'tacos']
favorite_foods = ['pizza', 'sushi', 'ice cream']
favorite_foods.remove('sushi')
print(favorite_foods)   # Output: ['pizza','ice cream']

Lesson 02: Dictionaries
Dictionaries are another type of data structure in Python that allow you to store data as key-value pairs. This lesson will focus on creating dictionaries, accessing and modifying values, and performing operations on dictionaries.

Part 1: Creating Dictionaries To create a dictionary in Python, use curly braces {} and separate each key-value pair with a colon. For example:

my_dict = {'apple': 1, 'banana': 2, 'orange': 3}

You can also create an empty dictionary and add key-value pairs later. For example:

my_dict = {}
my_dict['apple'] = 1
my_dict['banana'] = 2
my_dict['orange'] = 3

Part 2: Accessing and Modifying Values in Dictionaries To access a value in a dictionary, use its key in square brackets []. For example:

print(my_dict['apple'])  # Output: 1

To modify a value in a dictionary, use its key and assign a new value to it. For example:

my_dict['apple'] = 4
print(my_dict)  # Output: {'apple': 4, 'banana': 2, 'orange': 3}

Part 3: Operations on Dictionaries Dictionaries in Python have several built-in methods that allow you to perform various operations on them. Some common methods include:

  • keys(): Returns a list of all the keys in the dictionary.
  • values(): Returns a list of all the values in the dictionary.
  • items(): Returns a list of all the key-value pairs in the dictionary as tuples.

For example:

print(my_dict.keys())   # Output: ['apple', 'banana', 'orange']
print(my_dict.values()) # Output: [4, 2, 3]
print(my_dict.items())  # Output: [('apple', 4), ('banana', 2), ('orange', 3)]

Assignments:

  1. Create a dictionary of your favorite books and their authors.
  2. Access and print the author of your favorite book.
  3. Modify the author of your favorite book and print the updated dictionary.
  4. Use the keys() method to print a list of all the books in your dictionary.

Solutions:

favorite_books = {'To Kill a Mockingbird': 'Harper Lee', 'The Great Gatsby': 'F. Scott Fitzgerald', 'Pride and Prejudice': 'Jane Austen'}
print(favorite_books['To Kill a Mockingbird'])   # Output: 'Harper Lee'
favorite_books['To Kill a Mockingbird'] = 'Harper Lee (modified)'
print(favorite_books)   # Output: {'To Kill a Mockingbird': 'Harper Lee (modified)', 'The Great Gatsby': 'F. Scott Fitzgerald', 'Pride and Prejudice': 'Jane Austen'}
print(favorite_books.keys())   # Output: dict_keys(['To Kill a Mockingbird', 'The Great Gatsby', 'Pride and Prejudice'])

Lesson 03: Tuples in Python

Introduction: Tuples are another type of data structure in Python that are similar to lists but with one key difference: they are immutable. This means that once a tuple is created, you cannot change its values. This lesson will focus on creating tuples, accessing values, and performing operations on tuples.

Part 1: Creating Tuples To create a tuple in Python, use parentheses () and separate each value with a comma. For example:

my_tuple = (1, 2, 3)

You can also create a tuple with a single value by including a trailing comma. For example:

my_tuple = (1,)

Part 2: Accessing Values in Tuples To access a value in a tuple, use its index in square brackets []. Tuples are zero-indexed, meaning the first element has an index of 0. For example:

print(my_tuple[0])  # Output: 1

Part 3: Operations on Tuples Tuples in Python have several built-in methods that allow you to perform various operations on them. However, since tuples are immutable, these methods return new tuples instead of modifying the original tuple. Some common methods include:

  • count(): Returns the number of times a value appears in the tuple.
  • index(): Returns the index of the first occurrence of a value in the tuple.

For example:

my_tuple = (1, 2, 3, 2)
print(my_tuple.count(2))   # Output: 2
print(my_tuple.index(3))   # Output: 2

Assignments:

  1. Create a tuple of your favorite colors.
  2. Access and print the second color in your tuple.
  3. Use the count() method to print the number of times your favorite color appears in your tuple.
  4. Use the index() method to print the index of the first occurrence of your favorite color in your tuple.

Solutions:

favorite_colors = ('blue', 'green', 'purple', 'pink')
print(favorite_colors[1])   # Output: 'green'
print(favorite_colors.count('blue'))   # Output: 1
print(favorite_colors.index('purple'))   # Output: 

Lesson 04: Strings in Python

Introduction: Strings are a type of data structure in Python that are used to represent text. In this lesson, we will learn how to create and manipulate strings in Python.

Part 1: Creating Strings To create a string in Python, simply surround your text with either single quotes (‘) or double quotes (“). For example:

my_string = "Hello, World!"

Part 2: Accessing Characters in Strings To access a specific character in a string, use its index in square brackets []. Strings are also zero-indexed, meaning the first character has an index of 0. For example:

print(my_string[0])  # Output: 'H'

Part 3: Slicing Strings You can also access a range of characters in a string using slicing. Slicing is done by specifying the start and end indices separated by a colon (:). For example:

print(my_string[0:5])  # Output: 'Hello'

If you omit the start index, it will default to 0. If you omit the end index, it will default to the end of the string.

Part 4: Concatenating Strings You can concatenate (join) two or more strings together using the + operator. For example:

string1 = "Hello"
string2 = "World"
print(string1 + " " + string2)  # Output: 'Hello World'

Assignments:

  1. Create a string that contains your full name.
  2. Print the first letter of your first name.
  3. Print your last name using slicing.
  4. Concatenate your first and last name together with a space in between.

Solutions:

full_name = "John Smith"
print(full_name[0])   # Output: 'J'
print(full_name[5:])   # Output: 'Smith
first_name = full_name[:4]
last_name = full_name[5:]
print(first_name + " " + last_name)   # Output: 'John Smith'

Lesson 05: List Comprehension in Python

Introduction: List comprehension is a concise and efficient way to create lists in Python. It allows you to create a new list by applying an expression to each element of an existing list. In this lesson, we will learn how to use list comprehension in Python.

Part 1: Basic List Comprehension The basic syntax for list comprehension is to enclose an expression in square brackets [], followed by a for loop that iterates over an existing list. For example, to create a list of squares of numbers from 1 to 5, you can use list comprehension as follows:

squares = [x**2 for x in range(1, 6)]
print(squares)  # Output: [1, 4, 9, 16, 25]

Part 2: Conditional List Comprehension You can also add a conditional statement to list comprehension to filter the elements of the existing list that you want to include in the new list. For example, to create a list of even numbers from 1 to 10, you can use conditional list comprehension as follows:

evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)  # Output: [2, 4, 6, 8, 10]

Part 3: Nested List Comprehension You can also use nested list comprehension to create lists of lists. For example, to create a 3×3 identity matrix, you can use nested list comprehension as follows:

matrix = [[1 if i == j else 0 for j in range(3)] for i in range(3)]
print(matrix)  # Output: [[1, 0, 0], [0, 1, 0], [0, 0, 1]]

Assignments:

  1. Create a list of the first 10 even numbers using list comprehension.
  2. Create a list of the first 5 multiples of 3 using list comprehension.
  3. Use nested list comprehension to create a 4×4 identity matrix.

Solutions:

even_numbers = [x for x in range(2, 21, 2)]
print(even_numbers)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
multiples_of_3 = [x*3 for x in range(1, 6)]
print(multiples_of_3)  # Output: [3, 6, 9, 12, 15]
identity_matrix = [[1 if i == j else 0 for j in range(4)] for i in range(4)]
print(identity_matrix)  # Output: [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]

Lesson 06: Enumerate and Zip in Python

Introduction: In Python, there are two built-in functions called “enumerate” and “zip” that are used to simplify the process of iterating over multiple lists simultaneously. In this lesson, we will learn how to use these functions.

Part 1: Enumerate The “enumerate” function is used to add a counter to an iterable object, such as a list, tuple, or string. The function returns an enumerate object, which is an iterator that yields pairs of the form (index, element). Here is an example of how to use the enumerate function:

fruits = ["apple", "banana", "cherry"]
for i, fruit in enumerate(fruits):
    print(i, fruit

Output:

0 apple
1 banana
2 cherry

In this example, the “enumerate” function is used to add a counter to the “fruits” list. The for loop then iterates over the enumerated list, assigning the index to “i” and the fruit to “fruit”.

Part 2: Zip The “zip” function is used to combine two or more iterables into a single iterable. The function returns a zip object, which is an iterator that yields tuples containing elements from each of the iterables. Here is an example of how to use the zip function:

names = ["John", "Mary", "David"]
ages = [25, 32, 18]
for name, age in zip(names, ages):
    print(name, age)

Output:

John 25
Mary 32
David 18

In this example, the “zip” function is used to combine the “names” and “ages” lists into a single iterable. The for loop then iterates over the zipped list, assigning the name to “name” and the age to “age”.

Assignments:

  1. Use the enumerate function to print the index and the value of each letter in the word “Python”.
  2. Use the zip function to create a list of tuples containing the first 3 letters of the alphabet and their corresponding ASCII codes.
  3. Use the zip function to create a list of tuples containing the values from the lists [1, 2, 3] and [4, 5, 6].

Solutions:

word = "Python"
for i, letter in enumerate(word):
    print(i, letter)

Output:

0 P
1 y
2 t
3 h
4 o
5 n
letters = ['a', 'b', 'c']
ascii_codes = [ord(letter) for letter in letters]
letter_ascii = list(zip(letters, ascii_codes))
print(letter_ascii)

Output:

[('a', 97), ('b', 98), ('c', 99)]
list1 = [1, 2, 3]
list2 = [4, 5, 6]
zipped_list = list(zip(list1, list2))
print(zipped_list)

Output:

[(1, 4), (2, 5), (3, 6)]

Lesson 07: Map, Filter, and Reduce in Python

Introduction: Python provides three built-in functions, namely “map”, “filter”, and “reduce”, which can be used to perform operations on sequences. These functions are particularly useful for working with large datasets and functional programming. In this lesson, we will explore these functions.

Part 1: Map The “map” function is used to apply a function to each element of a sequence and returns a new sequence with the transformed elements. Here is an example of how to use the map function:

numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)

Output:

[1, 4, 9, 16, 25]

In this example, the “map” function is used to apply the lambda function to each element of the “numbers” list, which squares each number.

Part 2: Filter The “filter” function is used to apply a function to each element of a sequence and returns a new sequence with only the elements that satisfy a certain condition. Here is an example of how to use the filter function:

Output:

numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
[2, 4]

In this example, the “filter” function is used to apply the lambda function to each element of the “numbers” list, which checks if the number is even or not.

Part 3: Reduce The “reduce” function is used to apply a function to the elements of a sequence in a cumulative way, such that the result of each operation is passed on to the next operation. Here is an example of how to use the reduce function:

from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x*y, numbers)
print(product)

Output:

120

In this example, the “reduce” function is used to apply the lambda function to the elements of the “numbers” list, which multiplies each element together.

Assignments:

  1. Use the map function to convert a list of Celsius temperatures to Fahrenheit temperatures, given the conversion formula F = 1.8*C + 32.
  2. Use the filter function to create a list of all the even numbers in a list of integers.
  3. Use the reduce function to find the maximum value in a list of integers.

Solutions:

celsius_temps = [25, 30, 35, 40]
fahrenheit_temps = list(map(lambda x: 1.8*x + 32, celsius_temps))
print(fahrenheit_temps)

Output:

[77.0, 86.0, 95.0, 104.0]
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

Output:

[2, 4, 6, 8, 10]
from functools import reduce
numbers = [1, 5, 3, 8, 2, 10]
max_num = reduce(lambda x, y: x if x > y else y, numbers

Leave a Reply

Your email address will not be published. Required fields are marked *