Basic python notebook
Let's explore more in depth the basics¶
Variables¶
In [12]:
Copied!
# Assigning a value to a variable:
x = 5
y = 10
z = x + y
print(z) # Output: 15
# Assigning a value to a variable:
x = 5
y = 10
z = x + y
print(z) # Output: 15
15
In [11]:
Copied!
# Assigning a value to multiple variables at once:
a, b, c = 1, 2, 3
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
# Assigning a value to multiple variables at once:
a, b, c = 1, 2, 3
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3
1 2 3
In [10]:
Copied!
# Assigning a value to a variable and then reassigning a new value:
name = "John"
print(name) # Output: John
name = "Eric"
print(name) # Output: Eric
# Assigning a value to a variable and then reassigning a new value:
name = "John"
print(name) # Output: John
name = "Eric"
print(name) # Output: Eric
John Eric
In [9]:
Copied!
# Assigning a value to a variable and then using it in a calculation:
num1 = 15
num2 = 20
result = num1 * num2
print(result) # Output: 300
# Assigning a value to a variable and then using it in a calculation:
num1 = 15
num2 = 20
result = num1 * num2
print(result) # Output: 300
300
In [8]:
Copied!
# Using a variable as an input for a function:
name = "Michael"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
# Using a variable as an input for a function:
name = "Michael"
age = 25
print("My name is " + name + " and I am " + str(age) + " years old.")
My name is Michael and I am 25 years old.
In [7]:
Copied!
# Assigning a value to a variable and then using it in a loop:
word = "hello"
for letter in word:
print(letter)
# Assigning a value to a variable and then using it in a loop:
word = "hello"
for letter in word:
print(letter)
h e l l o
In [6]:
Copied!
# Assign a value to a variable and then using it in a data structure, such as a list:
x = 6
numbers = [1, 2, 3, 4, 5]
numbers.append(x)
print(numbers)
# Assign a value to a variable and then using it in a data structure, such as a list:
x = 6
numbers = [1, 2, 3, 4, 5]
numbers.append(x)
print(numbers)
[1, 2, 3, 4, 5, 6]
Data types¶
In [16]:
Copied!
# lists
# Creating a list
a = [1, 2, 3, 4, 5]
# Accessing elements in a list
print(a[2])
# Modifying elements in a list
a[2] = 6
print(a)
# Adding elements to a list
a.append(7)
print(a)
# Removing elements from a list
a.remove(6)
print(a)
# lists
# Creating a list
a = [1, 2, 3, 4, 5]
# Accessing elements in a list
print(a[2])
# Modifying elements in a list
a[2] = 6
print(a)
# Adding elements to a list
a.append(7)
print(a)
# Removing elements from a list
a.remove(6)
print(a)
3 [1, 2, 6, 4, 5] [1, 2, 6, 4, 5, 7] [1, 2, 4, 5, 7]
In [19]:
Copied!
# tuples
# Creating a tuple
b = (1, 2, 3, 4, 5)
# Accessing elements in a tuple
print(b[2]) # Output: 3
# Tuples are immutable, so modifying elements is not possible
# Concatenating tuples
c = b + (6, 7)
print(c) # Output: (1, 2, 3, 4, 5, 6, 7)
# tuples
# Creating a tuple
b = (1, 2, 3, 4, 5)
# Accessing elements in a tuple
print(b[2]) # Output: 3
# Tuples are immutable, so modifying elements is not possible
# Concatenating tuples
c = b + (6, 7)
print(c) # Output: (1, 2, 3, 4, 5, 6, 7)
3 (1, 2, 3, 4, 5, 6, 7)
In [18]:
Copied!
# dict
# Creating a dictionary
d = {'a': 1, 'b': 2, 'c': 3}
# Accessing elements in a dictionary
print(d['b'])
# Modifying elements in a dictionary
d['b'] = 4
print(d)
# Adding elements to a dictionary
d['d'] = 5
print(d)
# Removing elements from a dictionary
del d['a']
print(d)
# dict
# Creating a dictionary
d = {'a': 1, 'b': 2, 'c': 3}
# Accessing elements in a dictionary
print(d['b'])
# Modifying elements in a dictionary
d['b'] = 4
print(d)
# Adding elements to a dictionary
d['d'] = 5
print(d)
# Removing elements from a dictionary
del d['a']
print(d)
2 {'a': 1, 'b': 4, 'c': 3} {'a': 1, 'b': 4, 'c': 3, 'd': 5} {'b': 4, 'c': 3, 'd': 5}
In [22]:
Copied!
# sets
# Creating a set
e = {1, 2, 3, 4, 5}
# Sets do not support indexing, so accessing elements is not possible
# Modifying elements in a set
e.add(6)
print(e)
e.remove(4)
print(e)
# Union and intersection of sets
f = {4, 5, 6, 7, 8}
print(e.union(f))
print(e.intersection(f))
# sets
# Creating a set
e = {1, 2, 3, 4, 5}
# Sets do not support indexing, so accessing elements is not possible
# Modifying elements in a set
e.add(6)
print(e)
e.remove(4)
print(e)
# Union and intersection of sets
f = {4, 5, 6, 7, 8}
print(e.union(f))
print(e.intersection(f))
{1, 2, 3, 4, 5, 6} {1, 2, 3, 5, 6} {1, 2, 3, 4, 5, 6, 7, 8} {5, 6}
In [20]:
Copied!
# Creating a string
g = "Hello, World!"
# Accessing elements in a string
print(g[7])
# Modifying elements in a string is not possible as strings are immutable
# Concatenating strings
h = g + " How are you?"
print(h)
# Splitting a string
print(h.split())
# Creating a string
g = "Hello, World!"
# Accessing elements in a string
print(g[7])
# Modifying elements in a string is not possible as strings are immutable
# Concatenating strings
h = g + " How are you?"
print(h)
# Splitting a string
print(h.split())
W Hello, World! How are you? ['Hello,', 'World!', 'How', 'are', 'you?']
Operators¶
In [23]:
Copied!
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b)
print(a is c)
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a is b)
print(a is c)
False True
In [24]:
Copied!
numbers = [1, 2, 3, 4, 5]
print(3 in numbers)
print(6 in numbers)
numbers = [1, 2, 3, 4, 5]
print(3 in numbers)
print(6 in numbers)
True False
In [25]:
Copied!
numbers = [1, 2, 3, 4, 5]
print(3 not in numbers)
print(6 not in numbers)
numbers = [1, 2, 3, 4, 5]
print(3 not in numbers)
print(6 not in numbers)
False True
In [26]:
Copied!
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3)
[1, 2, 3, 4, 5, 6]
In [27]:
Copied!
list1 = [1, 2, 3]
list2 = list1 * 3
print(list2)
list1 = [1, 2, 3]
list2 = list1 * 3
print(list2)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
In [28]:
Copied!
print(2 ** 3)
print(2 ** 3)
8
In [33]:
Copied!
print(7 // 3)
print(7 / 3)
print(7 % 3)
print(7 // 3)
print(7 / 3)
print(7 % 3)
2 2.3333333333333335 1
In [ ]:
Copied!
# Example 1: Using "elif" to check multiple conditions
age = 25
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 30:
print("You are a young adult.")
else:
print("You are an adult.")
# Example 1: Using "elif" to check multiple conditions
age = 25
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 30:
print("You are a young adult.")
else:
print("You are an adult.")
In [ ]:
Copied!
# Example 2: Using "for" to iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Example 2: Using "for" to iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
In [ ]:
Copied!
# Example 3: Using "while" to repeat a block of code
counter = 0
while counter < 5:
print(counter)
counter += 1
# Example 3: Using "while" to repeat a block of code
counter = 0
while counter < 5:
print(counter)
counter += 1
In [ ]:
Copied!
# Example 4: Using "break" and "continue" in a loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
continue
print(number)
if number == 3:
break
# Example 4: Using "break" and "continue" in a loop
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number % 2 == 0:
continue
print(number)
if number == 3:
break
In [ ]:
Copied!
# Example 5: Using "for" and "enumerate" to iterate over a list with index
fruits = ["apple", "banana", "orange"]
for i, fruit in enumerate(fruits):
print(i, fruit)
# Example 5: Using "for" and "enumerate" to iterate over a list with index
fruits = ["apple", "banana", "orange"]
for i, fruit in enumerate(fruits):
print(i, fruit)
Functions¶
In [34]:
Copied!
# Example 1: A function that takes a list and returns the average of its elements
def average(numbers):
return sum(numbers) / len(numbers)
result = average([1, 2, 3, 4, 5])
print(result)
# Example 1: A function that takes a list and returns the average of its elements
def average(numbers):
return sum(numbers) / len(numbers)
result = average([1, 2, 3, 4, 5])
print(result)
3.0
In [ ]:
Copied!
# Example 2: A function that uses a default value for an argument
def power(number, exponent=2):
return number ** exponent
print(power(3))
print(power(3, 3))
# Example 2: A function that uses a default value for an argument
def power(number, exponent=2):
return number ** exponent
print(power(3))
print(power(3, 3))
In [38]:
Copied!
# Example 3 : Function that takes in a list of numbers and returns the sum of the even numbers in the list
def sum_of_even_numbers(numbers):
even_sum = 0
for number in numbers:
if number % 2 == 0:
even_sum += number
return even_sum
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sum_of_even_numbers(numbers))
# Example 3 : Function that takes in a list of numbers and returns the sum of the even numbers in the list
def sum_of_even_numbers(numbers):
even_sum = 0
for number in numbers:
if number % 2 == 0:
even_sum += number
return even_sum
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(sum_of_even_numbers(numbers))
30
In [39]:
Copied!
# Example 4 : Function that takes in a string and returns a new string with all the vowels removed
def remove_vowels(string):
vowels = ['a', 'e', 'i', 'o', 'u']
new_string = ''
for char in string:
if char.lower() not in vowels:
new_string += char
return new_string
print(remove_vowels("Hello World"))
# Example 4 : Function that takes in a string and returns a new string with all the vowels removed
def remove_vowels(string):
vowels = ['a', 'e', 'i', 'o', 'u']
new_string = ''
for char in string:
if char.lower() not in vowels:
new_string += char
return new_string
print(remove_vowels("Hello World"))
Hll Wrld
In [40]:
Copied!
# Example 5 : Function that takes in a list of numbers and a number, and returns a new list with all the numbers in the original list that are greater than the given number
def filter_numbers(numbers, number):
filtered_numbers = []
for num in numbers:
if num > number:
filtered_numbers.append(num)
return filtered_numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_numbers(numbers, 5)) # Output: [6, 7, 8, 9, 10]
# Example 5 : Function that takes in a list of numbers and a number, and returns a new list with all the numbers in the original list that are greater than the given number
def filter_numbers(numbers, number):
filtered_numbers = []
for num in numbers:
if num > number:
filtered_numbers.append(num)
return filtered_numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(filter_numbers(numbers, 5)) # Output: [6, 7, 8, 9, 10]
[6, 7, 8, 9, 10]
Modules and Libraries¶
In [41]:
Copied!
# Using the math module to perform mathematical operations
import math
# Using the sqrt function from the math module
print(math.sqrt(16))
# Using the pi constant from the math module
print(math.pi)
# Using the math module to perform mathematical operations
import math
# Using the sqrt function from the math module
print(math.sqrt(16))
# Using the pi constant from the math module
print(math.pi)
4.0 3.141592653589793
In [43]:
Copied!
# Using the random module to generate random numbers:
import random
# Generating a random integer between 1 and 10
print(random.randint(1, 10))
# Generating a random float between 0 and 1
print(random.random())
# selecting a random item from a list
my_list = [1, 2, 3, 4, 5]
print(random.choice(my_list))
# Using the random module to generate random numbers:
import random
# Generating a random integer between 1 and 10
print(random.randint(1, 10))
# Generating a random float between 0 and 1
print(random.random())
# selecting a random item from a list
my_list = [1, 2, 3, 4, 5]
print(random.choice(my_list))
1 0.7110608023753344 4
Exception Handling¶
In [ ]:
Copied!
# Example 1: Using a try-except block
try:
# code that might raise an exception
result = 1 / 0
except ZeroDivisionError:
# code to handle the exception
print("Cannot divide by zero.")
# Example 1: Using a try-except block
try:
# code that might raise an exception
result = 1 / 0
except ZeroDivisionError:
# code to handle the exception
print("Cannot divide by zero.")
In [ ]:
Copied!
# Example 2: Using the "raise" keyword
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
try:
result = divide(1, 0)
except ValueError as e:
print(e)
# Example 2: Using the "raise" keyword
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero.")
return a / b
try:
result = divide(1, 0)
except ValueError as e:
print(e)
In [ ]:
Copied!
# Example 3: Using an "else" block with a try-except block
try:
# code that might raise an exception
result = 1 / 2
except ZeroDivisionError:
# code to handle the exception
print("Cannot divide by zero.")
else:
# code to run if no exception was raised
print(result)
# Example 3: Using an "else" block with a try-except block
try:
# code that might raise an exception
result = 1 / 2
except ZeroDivisionError:
# code to handle the exception
print("Cannot divide by zero.")
else:
# code to run if no exception was raised
print(result)
In [ ]:
Copied!
In [ ]:
Copied!
In [ ]:
Copied!
In [ ]:
Copied!