Day 4: Exploring Randomness, Lists, and Conditional Logic in Python


Greetings, fellow learners!
Welcome to Day 4 of my 100 Days of Python journey! Today was exciting as I explored more advanced topics, including generating randomness, working with lists, and implementing conditional logic within lists. These concepts are crucial for creating dynamic and flexible programs. Let’s dive in!
1. Generating Randomness in Python
Python’s random
module provides functions to generate random numbers and make random selections. This is especially useful in simulations, games, and more.
Example:
import random
# Generating a random number between 1 and 10
random_number = random.randint(1, 10)
print(f"Your random number is: {random_number}")
# Selecting a random choice from a list
names = ["Ayushi", "John", "Emily", "Michael"]
random_name = random.choice(names)
print(f"The chosen name is: {random_name}")
Here, randint
generates a random integer, while choice
picks a random element from a list.
2. Working with Lists in Python
Lists are versatile data structures that can store multiple items. Python makes it easy to manipulate and access list elements.Lists are incredibly flexible, allowing you to efficiently add, remove, and access elements.
Example:
# Creating and manipulating lists
fruits = ["apple", "banana", "cherry"]
fruits.append("orange") # Adding an item to the list
print(fruits)
# Accessing elements
print(f"The first fruit is: {fruits[0]}")
# Slicing a list
print(f"The first two fruits are: {fruits[:2]}")
3. Combining Randomness, Lists, and Conditional Logic
By combining these concepts, we can create more interactive and dynamic programs.
Example: A Simple Random Selector with Conditions
import random
# List of activities
activities = ["reading", "coding", "drawing", "exercise"]
selected_activity = random.choice(activities)
# Conditional logic based on the random selection
if selected_activity == "reading":
print("Time to grab a book and dive into a story!")
elif selected_activity == "coding":
print("Let's write some awesome Python code!")
elif selected_activity == "drawing":
print("Unleash your creativity with some art!")
else:
print("Stay fit and active with some exercise!")
This program randomly selects an activity and provides a corresponding message based on the choice.
Join Me!
Have you ever combined randomness, lists, and logic in a project? Share your ideas or ask questions in the comments below. Let’s inspire and learn from each other!
Until tomorrow, happy coding! 😊
Subscribe to my newsletter
Read articles from Ayushi singla directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
