Python Mid
Python Mid
Problem: Given a list of integers, display only even numbers using a for loop and calculate the sum of all
numbers using a while loop.
python
Copy code
# Get a list of integers from the user
numbers = list(map(int, input("Enter a list of integers (space-separated): ").split()))
# For loop to display even numbersprint("Even numbers:")for num in numbers:
if num % 2 == 0:
print(num, end=" ")
# While loop to calculate the sum of all numbers
total_sum = 0
i = 0while i < len(numbers):
total_sum += numbers[i]
i += 1print("\nSum of all numbers:", total_sum)
Question 2
Problem: Convert temperatures from Celsius to Fahrenheit and count Fahrenheit temperatures above 90°F.
python
Copy code
# Input temperatures in Celsius
temps_celsius = list(map(float, input("Enter temperatures in Celsius (space-
separated): ").split()))
# Convert each to Fahrenheit and store in a new list
temps_fahrenheit = []for temp in temps_celsius:
fahrenheit = (temp * 9/5) + 32
temps_fahrenheit.append(fahrenheit)
# Count Fahrenheit temperatures above 90°F using a while loop
i=0
count_above_90 = 0while i < len(temps_fahrenheit):
if temps_fahrenheit[i] > 90:
count_above_90 += 1
i += 1
print("Temperatures in Fahrenheit:", temps_fahrenheit)print("Number of
temperatures above 90°F:", count_above_90)
Question 3
Problem: Display names with more than 5 characters and check if they start with 'A'.
python
Copy code
# Input list of names
names = input("Enter a list of names (space-separated): ").split()
# For loop to display names with more than 5 characters and check if they start with
'A'for name in names:
if len(name) > 5:
print(name)
if name.startswith('A'):
print("Starts with A")
else:
print(name)
Question 4
Problem: Create a new list with squares of numbers and remove odd numbers from the list.
python
Copy code
# Input list of numbers
numbers = list(map(int, input("Enter a list of numbers: ").split()))
# For loop to create a list of squares
squares = [num ** 2 for num in numbers]
# While loop to remove odd numbers from squares list
i = 0while i < len(squares):
if squares[i] % 2 != 0:
squares.pop(i)
else:
i += 1
print("List of squares with odd numbers removed:", squares)
Question 5
Problem: Find the largest number using a while loop and display numbers greater than the average.
python
Copy code
# Input list of integers
numbers = list(map(int, input("Enter a list of integers: ").split()))
# Find the largest number using a while loop
largest = numbers[0]
i = 1while i < len(numbers):
if numbers[i] > largest:
largest = numbers[i]
i += 1
# Calculate the average and display numbers greater than average using a for loop
average = sum(numbers) / len(numbers)
greater_than_avg = [num for num in numbers if num > average]
print("Largest number:", largest)print("Numbers greater than average:",
greater_than_avg)
Question 6
Problem: Find the second largest number in a list and handle cases with fewer than 2 elements.
python
Copy code
# Input list of integers
numbers = list(map(int, input("Enter a list of integers: ").split()))
# Check for list lengthif len(numbers) < 2:
print("List has fewer than 2 elements.")else:
# Sort and find the second largest
unique_numbers = list(set(numbers))
unique_numbers.sort(reverse=True)
second_largest = unique_numbers[1] if len(unique_numbers) > 1 else
unique_numbers[0]
print("Second largest number:", second_largest)
Question 7
python
Copy code
# Helper function to check if a number is primedef is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Input list of positive integers
numbers = list(map(int, input("Enter a list of positive integers: ").split()))
# Count primes and list non-primes
prime_count = 0
non_primes = []
for num in numbers:
if is_prime(num):
prime_count += 1
else:
non_primes.append(num)
print("Number of prime numbers:", prime_count)print("Non-prime numbers:",
non_primes)
4o
You said:
ChatGPT
Question 8
Problem: Reverse the elements of a list without using the reverse method and check if the reversed list is
sorted in ascending order.
python
Copy code
# Input list of integers
numbers = list(map(int, input("Enter a list of integers: ").split()))
# Reverse the list using a for loop
reversed_list = []for i in range(len(numbers) - 1, -1, -1):
reversed_list.append(numbers[i])
# Check if the reversed list is sorted in ascending order using a while loop
is_sorted = True
i = 0while i < len(reversed_list) - 1:
if reversed_list[i] > reversed_list[i + 1]:
is_sorted = False
break
i += 1
print("Reversed list:", reversed_list)print("Is the reversed list sorted in ascending
order?", is_sorted)
Question 9
Problem: Create a new list with only positive numbers and calculate the product of all positive numbers.
python
Copy code
# Input list of numbers
numbers = list(map(int, input("Enter a list of numbers: ").split()))
# For loop to create a list of positive numbers
positive_numbers = [num for num in numbers if num > 0]
# Calculate the product of positive numbers using a while loop
product = 1
i = 0while i < len(positive_numbers):
product *= positive_numbers[i]
i += 1
print("Positive numbers:", positive_numbers)print("Product of all positive numbers:",
product)
Question 10
Problem: Capitalize each word in a list and remove words shorter than 4 characters.
python
Copy code
# Input list of words
words = input("Enter a list of words: ").split()
# For loop to capitalize each word and store in a new list
capitalized_words = [word.capitalize() for word in words]
# While loop to remove words shorter than 4 characters
i = 0while i < len(capitalized_words):
if len(capitalized_words[i]) < 4:
capitalized_words.pop(i)
else:
i += 1
print("Capitalized words with words shorter than 4 characters removed:",
capitalized_words)
To convert a string into a date in Python, you can use the datetime.strptime() method from the
datetime module. Here’s how to do it:
python
Copy code
from datetime import datetime
# Sample string date
date_string = "2023-10-25" # Example format: "YYYY-MM-DD"
# Convert the string into a date object
date_object = datetime.strptime(date_string, "%Y-%m-%d").date()
print("Date object:", date_object)
python
Copy code
# Number of terms in the Fibonacci sequence
num_terms = int(input("Enter the number of terms: "))
# Initialize the first two terms
a, b = 0, 1
fibonacci_sequence = []
# Generate the Fibonacci sequencefor _ in range(num_terms):
fibonacci_sequence.append(a)
a, b = b, a + b # Update values for the next iteration
print("Fibonacci sequence:", fibonacci_sequence)
Here’s a simple Python program to calculate the factorial of a number using a loop:
CLASSES IN PYTHON
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print(f"Name: {self.name}, Age: {self.age}")
def have_birthday(self):
self.age += 1
print(f"Happy Birthday, {self.name}! Now {self.age} years old.")
python
Copy code
# Function to convert a simple list into a dictionarydef list_to_dict(simple_list):
return {index: value for index, value in enumerate(simple_list)}
# Example Usage
simple_list = ['apple', 'banana', 'cherry']
dictionary = list_to_dict(simple_list)
print(dictionary) # Output: {0: 'apple', 1: 'banana', 2: 'cherry'}
class ParentClass:
def __init__(self):
self.parent_attribute = "This is a parent attribute"
def parent_method(self):
return "This is a method from the parent class"
# Child class inherits from ParentClassclass
ChildClass(ParentClass):
def __init__(self):
super().__init__() # Call the constructor of the parent class
self.child_attribute = "This is a child attribute"
def child_method(self):
return "This is a method from the child class"
# Example Usage
child_instance = ChildClass()print(child_instance.parent_attribute) # Output: This is
a parent attributeprint(child_instance.child_attribute) # Output: This is a child
attributeprint(child_instance.parent_method()) # Output: This is a method from the
parent classprint(child_instance.child_method()) # Output: This is a method from
the child class
class Car:
# Class attribute
wheels = 4 # All cars have 4 wheels
def car_info(self):
"""Method to display car information."""
return f"{self.year} {self.make} {self.model} with {Car.wheels} wheels."
# Example Usage
my_car = Car("Toyota", "Camry", 2022)print(my_car.car_info()) # Output: 2022
Toyota Camry with 4 wheels.
python
Copy code
class Car:
# Class attribute
wheels = 4 # All cars have 4 wheels
# Example Usage
my_car = Car()
# Setting instance attributes directly
my_car.make = "Toyota" # Brand of the car
my_car.model = "Camry" # Model of the car
my_car.year = 2022 # Year of manufacture
# Accessing attributes directlyprint("Make:", my_car.make) # Output: Make:
Toyotaprint("Model:", my_car.model) # Output: Model: Camryprint("Year:",
my_car.year) # Output: Year: 2022print("Wheels:", Car.wheels) # Output:
Wheels: 4