Class 1: Getting to Know Python

Open In Colab

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python is widely used in data analysis, web development, machine learning, and artificial intelligence. Its extensive library support and vibrant community make it a popular choice for both beginners and experienced developers.

Here is a simple example of Python code that takes an input and produces an output:

# Input
name = input('What is your name? ')

# Output
print(f'Hello, {name}!')

Data Types in Python

Python has several built-in data types. Here are some of the most common ones:

  • Integers (int): Whole numbers, such as 3, 4, or 100.
  • Floating point numbers (float): Numbers with a decimal point, such as 2.3 or 4.6.
  • Strings (str): Sequences of characters, such as ‘hello’ or ‘python’.
  • Booleans (bool): True or false values.

Let’s see some examples:

# Integer
x = 10
print(type(x))

# Float
y = 3.14
print(type(y))

# String
z = 'Hello, Python!'
print(type(z))

# Boolean
w = True
print(type(w))

Lists in Python

A list in Python is an ordered collection of items that can be of any type. Lists are very flexible and can be modified after they are created (they are mutable).

Here is an example of a list:

# List of integers
numbers = [1, 2, 3, 4, 5]
print(numbers)

# List of different types
mixed = [1, 'two', 3.0, True]
print(mixed)

Dictionaries in Python

A dictionary in Python is an unordered collection of items. Each item in a dictionary has a key and a corresponding value. Dictionaries are mutable, meaning they can be changed after they are created.

Here is an example of a dictionary:

# Dictionary
person = {
    'name': 'John',
    'age': 30,
    'is_married': True
}
print(person)

Comparing Lists and Dictionaries

Lists and dictionaries are both versatile data structures in Python, but they are used in different scenarios.

Lists are ordered collections of items, and they are best when the order of items matters. You can use lists when you have a collection of items that you want to keep in a specific order, or when you want to easily add or remove items from the collection.

Dictionaries are unordered collections of key-value pairs, and they are best when you need to associate values with keys, so you can look them up efficiently by key. Dictionaries are ideal for data that is labeled, where each item can be accessed by a unique key (like a product code or name).

Let’s see some examples:

# List example
fruits = ['apple', 'banana', 'cherry']
print(fruits)

# Add an item to the list
fruits.append('date')
print(fruits)

# Dictionary example
fruit_colors = {
    'apple': 'red',
    'banana': 'yellow',
    'cherry': 'red'
}
print(fruit_colors)

# Add an item to the dictionary
fruit_colors['date'] = 'brown'
print(fruit_colors)

It is possible to convert a list to a dictionary and vice versa, but the way you do it depends on the structure of your data.

For example, if you have a list of pairs, you can convert it to a dictionary using the dict() function. And if you have a dictionary, you can convert it to a list of pairs using the items() method.

Let’s see some examples:

# List of pairs
pairs = [('one', 1), ('two', 2), ('three', 3)]

# Convert list to dictionary
dict_from_list = dict(pairs)
print(dict_from_list)

# Dictionary
dictionary = {'one': 1, 'two': 2, 'three': 3}

# Convert dictionary to list
list_from_dict = list(dictionary.items())
print(list_from_dict)

Operations and Methods in Python

In Python, an operation is an action that is carried out on one or more values. For example, the + operation adds two numbers together, and the * operation multiplies them.

A method is a function that is associated with a particular type of object. For example, the count method can be used on a list to count the number of times a particular value appears in the list, and the upper method can be used on a string to convert all the characters to uppercase.

The len function is a built-in Python function that returns the length of a sequence, such as a list or a string.

Let’s see some examples:

# Operations
print(3 + 4)  # Addition
print(3 * 4)  # Multiplication

# Methods
numbers = [1, 2, 3, 2, 1]
print(numbers.count(2))  # Count method

text = 'hello'
print(text.upper())  # Upper method

# Len function
print(len(numbers))  # Length of a list
print(len(text))  # Length of a string

Combining Different Data Types with + and *

In Python, the + and * operators can be used with different types of data, but the behavior can be different depending on the types of the operands.

When used with integers (int), the + operator performs addition and the * operator performs multiplication.

When used with strings (str), the + operator concatenates the strings, and the * operator repeats the string a certain number of times.

However, trying to use + or * with an integer and a string will result in a TypeError.

Let’s see some examples:

# Addition with integers
print(3 + 4)

# Multiplication with integers
print(3 * 4)

# Concatenation with strings
print('hello' + 'world')

# Repetition with strings
print('hello' * 3)

# Trying to add an integer and a string
try:
    print(3 + 'hello')
except TypeError as e:
    print(e)

# Trying to multiply an integer and a string
try:
    print(3 * 'hello')
except TypeError as e:
    print(e)
7
12
helloworld
hellohellohello
unsupported operand type(s) for +: 'int' and 'str'
hellohellohello

Libraries in Python

In Python, a library is a collection of modules, which are files containing Python code that define functions, classes, and variables that you can use once the module is imported.

Python comes with a standard library that includes many useful modules, and there are also many third-party libraries available that provide additional functionality.

You can import a module using the import statement. Once a module is imported, you can use its functions and variables by prefixing them with the module name and a dot.

If a library is not installed, you can install it using the pip tool, which is the package installer for Python.

Let’s see some examples:

# Importing a module from the standard library
import math

# Using a function from the math module
print(math.sqrt(16))

# Note: The following code is commented out because it requires user interaction and might not work in this notebook interface.
# But you can run it in your local Python environment.

# Installing a third-party library (uncomment to run)
# !pip install numpy
4.0

If you only need a specific function from a module, you can import just that function using the from ... import ... statement. This allows you to use the function directly without prefixing it with the module name.

Let’s see an example:

# Importing a specific function from the math module
from math import sqrt

# Using the function directly
print(sqrt(16))
4.0

Google Colab

Google Colab is a cloud-based Python development environment that provides a platform for anyone to write and execute Python code through the browser. It is especially useful for machine learning, data analysis, and education.

Advantages

  • No setup required
  • Free access to GPUs
  • Easy sharing

Whether you’re a student, a data scientist, or an AI researcher, Colab can make your work easier. You can write and execute code, save and share your analyses, and access powerful computing resources, all for free from your browser.

Disadvantages

  • Internet connection is required
  • Limited resources

Despite its advantages, Google Colab does have some limitations. It requires an internet connection to save and run notebooks, and the available resources (RAM and disk space) are limited.

To start a new notebook in Google Colab, you can follow this link.

Exercises

  1. Data Types: Write a Python function that takes two inputs, determines their data types, and returns a message indicating the data type of each input.

  2. List Operations: Given a list of numbers, write a Python function that returns a new list containing the square of each number. Use a loop in your solution.

  3. Dictionary Operations: Write a Python function that takes a dictionary and a key as input, checks if the key is in the dictionary, and returns a message indicating whether the key was found.

  4. String Methods: Write a Python function that takes a string as input and returns a new string with the first letter of each word capitalized.

  5. Library Usage: Use the math library to write a Python function that takes a number as input and returns the square root of the number.