0% found this document useful (0 votes)
9 views5 pages

Lab Exercise 4

The document provides multiple examples of Python code for various applications, including creating plots with matplotlib, generating a list of prime numbers, a number guessing game, and a simple calculator. Each example includes code snippets and explanations of functionality. The examples demonstrate basic programming concepts and the use of libraries for data visualization and user interaction.

Uploaded by

pzb9pks8h4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

Lab Exercise 4

The document provides multiple examples of Python code for various applications, including creating plots with matplotlib, generating a list of prime numbers, a number guessing game, and a simple calculator. Each example includes code snippets and explanations of functionality. The examples demonstrate basic programming concepts and the use of libraries for data visualization and user interaction.

Uploaded by

pzb9pks8h4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Example Python

Example creating multiple plots in a single figure


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 2 * np.pi, 100)


y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x)
y4 = np.exp(x)

# Create a 2x2 grid of subplots


fig, axes = plt.subplots(2, 2, figsize=(10,8))

# Plot the second subplot (top-left)


axes[0, 0].plot(x, y1, color='blue')
axes[0, 0].set_title('Sine Function')

# Plot the second subplot (top-right)


axes[0, 1].plot(x, y2, color='green')
axes[0, 1].set_title('Cosine Function')

# Plot the second subplot (bottom-left)


axes[1, 0].plot(x, y3, color='red')
axes[1, 0].set_title('Tangent Function')

# Plot the second subplot (bottom-right)


axes[1, 1].plot(x, y4, color='purple')
axes[1, 1].set_title('Exponential Function')

# Adjust spacing between subplots


plt.tight_layout()

# Add a common title for all subplots


fig.suptitle('Various Functions', fontsize=16)

# Display the subplots


plt.show()
Example combining different types of plots
import matplotlib.pyplot as plt
import numpy as np

x = np.arange(1, 6)
y1 = np.array([10, 15, 7, 12, 9])
y2 = np.array([200, 300, 150, 250, 180])

# Create a bar plot


fig, ax1 = plt.subplots(figsize=(8, 4))
ax1.bar(x, y1, color='b', alpha=0.7, label='Sales')
ax1.set_xlabel('Month')
ax1.set_ylabel('Sales', color='b')
ax1.set_ylim(0, 20) # Set y-axis limits for the left y-axis

# Create a line plot sharing the x-axis


ax2 = ax1.twinx()
ax2.plot(x, y2, color='r', marker='o', label='Revenue')
ax2.set_ylabel('Revenue', color='r')
ax2.set_ylim(0, 400) # Set y-axis limits for the right y-axis

# Add a legend
fig.legend(loc='upper left', bbox_to_anchor=(0.15, 0.85))

# Add a title
plt.title('Sales and Revenue Comparison')

# Show the plot


plt.show()
Example list prime number that cannot be divided evenly by any other numbers except for 1 and the
number itself.
# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, n - 1):
if n % i == 0:
return False
return True

# List to store prime numbers


prime_numbers = []

# Find prime numbers up to 1000


for num in range(2, 1001):
if is_prime(num):
prime_numbers.append(num)

# Print the list of prime numbers


print(prime_numbers)
Example guess number game. Program random choose number from 0-1000, user need to guess
that number.
import random

# Computer chooses a random number between 0 and 100


number_to_guess = random.randint(0, 1000)
guesses = 0
guess = None
min = 0
max = 1000

print("Welcome to the Number Guessing Game!")


print("I have chosen a number between 0 and 1000.")

# Loop until the user guesses the correct number


while guess != number_to_guess:
try:
print(f"Guest number from {min} to {max}")
guess = int(input("Enter your guess: "))
guesses += 1

if number_to_guess > guess and guess > min:


min = guess
elif number_to_guess < guess and guess < max:
max = guess

if guess == number_to_guess:
print(f"Congratulations! You guessed the number in {guesses} attempts.")
except ValueError:
print("Invalid input. Please enter a valid number.")
Example simple calculator
def add(x, y):
return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
return "Error! Division by zero."
return x / y

print("Welcome to the Simple Calculator!")

while True:
print("Select an operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
choice = input("Enter choice (1/2/3/4): ")

if choice in ['1', '2', '3', '4']:


try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"The result of addition: {add(num1, num2)}")
elif choice == '2':
print(f"The result of subtraction: {subtract(num1, num2)}")
elif choice == '3':
print(f"The result of multiplication: {multiply(num1, num2)}")
elif choice == '4':
print(f"The result of division: {divide(num1, num2)}")
except ValueError:
print("Invalid input. Please enter numeric values.")
else:
print("Invalid choice. Please select a valid operation.")

# Check if the user wants to perform another calculation


next_calculation = input("Do you want to perform another calculation? (yes/no): ")
if next_calculation.lower() != 'yes':
break

You might also like