Create a dictionary named student with the following keys and values. and print the same
"name": "Alice"
"age": 21
"major": "Computer Science"
Using the student dictionary, print the values associated with the keys "name" and "major".
Add a new key-value pair to the student dictionary: "gpa": 3.8. Then update the "age" to 22.
Remove the key "major" from the student dictionary using the del statement. Print the dictionary to confirm the removal.
Check if the key "age" exists in the student dictionary. Print True or False based on the result.
Create a dictionary prices with three items, e.g., "apple": 0.5, "banana": 0.3, "orange": 0.7. Iterate over the dictionary and print each key-value pair.
Use the len() function to find the number of key-value pairs in the prices dictionary. Print the result.
Use the get() method to access the "gpa" in the student dictionary. Try to access a non-existing key, e.g., "graduation_year", with a default value of 2025.
Create another dictionary extra_info with the following keys and values. Also merge extra_info into the student dictionary using the update() method.
"graduation_year": 2025
"hometown": "Springfield"
Create a dictionary squares where the keys are numbers from 1 to 5 and the values are the squares of the keys. Use dictionary comprehension.
Using the prices dictionary, print the keys and values as separate lists using the keys() and values() methods.
Create a dictionary school with two nested dictionaries. Access and print the age of "student2".
"student1": {"name": "Alice", "age": 21}
"student2": {"name": "Bob", "age": 22}
Use the setdefault() method to add a new key "advisor" with the value "Dr. Smith" to the student dictionary if it does not exist.
Use the pop() method to remove the "hometown" key from the student dictionary and store its value in a variable. Print the variable.
Use the clear() method to remove all items from the prices dictionary. Print the dictionary to confirm it’s empty.
Make a copy of the student dictionary using the copy() method. Modify the copy by changing "name" to "Charlie". Print both dictionaries to see the differences.
Create two lists: keys = ["name", "age", "major"] and values = ["Eve", 20, "Mathematics"]. Use the zip() function to create a dictionary from these lists.
Use the items() method to iterate over the student dictionary and print each key-value pair.
Given a list of fruits: ["apple", "banana", "apple", "orange", "banana", "banana"], create a dictionary fruit_count that counts the occurrences of each fruit.
Use collections.defaultdict to create a dictionary word_count that counts the number of occurrences of each word in a list: ["hello", "world", "hello", "python"].
We are planning to opening a botanical garden with flowers which will attract people to visit.
Morning: Planting Unique Flowers
One morning, we decides to plant flowers in the garden. They ensure that each flower they plant is unique.
botanical_garden = {"Rose", "Lily", "Sunflower"}
Noon: Adding More Flowers
At noon, they find some more flowers and add them to the garden, making sure they only add flowers that aren’t already there.
Adding Elements to a Set:
# Adding more unique flowers to the enchanted garden
botanical_garden.add("Jasmine")
botanical_garden.add("Hibiscus")
print(botanical_garden)
# output: {'Hibiscus', 'Rose', 'Tulip', 'Sunflower', 'Jasmine'}
Afternoon: Trying to Plant Duplicate Flowers
In the afternoon, they accidentally try to plant another Rose, but the garden’s rule prevents any duplicates from being added.
Adding Duplicate Elements:
# Attempting to add a duplicate flower
botanical_garden.add("Rose")
print(botanical_garden)
# output: {'Lily', 'Sunflower', 'Rose'}
Evening: Removing Unwanted Plants
As evening approaches, they decide to remove some flowers they no longer want in their garden.
Removing Elements from a Set:
# Removing a flower from the enchanted garden
botanical_garden.remove("Lily")
print(botanical_garden)
# output: {'Sunflower', 'Rose'}
Night: Checking Flower Types
Before going to bed, they check if certain flowers are present in their botanical garden.
Checking Membership:
# Checking if certain flowers are in the garden
is_rose_in_garden = "Rose" in botanical_garden
is_tulip_in_garden = "Tulip" in botanical_garden
print(f"Is Rose in the garden? {is_rose_in_garden}")
print(f"Is Tulip in the garden? {is_tulip_in_garden}")
# Output
# Is Rose in the garden? True
# Is Tulip in the garden? False
Midnight: Comparing with Rose Garden
Late at night, they compare their botanical garden with their rose garden to see which flowers they have in common and which are unique to each garden.
Set Operations:
Intersections:
# Neighbor's enchanted garden
rose_garden = {"Rose", "Lavender"}
# Flowers in both gardens (Intersection)
common_flowers = botanical_garden.intersection(rose_garden)
print(f"Common flowers: {common_flowers}")
# Output
# Common flowers: {'Rose'}
# Unique flowers: {'Sunflower'}
# All unique flowers: {'Sunflower', 'Lavender', 'Rose'}
Difference:
# Flowers unique to their garden (Difference)
unique_flowers = botanical_garden.difference(rose_garden)
print(f"Unique flowers: {unique_flowers}")
#output
# Unique flowers: {'Sunflower'}
Union:
# All unique flowers from both gardens (Union)
all_unique_flowers = botanical_garden.union(rose_garden)
print(f"All unique flowers: {all_unique_flowers}")
# Output: All unique flowers: {'Sunflower', 'Lavender', 'Rose'}
In a vibrant town in Tamil Nadu, there is a popular grocery store called Annachi Kadai. This store is always bustling with fresh deliveries of items.
The store owner, Pandian, uses a special inventory system to track the products. This system functions like a dictionary in Python, where each item is labeled with its name, and the quantity available is recorded.
Morning: Delivering Items to the Store
One bright morning, a new delivery truck arrives at the grocery store, packed with fresh items. Pandian records these new items in his inventory list.
Creating and Updating the Inventory:
# Initial delivery of items to the store
inventory = {
"apples": 20,
"bananas": 30,
"carrots": 15,
"milk": 10
}
print("Initial Inventory:", inventory)
# Output: Initial Inventory: {'apples': 20, 'bananas': 30, 'carrots': 15, 'milk': 10}
Noon: Additional Deliveries
As the day progresses, more deliveries arrive with additional items that need to be added to the inventory. Pandian updates the system with these new arrivals.
In the afternoon, Pandian notices that some items are running low and restocks them by updating the quantities in the inventory system.
Updating Quantities:
# Updating item quantities after restocking shelves
inventory["apples"] += 10 # 10 more apples added
inventory["milk"] += 5 # 5 more bottles of milk added
print("Inventory after Restocking:", inventory)
# Output: Inventory after Restocking: {'apples': 30, 'bananas': 30, 'carrots': 15, 'milk': 15, 'bread': 25, 'eggs': 50}
Evening: Removing Sold-Out Items
As evening falls, some items are sold out, and Pandian needs to remove them from the inventory to reflect their unavailability.
Removing Items from the Inventory:
# Removing sold-out items
del inventory["carrots"]
print("Inventory after Removal:", inventory)
# Output: Inventory after Removal: {'apples': 30, 'bananas': 30, 'milk': 15, 'bread': 25, 'eggs': 50}
Night: Checking Inventory
Before closing the store, Pandian checks the inventory to ensure that all items are accurately recorded and none are missing.
Checking for Items:
# Checking if specific items are in the inventory
is_bananas_in_stock = "bananas" in inventory
is_oranges_in_stock = "oranges" in inventory
print(f"Are bananas in stock? {is_bananas_in_stock}")
print(f"Are oranges in stock? {is_oranges_in_stock}")
# Output: Are bananas in stock? True
# Output: Are oranges in stock? False
Midnight: Reviewing Inventory
After a busy day, Pandian reviews the entire inventory to ensure all deliveries and sales are accurately recorded.
Think of a function as a little helper in your code. It’s like a recipe that you can use over and over again.
Instead of writing the same steps every time you cook a dish, you write down the recipe once and follow it whenever you need to make that dish.
In programming, instead of writing the same code over and over, you write a function and use it whenever needed.
Why Do We Need Functions?
Here are some everyday examples to show why functions are awesome:
Reusability:
Imagine you love making dosa. You have a great recipe, and every time you want dosa, you follow that recipe.
You don’t reinvent dosa each time! Similarly, in programming, if you have a piece of code that works well, you put it in a function and reuse it whenever you need it.
Organization:
Think about how a recipe book organizes different recipes. One section for breakfast, another for lunch, etc.
Functions help you organize your code into neat sections, making it easier to read and understand.
Avoiding Repetition:
Let’s say you need to chop vegetables for several different dishes. Instead of writing down “chop vegetables” each time in every recipe, you have a single “chop vegetables” recipe. In programming, functions help you avoid writing the same code multiple times, reducing mistakes and making your code cleaner.
Simplifying Complex Problems:
If you have a big dinner to cook, breaking it down into simpler tasks like chutneys, tiffins, and sweets makes it manageable. In programming, you break a big problem into smaller functions, solve each one, and then combine them.
Let’s say you’re writing a program to convert temperatures from Celsius to Fahrenheit. Without functions, your code might look like this:
This works, but it’s repetitive. Now, let’s add a function:
# Define a function to convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
# Use the function to convert temperatures
celsius1 = 25
fahrenheit1 = celsius_to_fahrenheit(celsius1)
print(f"{celsius1}°C is {fahrenheit1}°F")
celsius2 = 30
fahrenheit2 = celsius_to_fahrenheit(celsius2)
print(f"{celsius2}°C is {fahrenheit2}°F")
celsius3 = 15
fahrenheit3 = celsius_to_fahrenheit(celsius3)
print(f"{celsius3}°C is {fahrenheit3}°F")
Some of the examples demonstrating how to use functions to accomplish different tasks.
In this blog, we’ll cover three fundamental concepts: operators, conditionals, and getting user input with the input() function. By the end, you’ll have a good grasp of how to use them in your Python programs.
What Are Operators?
Operators are symbols that tell the computer to perform specific mathematical or logical operations.
Think of them as the verbs in a sentence that tell you what action to take. There are several types of operators in Python:
Arithmetic Operators
These operators perform basic mathematical operations like addition, subtraction, multiplication, and division.
Addition (+): Add two numbers.
Subtraction (-): Subtracts one number from another.
Multiplication (*): Multiplies two numbers.
Division (/): Divides one number by another.
Floor Division (//): Divides one number by another and rounds down to the nearest whole number.
Modulus (%): Returns the remainder when one number is divided by another.
Exponentiation ():** Raises one number to the power of another.
Comparison Operators
These operators compare two values and return either True or False.
Equal to (==): Checks if two values are equal.
a = 5
b = 3
result = (a == b) # result is False
Not equal to (!=): Checks if two values are not equal.
a = 5
b = 3
result = (a != b) # result is True
Greater than (>): Checks if one value is greater than another.
a = 5
b = 3
result = (a > b) # result is True
Less than (<): Checks if one value is less than another.
a = 5
b = 3
result = (a < b) # result is False
Greater than or equal to (>=): Checks if one value is greater than or equal to another.
a = 5
b = 3
result = (a >= b) # result is True
Less than or equal to (<=): Checks if one value is less than or equal to another.
a = 5
b = 3
result = (a <= b) # result is False
Logical Operators
These operators are used to combine conditional statements.
and: Returns True if both statements are true.
a = 5
b = 3
result = (a > b and a > 0) # result is True
or: Returns True if one of the statements is true.
a = 5
b = 3
result = (a > b or a < 0) # result is True
not: Reverses the result, returns False if the result is true.
a = 5
result = not (a > 0) # result is False
What Are Conditionals?
Conditionals are like traffic signals for your code. They help your program decide which path to take based on certain conditions. The most common conditional statements in Python are if, elif, and else.
1. The if Statement
The if statement checks a condition and executes the code block if the condition is True.
a = 5
b = 3
if a > b:
print("a is greater than b")
2. The elif Statement
The elif statement is short for “else if”. It checks another condition if the previous if condition was False.
a = 5
b = 5
if a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
3. The else Statement
The else statement catches anything that isn’t caught by the preceding conditions.
a = 3
b = 5
if a > b:
print("a is greater than b")
elif a == b:
print("a is equal to b")
else:
print("a is less than b")
Using input() to Get User Input
This function allows you to get input from the user. It’s like asking a question and waiting for the user to answer.
The input you get is always a string (text), so if you need a number, you have to convert it.
Basic Usage of input()
Here’s a simple example:
name = input("What is your name? ")
print("Hello, " + name + "!")
In this example, the program asks the user for their name and then prints the same.
Converting Input to Numbers
If you want to work with numbers, you’ll need to convert the input from a string to an integer or a float.
age = input("How old are you? ")
age = int(age)
print("You are " + str(age) + " years old.")
Putting It All Together
Let’s combine operators, conditionals, and input() in a simple example. Suppose you want to create a program that checks if a number entered by the user is positive, negative, or zero.
number = input("Enter a number: ")
number = float(number) # Convert the input to a float
if number > 0:
print("The number is positive.")
elif number < 0:
print("The number is negative.")
else:
print("The number is zero.")
In this example, the program:
Asks the user to enter a number.
Converts the input to a float (to handle decimal numbers).
Uses conditionals to check if the number is positive, negative, or zero, and prints the result.
A variable in Python is a symbolic name that references or points to an object.
Once a variable is assigned a value, it can be used to refer to that value throughout the program.
Variables act as containers (eg: box) for storing data values. But ideally they are reference to a memory where the value is stored.
How to name a variable ?
When naming variables in Python, there are a few rules and best practices to follow:
Start with a letter or an underscore: Variable names must begin with a letter (a-z, A-Z) or an underscore (_).
Followed by letters, digits, or underscores: After the first character, you can use letters, digits (0-9), or underscores.
Case-sensitive: Variable names are case-sensitive. For example, myVariable and myvariable are different variables.
Avoid Python keywords: Do not use Python reserved words or keywords as variable names (e.g., class, def, for, while).
Examples of Valid Variable Names:
my_variable
variable1
_hidden_variable
userName
Examples of Invalid Variable Names:
1variable (starts with a digit)
my-variable (contains a hyphen)
for (a reserved keyword)
Assigning Values to Variables
In Python, the assignment operator = is used to assign values to variables. The syntax is straightforward: variable_name = value.
Examples:
# Assigning integer value
age = 25
# Assigning string value
name = "John Doe"
# Assigning float value
height = 5.9
# Assigning boolean value
is_student = True
Multiple Assignments
Python allows you to assign values to multiple variables in a single line. This can make your code more concise and readable.
Example:
# Assigning multiple variables in a single line
a, b, c = 5, 10, 15
# Swapping values of two variables
x, y = y, x
Unpacking Sequences
Python also supports unpacking sequences, such as lists or tuples, into variables. This feature is handy when working with collections of data.
Example:
# Unpacking a tuple
person = ("Alice", 30, "Engineer")
name, age, profession = person
# Unpacking a list
numbers = [1, 2, 3]
one, two, three = numbers
Variable Types
Python is a dynamically typed language, which means you don’t need to declare the type of a variable when assigning a value to it. The type is inferred at runtime based on the assigned value.
Example:
# Dynamic typing
my_variable = 10 # my_variable is an integer
my_variable = "Hello" # my_variable is now a string
You can check the type of a variable using the type() function.
In Python, constants are variables whose values are not meant to change. By convention, constants are typically written in all uppercase letters with underscores separating words.
Note: However, Python does not enforce this, so constants are not truly immutable.
# Defining a constant
PI = 3.14159
MAX_USERS = 100
Data Types
Data types are the different kinds of values that you can store and work with.
Just like in your home, you have different categories of items like clothes, books, and utensils, in Python, you have different categories of data.
1. Numeric Types
Integer (int): Whole numbers.
Float (float): Decimal numbers.
Complex (complex): Complex numbers.
2. Text Type
String (str): Sequence of characters.
3. Boolean Type
Boolean (bool): Represents True or False.
4. None Type
NoneType: Represents the absence of a value
5. Sequence Types
List (list): Ordered, mutable collection
Tuple (tuple): Ordered, immutable collection.
Range (range): Sequence of numbers.
6. Mapping Type
Dictionary (dict): Unordered, mutable collection of key-value pairs.
7, Set Type
Set (set): Unordered collection of unique elements.
Frozenset (frozenset): Immutable set.
Checking Data Type
Syntax:type(variable_name)
Why Do Data Types Matter?
Data types are important because they tell Python what kind of operations you can perform with the data. For example:
You can add, subtract, multiply, and divide numbers.
You can join (concatenate) strings together.
You can access, add, remove, and change items in lists.
You can look up values by their keys in dictionaries.
Using the right data type helps your program run smoothly and prevents errors.
One of the first things you’ll learn in any programming language is how to display output on the screen.
In Python, we do this using the print function. It’s simple, yet powerful. Let’s explore the various ways you can use print in Python.
1. The Basics: Printing a String
To print text, you simply put the text inside double or single quotes and pass it to the print function.
print("Hello, world!")
This will display: Hello, world!
2. Printing Variables
Variables are used to store data. You can print variables by passing them to the print function.
name = "Parotta Salna"
print(name)
This will display: `Parotta Salna`
3. Printing Multiple Items
You can print multiple items by separating them with commas. Python will add a space between each item.
age = 25
city = "New York"
name = "Parotta Salna"
print("Name:", name, "Age:", age, "City:", city)
This will display: Name: Parotta Salna Age: 25 City: New York
4. Formatted Strings with f-strings
An f-string is a way to format strings in Python. You can insert variables directly into the string by prefixing it with an f and using curly braces {} around the variables.
age = 25
city = "New York"
name = "Parotta Salna"
print(f"Name: {name}, Age: {age}, City: {city}")
This will display: Name: Parotta Salna Age: 25 City: New York
5. Concatenation of Strings
You can also combine (concatenate) strings using the + operator.