Learn Python, Microsoft 365 and Google Workspace
Connect with me: Youtube | LinkedIn | WhatsApp Channel | Web | Facebook | Twitter
In Python, data types define the kind of value a variable can hold and the operations that can be performed on it. They act as blueprints, specifying how data is stored and manipulated in your programs.
- `int`: Stores whole (non-decimal) numbers, like `10`, `-5`, or `9999`.
- `float`: Represents floating-point numbers with decimals, like `3.14`, `-2.5e2` (scientific notation), or `1.2345678901234567` (limited precision).
- `complex`: Holds complex numbers with a real and imaginary part, like `3+2j` or `1.5-4.7j`.
# Integer (int) to store age
age = 25
# Float (float) to store price with decimals
price = 14.99
# Complex number (complex) - not as common in everyday use
complex_num = 3 + 2j # Imaginary unit represented by j
- `str`: Represents textual data enclosed in single or double quotes, such as `"Hello, world!"`, `'This is a string'`, or multi-line strings using triple quotes (''' or """).
# String (str) to store a name
name = "Alice"
# String with a sentence
greeting = "Hello, how are you?"
# Multi-line string using triple quotes
message = """This is a message
that spans multiple lines."""
- `bool`: Represents logical values: `True` or `False`. Used for conditional statements and boolean expressions.
# Boolean (bool) for a true/false condition
is_raining = True
# Using booleans in an if statement
if is_raining:
print("Bring an umbrella!")
Great! Hereâs your next task.
Write a Python program that:
type()
function to check the data type of each number.Example Output:
The type of variable x is: <class 'int'>
The type of variable y is: <class 'float'>
The type of variable z is: <class 'complex'>
Write a Python program that:
str()
function.Example Input:
Enter a number: 100
Expected Output:
Your number is: 100
Write a Python program that:
"123"
).int()
function.Example Input:
Enter a number as a string: 50
Expected Output:
Double the number: 100
Write a Python program that:
oct()
and hexadecimal using hex()
.Example Input:
Enter a number: 255
Expected Output:
Octal: 0o377
Hexadecimal: 0xff
Write a Python program that:
int(value, base)
.Example Input:
Enter an octal number: 0o377
Enter a hexadecimal number: 0xff
Expected Output:
Octal to Integer: 255
Hexadecimal to Integer: 255
Creating a Tuple in Python
A tuple is created by enclosing elements within parentheses () and separating them with commas. While parentheses are technically optional, itâs generally considered best practice to use them for clarity and consistency.
Example
Some common ways to create tuples in Python include:
tup = (1,2,3)
print(tup) # Output: (1, 2, 3)
# check the type of variable
print(type(tup)) # Output: <class 'tuple'>
# another example to create tuple
tup1 = 4,5,6
print(tup1) # Output: (4, 5, 6)
# tuple with mixed datatypes
tup_mixed = (7, "String", 7.8)
print(tup_mixed)
tup4 = tuple('string')
print(tup4) # Output: ('s','t','r','i','n','g')
Creating a List
You can create a list by placing items inside square brackets []
, separated by commas.
# A list of integers
numbers = [1, 2, 3, 4, 5]
# A list of strings
fruits = ["apple", "banana", "cherry"]
# A list of mixed data types
mixed_list = [1, "hello", 3.14, True]
# An empty list
empty_list = []
Accessing Elements in a List
You can access individual elements in a list using their index.
# Access the first element (index 0)
print(fruits[0]) # Output: apple
# Access the second element (index 1)
print(fruits[1]) # Output: banana
# Access the last element (index -1)
print(fruits[-1]) # Output: cherry
Modifying Elements in a List
Since lists are mutable, you can change an element in a list by assigning a new value to a specific index.
# Change the first element of the list
fruits[0] = "orange"
print(fruits) # Output: ['orange', 'banana', 'cherry']
In Python, a dictionary is a collection of key-value pairs. Each key in a dictionary is unique, and it is associated with a value. Dictionaries are used to store data values like a map or a real-life dictionary where each word (key) has a definition (value). They are mutable, meaning you can change, add, or remove items after the dictionary is created.
Creating a Dictionary
You create a dictionary using curly braces {}
with keys and values separated by a colon :
. Multiple key-value pairs are separated by commas.
# Example of a dictionary
student = {
"name": "John",
"age": 20,
"courses": ["Math", "Science"]
}
Accessing Values
You can access the value associated with a specific key by using square brackets []
or the get()
method.
# Accessing values
print(student["name"]) # Output: John
print(student.get("age")) # Output: 20
Adding or Updating Elements
You can add a new key-value pair or update an existing one by assigning a value to the key.
# Adding a new key-value pair
student["grade"] = "A"
# Updating an existing value
student["age"] = 21
In Python, a set is an unordered collection of unique elements, meaning no duplicates are allowed. Sets are useful when you want to store multiple items but donât need to keep them in a particular order, and you want to ensure that each item only appears once.
Creating a Set
You can create a set using curly braces {}
or the set()
function.
# Creating a set using curly braces
my_set = {1, 2, 3, 4, 5}
# Creating a set using the set() function
my_set = set([1, 2, 3, 4, 5])
# Creating a set
fruits = {"apple", "banana", "cherry", "apple"}
# Displaying the set
print(fruits) # Output: {'apple', 'banana', 'cherry'}
Notice how apple
only appears once, even though we tried to add it twice.
For more details , see Data Structures and Sequences
Write a Python program that:
Example Output:
Tuple: (10, 'Apple', 3.5)
First item: 10
Write a Python program that:
Example Output:
Name: Alice
Age: 25
Country: USA
Write a Python program that:
Example Output:
Numbers: (5, 10, 15, 20, 25)
Last number: 25
Write a Python program that:
Example Output:
Favorite Foods: ['Pizza', 'Burger', 'Pasta', 'Ice Cream']
Second food: Burger
Write a Python program that:
Example Output:
Original List: ['Red', 'Blue', 'Green']
Updated List: ['Yellow', 'Blue', 'Green']
Write a Python program that:
Example Input:
Enter a city: Paris
Enter a city: London
Enter a city: Tokyo
Example Output:
Cities: ['Paris', 'London', 'Tokyo']
Write a Python program that:
Example Output:
Person: {'name': 'Alice', 'age': 25}
Name: Alice
Write a Python program that:
Example Output:
Original Dictionary: {'name': 'John', 'country': 'USA'}
Updated Dictionary: {'name': 'John', 'country': 'USA', 'hobby': 'Reading'}
Write a Python program that:
Example Output:
Numbers: {1, 2, 3, 4}
Write a Python program that:
Example Input:
Original List: [1, 2, 2, 3, 3, 4, 5]
Example Output:
Unique Numbers: {1, 2, 3, 4, 5}
Write a Python program that:
Example Output:
Original List: ['Inception', 'Titanic', 'Avatar', 'Interstellar', 'Joker']
Third movie: Avatar
Updated List: ['Inception', 'Titanic', 'Avatar', 'Interstellar', 'The Dark Knight']
Write a Python program that:
Example Input:
Original List: [1, 2, 2, 3, 4, 4, 5]
Expected Output:
Unique Numbers: {1, 2, 3, 4, 5}
Write a Python program that:
Expected Output:
Even Numbers: {2, 4, 6, 8, 10}
Prime Numbers: {2, 3, 5, 7}
Union: {2, 3, 4, 5, 6, 7, 8, 10}
Intersection: {2}
video: 3 Reasons Why Are Data Types So Important in Python
Data types are essential in Python for several reasons:
video: Is Python a Dynamic Language?
Example #: Dynamic Variables in Python
# Initial assignment of an integer value
x = 10
print(x) # Output: 10
print(type(x)) # Output: <class 'int'>
# Reassigning a string value to the same variable
x = "Hello, World!"
print(x) # Output: Hello, World!
print(type(x)) # Output: <class 'str'>
# Reassigning a list to the same variable
x = [1, 2, 3]
print(x) # Output: [1, 2, 3]
print(type(x)) # Output: <class 'list'>
# Reassigning a float value to the same variable
x = 3.14
print(x) # Output: 3.14
print(type(x)) # Output: <class 'float'>
In this example:
x
is initially assigned an integer value of 10
.x
is then reassigned a string value "Hello, World!"
.x
is later reassigned a list [1, 2, 3]
.x
is reassigned a float value 3.14
.Each time, the type of x
changes dynamically to match the type of the value assigned to it. This flexibility is one of the powerful features of Python, allowing for more concise and adaptable code.
input()
Function - Lecture Notesinput()
?The input()
function in Python is used to take user input from the keyboard. It allows a program to interact with users by asking for information.
variable_name = input("Prompt message")
Prompt message
: A string displayed to the user before they enter input.variable_name
: The variable where the userâs input is stored.Basic Example
name = input("Enter your name: ")
print("Hello, " + name + "!")
input("Enter your name: ")
displays the message âEnter your name: â and waits for the user to type something.name
.print("Hello, " + name + "!")
displays a greeting message with the userâs name.By default, input()
returns a string. If you need a number, you must convert it using int()
or float()
.
age = int(input("Enter your age: "))
print("In 5 years, you will be", age + 5)
int(input(...))
converts it into an integer.In Python, None
is a special constant that represents the absence of a value or a null value. It is an object of its own datatype, called NoneType
.
Examples:
None
to Variables:
a = None
None
:
if a is None:
print("a is None")
else:
print("a is not None")
In Python, type hints allow you to specify the expected data types of variables, function parameters, and return values. They make the code more readable and help developers understand what kind of values are expected.
Hereâs how you can use type hints in Python:
You can add type hints to variables by using a colon :
after the variable name, followed by the type:
age: int = 25
name: str = "Alice"
height: float = 5.7
is_student: bool = True
For functions, type hints are added after the parameter names and before the return type with ->
.
def greet(name: str) -> str:
return f"Hello, {name}!"
# Usage
print(greet("Alice")) # Output: Hello, Alice!
This code specifies that the name
parameter should be a str
, and the function should return a str
.
For more complex types like lists, dictionaries, sets, and tuples.
To specify that a list contains elements of a certain type, use list
.
# A list of integers
numbers: list[int] = [1, 2, 3, 4, 5]
# A list of strings
names: list[str] = ["Alice", "Bob", "Charlie"]
For dictionaries, you can specify the types of both keys and values using dict
.
# A dictionary with string keys and integer values
age_map: dict[str, int] = {"Alice": 30, "Bob": 25, "Charlie": 35}
To specify the type of elements in a set, use Set
.
# A set of strings
unique_names: set[str] = {"Alice", "Bob", "Charlie"}
You can also use type hints in function definitions to specify the types of parameters and return values.
# Function that processes a list of integers and returns a dictionary
def process_data(numbers: list[int]) -> dict[str, int]:
result = {
'sum': sum(numbers),
'count': len(numbers)
}
return result
data = [1, 2, 3, 4, 5]
processed_data = process_data(data)
print(processed_data) # Output: {'sum': 15, 'count': 5}
Using type hints doesnât enforce types at runtime but can improve code readability and help detect type-related issues with tools like mypy.
Incorrect Input Conversion [Python Quiz #64]
age = input("Enter your age: ")
result = age * 2
Answer Key (True/False):
What is the output of the following code? [Python Quiz #22]
age = 25
print("I am " + str(age) + " years old.")
Watch this video for the answer:https://youtube.com/shorts/DBC5-ZYoGXI?si=PXk-CPGymx2Q6X2p
age = 25
message = "You are " + str(age) + " years old."
message += " Welcome!"
print(message)
type(3 + 4.0)
- A) <class 'str'>
- B) <class 'bool'>
- C) <class 'int'>
- D) <class 'float'>
x = 10
x = "Hello"
print(type(x))
- A) <class 'int'>
- B) <class 'str'>
- C) <class 'bool'>
- D) <class 'float'>
x = 5
x = 5.0
x = True
x = "Python"
print(x)
- A) 5
- B) 5.0
- C) True
- D) Python
x = "10"
x = int(x) + 2
print(x)
- A) "102"
- B) 102
- C) 12
- D) "12"
Answer Key (Fill in the Blanks):
5
to a variable named x
.10
to a variable named y
.x
and y
to a variable named sum_xy
.sum_xy
.Solution:
x = 5
y = 10
sum_xy = x + y
print("Sum of x and y:", sum_xy)
pi
.greeting
.is_active
.pi
, greeting
, and is_active
.Solution:
pi = 3.14
greeting = "Hello, World!"
is_active = True
print("Type of pi:", type(pi), "Value:", pi)
print("Type of greeting:", type(greeting), "Value:", greeting)
print("Type of is_active:", type(is_active), "Value:", is_active)
first_name
.last_name
.first_name
and last_name
with a space in between and assign the result to a variable named full_name
.full_name
.Solution:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print("Full name:", full_name)
True
to a variable named is_sunny
.False
to a variable named is_raining
.can_go_outside
that is True
if is_sunny
is True
and is_raining
is False
.can_go_outside
.Solution:
is_sunny = True
is_raining = False
can_go_outside = is_sunny and not is_raining
print("Can go outside:", can_go_outside)
"123"
to a variable named num_str
.num_str
to an integer and assign it to a variable named num_int
.num_int
.Solution:
num_str = "123"
num_int = int(num_str)
print("Type of num_int:", type(num_int), "Value:", num_int)
Basic Data Types
int
), floating-point numbers (float
), and complex numbers (complex
).str
) to represent sequences of characters.bool
) for True or False.Boolean and None
None
None
is a singleton in Python, meaning there is only one instance of None
in a Python runtime. All occurrences of None
point to the same object.
a = None
b = None
print(a is b) # Output: True
None
is NoneType
.
print(type(None)) # Output: <class 'NoneType'>
None
is treated as False
in a boolean context.
if not None:
print("None is considered False") # Output: None is considered False
None
None
, use the is
operator, as it checks for identity.
variable = None
if variable is None:
print("Variable is None") # Output: Variable is None
How do you check if a variable is None?
variable = None
if variable is None:
print("Variable is None")
Type Casting
[1]R. Python, âDynamic vs Static â Real Python,â realpython.com. https://realpython.com/lessons/dynamic-vs-static/ [2]Python Software Foundation, âBuilt-in Types â Python 3.12.1 documentation,â Python.org, 2019. https://docs.python.org/3/library/stdtypes.html [3]âPEP 526 â Syntax for Variable Annotations | peps.python.org,â peps.python.org. https://peps.python.org/pep-0526/ â â â