0% found this document useful (0 votes)
2 views17 pages

Python User Input and Data Handling

Uploaded by

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

Python User Input and Data Handling

Uploaded by

Hamna Sattar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

28/10/2025, 11:57 Untitled19.

ipynb - Colab

# Prompt the user to input their first name and store it in the 'fname' variable
fname = input("Input your First Name : ")

# Prompt the user to input their last name and store it in the 'lname' variable
lname = input("Input your Last Name : ")

# Display a greeting message with the last name followed by the first name
print("Hello " + lname + " " + fname)

Input your First Name : hamna


Input your Last Name : sattar
Hello sattar hamna

# Prompt the user to input a sequence of comma-separated numbers and store it in the 'values' variable
values = input("Input some comma-separated numbers: ")

# Split the 'values' string into a list using commas as separators and store it in the 'list' variable
list = [Link](",")

# Convert the 'list' into a tuple and store it in the 'tuple' variable
tuple = tuple(list)

# Print the list


print('List : ', list)

# Print the tuple


print('Tuple : ', tuple)

Input some comma-separated numbers: 2,3,4,5,6,7


List : ['2', '3', '4', '5', '6', '7']
Tuple : ('2', '3', '4', '5', '6', '7')

# Prompt the user to input a filename and store it in the 'filename' variable
filename = input("Input the Filename: ")

# Split the 'filename' string into a list using the period (.) as a separator and store it in the 'f_extns' variable
f_extns = [Link](".")

# Print the extension of the file, which is the last element in the 'f_extns' list
print("The extension of the file is : " + repr(f_extns[-1]))

Input the Filename: hamna


The extension of the file is : 'hamna'

# Create a list called 'color_list' containing color names


color_list = ["Red", "Green", "White", "Black"]
# Print the first and last elements of the 'color_list' using string formatting
# The '%s' placeholders are filled with the values of 'color_list[0]' (Red) and 'color_list[-1]' (Black)
print("%s %s" % (color_list[0], color_list[-1]))

Red Black

# Define a tuple called 'exam_st_date' containing the exam start date in the format (day, month, year)
exam_st_date = (11, 12, 2014)

# Print the exam start date using string formatting


# The '%i' placeholders are filled with the values from the 'exam_st_date' tuple
print("The examination will start from : %i / %i / %i" % exam_st_date)

The examination will start from : 11 / 12 / 2014

# Prompt the user to input an integer and store it in the variable 'a'
a = int(input("Input an integer: "))

# Create new integers 'n1', 'n2', and 'n3' by concatenating 'a' with itself one, two, and three times, respectively
n1 = int("%s" % a) # Convert 'a' to an integer
n2 = int("%s%s" % (a, a)) # Concatenate 'a' with itself and convert to an integer
n3 = int("%s%s%s" % (a, a, a)) # Concatenate 'a' with itself twice and convert to an integer

[Link] 1/17
28/10/2025, 11:57 [Link] - Colab

# Calculate the sum of 'n1', 'n2', and 'n3' and print the result
print(n1 + n2 + n3)

Input an integer: 5
615

# Import the 'calendar' module


import calendar

# Prompt the user to input the year and month


y = int(input("Input the year : "))
m = int(input("Input the month : "))

# Print the calendar for the specified year and month


print([Link](y, m))

Input the year : 2025


Input the month : 6
June 2025
Mo Tu We Th Fr Sa Su
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

# Use triple double-quotes to create a multi-line string


print("""
a string that you "don't" have to escape
This
is a ....... multi-line
heredoc string --------> example
""")

a string that you "don't" have to escape


This
is a ....... multi-line
heredoc string --------> example

# Import the 'date' class from the 'datetime' module


from datetime import date

[Link] 2/17
28/10/2025, 11:57 [Link] - Colab

# Define a start date as July 2, 2014


f_date = date(2014, 7, 2)

# Define an end date as July 11, 2014


l_date = date(2014, 7, 11)

# Calculate the difference between the end date and start date
delta = l_date - f_date

# Print the number of days in the time difference


print([Link])

# Define the value of pi


pi = 3.1415926535897931

# Define the radius of the sphere


r = 6.0

# Calculate the volume of the sphere using the formula


V = 4.0/3.0 * pi * r**3

# Print the calculated volume of the sphere


print('The volume of the sphere is: ', V)

The volume of the sphere is: 904.7786842338603

# Define a function named "difference" that takes an integer parameter "n"


def difference(n):
# Check if n is less than or equal to 17
if n <= 17:
# If n is less than or equal to 17, return the absolute difference between 17 and n
return 17 - n
else:
# If n is greater than 17, return the absolute difference between n and 17 multiplied by 2
return (n - 17) * 2

# Call the "difference" function with the argument 22 and print the result
print(difference(22))

# Call the "difference" function with the argument 14 and print the result
print(difference(14))

10
3

# Define a function named "near_thousand" that takes an integer parameter "n"


def near_thousand(n):
# Check if the absolute difference between 1000 and n is less than or equal to 100
# OR check if the absolute difference between 2000 and n is less than or equal to 100

[Link] 3/17
28/10/2025, 11:57 [Link] - Colab
return ((abs(1000 - n) <= 100) or (abs(2000 - n) <= 100))

# Call the "near_thousand" function with the argument 1000 and print the result
print(near_thousand(1000))

# Call the "near_thousand" function with the argument 900 and print the result
print(near_thousand(900))

# Call the "near_thousand" function with the argument 800 and print the result
print(near_thousand(800))

# Call the "near_thousand" function with the argument 2200 and print the result
print(near_thousand(2200))

True
True
False
False

# Define a function named "sum_thrice" that takes three integer parameters: x, y, and z
def sum_thrice(x, y, z):
# Calculate the sum of x, y, and z
sum = x + y + z

# Check if x, y, and z are all equal (all three numbers are the same)
if x == y == z:
# If they are equal, triple the sum
sum = sum * 3

# Return the final sum


return sum

# Call the "sum_thrice" function with the arguments (1, 2, 3) and print the result
print(sum_thrice(1, 2, 3))

# Call the "sum_thrice" function with the arguments (3, 3, 3) and print the result
print(sum_thrice(3, 3, 3))

6
27

# Define a function named "new_string" that takes a string parameter called "text"
def new_string(text):
# Check if the length of the "text" is greater than or equal to 2 and if the first two characters of "text" are "Is"
if len(text) >= 2 and text[:2] == "Is":
# If the conditions are met, return the original "text" unchanged
return text
else:
# If the conditions are not met, prepend "Is" to the "text" and return the modified string
return "Is" + text

# Call the "new_string" function with the argument "Array" and print the result
print(new_string("Array"))

# Call the "new_string" function with the argument "IsEmpty" and print the result
print(new_string("IsEmpty"))

IsArray
IsEmpty

# Define a function called histogram that takes a list of items as a parameter.


def histogram(items):
# Iterate through the items in the list.
for n in items:
output = '' # Initialize an empty string called output.
times = n # Set the times variable to the value of n.

# Use a while loop to append '*' to the output string 'times' number of times.
while times > 0:
output += '*'
times = times - 1 # Decrement the times variable.

# Print the resulting output string.

[Link] 4/17
28/10/2025, 11:57 [Link] - Colab
print(output)

# Call the histogram function with a list of numbers and print the histogram.
histogram([1,2, 3, 4, 5, 6])

*
**
***
****
*****
******

# Define a function called reverse_histogram that takes a list of items as a parameter.


def reverse_histogram(items):
# Iterate through the items in the list in reverse order.
for n in reversed(items):
output = '' # Initialize an empty string called output.
times = n # Set the times variable to the value of n.

# Use a while loop to append '*' to the output string 'times' number of times.
while times > 0:
output += '*'
times = times - 1 # Decrement the times variable.

# Print the resulting output string.


print(output)

# Call the reverse_histogram function with a list of numbers and print the reversed histogram.
reverse_histogram([1, 2, 3, 4, 5, 6])

******
*****
****
***
**
*

# Define a function called concatenate_list_data that takes a list as a parameter.


def concatenate_list_data(lst):
result = '' # Initialize an empty string called result.

# Iterate through the elements in the list.


for element in lst:
result += str(element) # Convert each element to a string and concatenate it to the result.

return result # Return the concatenated string.

# Call the concatenate_list_data function with a list of numbers and print the result.
print(concatenate_list_data([1, 5, 12, 2]))

15122

# Define a list of numbers.


numbers = [
386, 462, 47, 418, 907, 344, 236, 375, 823, 566, 597, 978, 328, 615, 953, 345,
399, 162, 758, 219, 918, 237, 412, 566, 826, 248, 866, 950, 626, 949, 687, 217,
815, 67, 104, 58, 512, 24, 892, 894, 767, 553, 81, 379, 843, 831, 445, 742, 717,
958,743, 527
]

# Iterate through the numbers in the list.


for x in numbers:
if x == 237:
print(x) # Print the number if it's 237.
break # Exit the loop if 237 is found.
elif x % 2 == 0:
print(x) # Print the number if it's even.

386
462
418
344
236

[Link] 5/17
28/10/2025, 11:57 [Link] - Colab
566
978
328
162
758
918
237

# Create two sets, color_list_1 and color_list_2.


color_list_1 = set(["White", "Black", "Red"])
color_list_2 = set(["Red", "Green"])

# Print the original elements of the sets.


print("Original set elements:")
print(color_list_1)
print(color_list_2)

# Calculate and print the difference of color_list_1 and color_list_2.


print("\nDifference of color_list_1 and color_list_2:")
print(color_list_1.difference(color_list_2))

# Calculate and print the difference of color_list_2 and color_list_1.


print("\nDifference of color_list_2 and color_list_1:")
print(color_list_2.difference(color_list_1))

Original set elements:


{'White', 'Red', 'Black'}
{'Red', 'Green'}

Difference of color_list_1 and color_list_2:


{'White', 'Black'}

Difference of color_list_2 and color_list_1:


{'Green'}

# Define a function to calculate the greatest common divisor (GCD) of two numbers.
def gcd(x, y):
# Initialize gcd to 1.
gcd = 1

# Check if y is a divisor of x (x is divisible by y).


if x % y == 0:
return y

# Iterate from half of y down to 1.


for k in range(int(y / 2), 0, -1):
# Check if both x and y are divisible by k.
if x % k == 0 and y % k == 0:
# Update the GCD to the current value of k and exit the loop.
gcd = k
break

# Return the calculated GCD.


return gcd

# Print the GCD of specific pairs of numbers.


print("GCD of 12 & 17 =", gcd(12, 17))
print("GCD of 4 & 6 =", gcd(4, 6))
print("GCD of 336 & 360 =", gcd(336, 360))

GCD of 12 & 17 = 1
GCD of 4 & 6 = 2
GCD of 336 & 360 = 24

# Define a function 'sum_three' that takes three integer inputs: x, y, and z.


def sum_three(x, y, z):
# Check if any of the two input values are equal. If so, set 'sum' to 0.
if x == y or y == z or x == z:
sum = 0
else:
# If all three input values are distinct, calculate the sum of x, y, and z.
sum = x + y + z
# Return the calculated sum.
return sum

[Link] 6/17
28/10/2025, 11:57 [Link] - Colab
# Test the 'sum_three' function with different sets of input values and print the results.
print(sum_three(2, 1, 2))
print(sum_three(3, 2, 2))
print(sum_three(2, 2, 2))
print(sum_three(1, 2, 3))

0
0
0
6

# Define a function 'sum' that takes two integer inputs: x and y.


def sum(x, y):
# Calculate the sum of x and y and store it in the 'sum' variable.
sum = x + y
# Check if the calculated sum is within the range [15, 20) (inclusive on 15, exclusive on 20).
if sum in range(15, 20):
# If the sum is within the range, return 20.
return 20
else:
# If the sum is outside the range, return the calculated sum.
return sum

# Test the 'sum' function with different sets of input values and print the results.
print(sum(10, 6))
print(sum(10, 2))
print(sum(10, 12))

20
12
22

# Define the principal amount (initial investment).


amt = 10000
# Define the annual interest rate as a percentage.
int = 3.5
# Define the number of years.
years = 7
# Calculate the future value of the investment using the compound interest formula.
future_value = amt * ((1 + (0.01 * int)) ** years)
# Round the future value to two decimal places and print it.
print(round(future_value, 2))

12722.79

# Import the math module to use the square root function.


import math

# Define the coordinates of the first point (p1) as a list.


p1 = [4, 0]

# Define the coordinates of the second point (p2) as a list.


p2 = [6, 6]

# Calculate the distance between the two points using the distance formula.
# The formula computes the Euclidean distance in a 2D space.
distance = [Link](((p1[0] - p2[0]) ** 2) + ((p1[1] - p2[1]) ** 2))

# Print the calculated distance.


print(distance)

6.324555320336759

import time # Import the time module to measure execution time

class LogExecutionTime: # Define a class for the decorator


def __init__(self, func): # Initialize the decorator with the function to be decorated
[Link] = func # Store the function to be decorated

def __get__(self, instance, owner): # Define the descriptor method to handle instance methods
return lambda *args, **kwargs: self(instance, *args, **kwargs) # Return a lambda that passes the instance

[Link] 7/17
28/10/2025, 11:57 [Link] - Colab

def __call__(self, *args, **kwargs): # Make the class instance callable


instance = args[0] # Extract the instance from the arguments
start_time = [Link]() # Record the start time
result = [Link](instance, *args[1:], **kwargs) # Call the original function with its arguments
end_time = [Link]() # Record the end time
execution_time = end_time - start_time # Calculate the execution time
print(f"Execution time of {[Link].__name__}: {execution_time:.4f} seconds") # Log the execution time
return result # Return the result of the original function call

# Example usage:

class ExampleClass: # Define an example class to demonstrate the decorator


@LogExecutionTime # Apply the decorator to the method
def example_method(self): # Define a method in the class
for _ in range(1000000): # A sample computation to add some delay
pass # Do nothing

# Instantiate the example class and call the decorated method


example = ExampleClass() # Create an instance of the ExampleClass
example.example_method() # Call the decorated method to see the execution time log

Execution time of example_method: 0.0277 seconds

# Define a function to perform matrix multiplication of matrices A and B


def matrix_multiplication(A, B):
"""
Perform matrix multiplication of matrices A and B.

Args:
A: First matrix (list of lists).
B: Second matrix (list of lists).

Returns:
Result of matrix multiplication (list of lists).
"""
if len(A[0]) != len(B):
raise ValueError("Number of columns in A must equal number of rows in B")

# Number of rows and columns in resulting matrix


num_rows_A = len(A)
num_cols_B = len(B[0])
num_cols_A = len(A[0])

# Initialize the result matrix with zeros


result = [[0 for _ in range(num_cols_B)] for _ in range(num_rows_A)]

# Perform matrix multiplication


for i in range(num_rows_A):
for j in range(num_cols_B):
for k in range(num_cols_A):
result[i][j] += A[i][k] * B[k][j]

return result

# Example usage:
if __name__ == "__main__":
# Example matrices A and B
A = [[1, 2, 3],
[4, 5, 6]]

B = [[7, 8],
[9, 10],
[11, 12]]

# Print the result of matrix multiplication


print(matrix_multiplication(A, B))

[[58, 64], [139, 154]]

# License: [Link]

# Define a function named 'test' that takes a list 'nums' as input


def test(nums):
# Check if the length of 'nums' is 8 and the count of the fifth element in 'nums' is equal to 3

[Link] 8/17
28/10/2025, 11:57 [Link] - Colab
return len(nums) == 8 and [Link](nums[4]) == 3

# Create a list 'nums' with specific elements


nums = [19, 19, 15, 5, 5, 5, 1, 2]

# Print the original list


print("Original list:")
print(nums)

# Print the result of the test function applied to the 'nums' list
print("Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :")
print(test(nums))

# Create a different list 'nums' with specific elements


nums = [19, 15, 5, 7, 5, 5, 2]

# Print the original list


print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the modified 'nums' list
print("Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :")
print(test(nums))

# Create another list 'nums' with specific elements


nums = [11, 12, 14, 13, 14, 13, 15, 14]

# Print the original list


print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the modified 'nums' list
print("Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :")
print(test(nums))

# Create one more list 'nums' with specific elements


nums = [19, 15, 11, 7, 5, 6, 2]

# Print the original list


print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the modified 'nums' list
print("Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :")
print(test(nums))

Original list:
[19, 19, 15, 5, 5, 5, 1, 2]
Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :
True

Original list:
[19, 15, 5, 7, 5, 5, 2]
Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :
False

Original list:
[11, 12, 14, 13, 14, 13, 15, 14]
Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :
True

Original list:
[19, 15, 11, 7, 5, 6, 2]
Check whether the length of the said list is 8 and fifth element occurs thrice in the said list. :
False

# License: [Link]

# Define a function named 'test' that takes an integer 'n' as input


def test(n):
# Check if 'n' is congruent to 4 modulo 34 and greater than 4^4
return n % 34 == 4 and n > 4 ** 4

# Assign a specific integer 'n' to the variable


n = 922

# Print the original integer

[Link] 9/17
28/10/2025, 11:57 [Link] - Colab
print("Original Integer:")
print(n)

# Print the result of the test function applied to the integer 'n'
print("Check whether the said integer greater than 4^4 and which is 7 mod 134 :")
print(test(n))

# Assign a different integer 'n' to the variable


n = 914

# Print the original integer


print("\nOriginal Integer:")
print(n)

# Print the result of the test function applied to the modified integer 'n'
print("Check whether the said integer greater than 4^4 and which is 7 mod 134 :")
print(test(n))

# Assign another integer 'n' to the variable


n = 854

# Print the original integer


print("\nOriginal Integer:")
print(n)

# Print the result of the test function applied to the modified integer 'n'
print("Check whether the said integer greater than 4^4 and which is 7 mod 134 :")
print(test(n))

# Print the original integer again (note: the variable 'n' retains its previous value)
print("\nOriginal Integer:")
print(n)

# Print the result of the test function applied to the integer 'n' (no modification to 'n' since the previous assignment)
print("Check whether the said integer greater than 4^4 and which is 7 mod 134 :")
print(test(n))

Original Integer:
922
Check whether the said integer greater than 4^4 and which is 7 mod 134 :
True

Original Integer:
914
Check whether the said integer greater than 4^4 and which is 7 mod 134 :
False

Original Integer:
854
Check whether the said integer greater than 4^4 and which is 7 mod 134 :
True

Original Integer:
854
Check whether the said integer greater than 4^4 and which is 7 mod 134 :
True

# License: [Link]

# Define a function named 'test' that takes a list of strings 'str1' as input
def test(str1):
# Check if the second-to-last character of the last string in 'str1' is a proper substring of the last string
# and if the second-to-last character is different from the last character
return str1[len(str1) - 2] in str1[len(str1) - 1] and str1[len(str1) - 2] != str1[len(str1) - 1]

# Create a list of strings 'str11' with specific elements


str11 = ["a", "abb", "sfs", "oo", "de", "sfde"]

# Print the original list


print("Original list:")
print(str11)

# Print the result of the test function applied to the 'str11' list
print("Check the nth-1 string is a proper substring of nth string of the said list of strings:")
print(test(str11))

# Create a different list of strings 'str11' with specific elements

[Link] 10/17
28/10/2025, 11:57 [Link] - Colab
str11 = ["a", "abb", "sfs", "oo", "ee", "sfde"]

# Print the original list


print("\nOriginal list:")
print(str11)

# Print the result of the test function applied to the modified 'str11' list
print("Check the nth-1 string is a proper substring of nth string of the said list of strings:")
print(test(str11))

# Create another list of strings 'str11' with specific elements


str11 = ["a", "abb", "sad", "ooaa", "esdfe", "sfsdfde", "sfsd", "sfsdf", "qwrew"]

# Print the original list


print("\nOriginal list:")
print(str11)

# Print the result of the test function applied to the modified 'str11' list
print("Check the nth-1 string is a proper substring of nth string of the said list of strings:")
print(test(str11))

# Create one more list of strings 'str11' with specific elements


str11 = ["a", "abb", "sad", "ooaa", "esdfe", "sfsdfde", "sfsd", "sfsdf", "qwsfsdfrew"]

# Print the original list


print("\nOriginal list:")
print(str11)

# Print the result of the test function applied to the modified 'str11' list
print("Check the nth-1 string is a proper substring of nth string of the said list of strings:")
print(test(str11))

Original list:
['a', 'abb', 'sfs', 'oo', 'de', 'sfde']
Check the nth-1 string is a proper substring of nth string of the said list of strings:
True

Original list:
['a', 'abb', 'sfs', 'oo', 'ee', 'sfde']
Check the nth-1 string is a proper substring of nth string of the said list of strings:
False

Original list:
['a', 'abb', 'sad', 'ooaa', 'esdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwrew']
Check the nth-1 string is a proper substring of nth string of the said list of strings:
False

Original list:
['a', 'abb', 'sad', 'ooaa', 'esdfe', 'sfsdfde', 'sfsd', 'sfsdf', 'qwsfsdfrew']
Check the nth-1 string is a proper substring of nth string of the said list of strings:
True

# Define a function named 'test' that takes a list 'li' and an integer 'i' as input
def test(li, i):
# Check if the sum of the first 'i' integers in 'li' equals 'i'
return sum(li[:i]) == i

# Create a list 'nums' with specific elements


nums = [0, 1, 2, 3, 4, 5]

# Assign an integer 'i' to the variable


i = 1

# Print the original list


print("Original list:")
print(nums)

# Print a message indicating the current value of 'i'


print("Check the said list, where the sum of the first i integers is i: i =", i)

# Print the result of the test function applied to the 'nums' list with the current value of 'i'
print(test(nums, 1))

# Update the value of 'i'


i = 3

# Print a message indicating the updated value of 'i'

[Link] 11/17
28/10/2025, 11:57 [Link] - Colab
print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the 'nums' list with the updated value of 'i'
print("Check the said list, where the sum of the first i integers is i: i =", i)
print(test(nums, 3))

# Update the value of 'i' and 'nums'


i = 6
nums = [1, 1, 1, 1, 1, 1]

# Print a message indicating the updated value of 'i'


print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the updated 'nums' list with the updated value of 'i'
print("Check the said list, where the sum of the first i integers is i: i =", i)
print(test(nums, 6))

# Update the value of 'i' and 'nums'


i = 2
nums = [2, 2, 2, 2, 2]

# Print a message indicating the updated value of 'i'


print("\nOriginal list:")
print(nums)

# Print the result of the test function applied to the updated 'nums' list with the updated value of 'i'
print("Check the said list, where the sum of the first i integers is i: i =", i)
print(test(nums, 2))

Show hidden output

Next steps: Explain error

Original list: [0, 1, 2, 3, 4, 5] Check the said list, where the sum of the first i integers is i: i = 1 False

Original list: [0, 1, 2, 3, 4, 5] Check the said list, where the sum of the first i integers is i: i = 3 True

Original list: [1, 1, 1, 1, 1, 1] Check the said list, where the sum of the first i integers is i: i = 6 True

Original list: [2, 2, 2, 2, 2] Check the said list, where the sum of the first i integers is i: i = 2 False

# License: [Link]

# Define a function named 'test' that takes a list of strings 'strs' as input
def test(strs):
# Use a list comprehension to check if each string in 'strs' is a palindrome (reads the same forwards and backwards)
return [s == s[::-1] for s in strs]

# Create a list of strings 'strs' with specific elements


strs = ['palindrome', 'madamimadam', '', 'foo', 'eyes']

# Print the original list of strings


print("Original strings:")
print(strs)

# Print a message indicating the operation to be performed on the list


print("\nTest whether the given strings are palindromes or not:")

# Print the result of the test function applied to the 'strs' list
print(test(strs))

Original strings:
['palindrome', 'madamimadam', '', 'foo', 'eyes']

Test whether the given strings are palindromes or not:


[False, True, True, False, False]

# License: [Link]

# Define a function named 'test' that takes a list of strings 'strs' and a prefix 'prefix' as input
def test(strs, prefix):
# Use a list comprehension to filter strings in 'strs' that start with the given 'prefix'

[Link] 12/17
28/10/2025, 11:57 [Link] - Colab
return [s for s in strs if [Link](prefix)]

# Create a list of strings 'strs' with specific elements


strs = ['cat', 'car', 'fear', 'center']

# Assign a specific prefix 'prefix' to the variable


prefix = "ca"

# Print the original list of strings


print("Original strings:")
print(strs)

# Print the starting prefix


print("Starting prefix:", prefix)

# Print a message indicating the operation to be performed on the list


print("Strings in the said list starting with a given prefix:")

# Print the result of the test function applied to the 'strs' list with the given prefix
print(test(strs, prefix))

# Create a different list of strings 'strs' with specific elements


strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo']

# Assign a different prefix 'prefix' to the variable


prefix = "do"

# Print the original list of strings


print("\nOriginal strings:")
print(strs)

# Print the updated starting prefix


print("Starting prefix:", prefix)

# Print a message indicating the operation to be performed on the list


print("Strings in the said list starting with a given prefix:")

# Print the result of the test function applied to the modified 'strs' list with the updated prefix
print(test(strs, prefix))

Original strings:
['cat', 'car', 'fear', 'center']
Starting prefix: ca
Strings in the said list starting with a given prefix:
['cat', 'car']

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo']
Starting prefix: do
Strings in the said list starting with a given prefix:
['dog', 'donut']

# Define a function named 'test' that takes a list of strings 'words' as input
def test(words):
# Use the max function to find the string with the maximum length in 'words' based on the key=len (length of each string)
return max(words, key=len)

# Create a list of strings 'strs' with specific elements


strs = ['cat', 'car', 'fear', 'center']

# Print the original list of strings


print("Original strings:")
print(strs)

# Print a message indicating the operation to be performed on the list


print("Longest string of the said list of strings:")

# Print the result of the test function applied to the 'strs' list
print(test(strs))

# Create a different list of strings 'strs' with specific elements


strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']

# Print the original list of strings


print("\nOriginal strings:")
print(strs)

[Link] 13/17
28/10/2025, 11:57 [Link] - Colab

# Print a message indicating the operation to be performed on the list


print("Longest string of the said list of strings:")

# Print the result of the test function applied to the modified 'strs' list
print(test(strs))

Original strings:
['cat', 'car', 'fear', 'center']
Longest string of the said list of strings:
center

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Longest string of the said list of strings:
shatter

# Define a function named 'test' that takes a list of strings 'strs' and a substring 'substr' as input
def test(strs, substr):
# Use a list comprehension to filter strings in 'strs' that contain the given 'substr'
return [s for s in strs if substr in s]

# Create a list of strings 'strs' with specific elements


strs = ['cat', 'car', 'fear', 'center']

# Print the original list of strings


print("Original strings:")
print(strs)

# Assign a specific substring 'substrs' to the variable


substrs = 'ca'

# Print the substring


print("Substring: " + substrs)

# Print a message indicating the operation to be performed on the list


print("Strings in the said list containing a given substring:")

# Print the result of the test function applied to the 'strs' list with the given substring
print(test(strs, substrs))

# Create a different list of strings 'strs' with specific elements


strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']

# Print the original list of strings


print("\nOriginal strings:")
print(strs)

# Assign a different substring 'substrs' to the variable


substrs = 'o'

# Print the substring


print("Substring: " + substrs)

# Print a message indicating the operation to be performed on the list


print("Strings in the said list containing a given substring:")

# Print the result of the test function applied to the modified 'strs' list with the updated substring
print(test(strs, substrs))

# Create another list of strings 'strs' with specific elements


strs = ['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']

# Print the original list of strings


print("\nOriginal strings:")
print(strs)

# Assign a different substring 'substrs' to the variable


substrs = 'oe'

# Print the substring


print("Substring: " + substrs)

# Print a message indicating the operation to be performed on the list


print("Strings in the said list containing a given substring:")

[Link] 14/17
28/10/2025, 11:57 [Link] - Colab
# Print the result of the test function applied to the modified 'strs' list with the updated substring
print(test(strs, substrs))

Original strings:
['cat', 'car', 'fear', 'center']
Substring: ca
Strings in the said list containing a given substring:
['cat', 'car']

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Substring: o
Strings in the said list containing a given substring:
['dog', 'donut', 'todo']

Original strings:
['cat', 'dog', 'shatter', 'donut', 'at', 'todo', '']
Substring: oe
Strings in the said list containing a given substring:
[]

# Define a function named 'test' that takes a non-negative integer 'n' as input
def test(n):
# Use the map function to convert each integer in the range from 0 to 'n' (inclusive) to a string
# Then, use ' '.join to concatenate the strings with a space separator
return ' '.join(map(str, range(n + 1)))

# Assign a specific non-negative integer 'n' to the variable


n = 4

# Print the non-negative integer


print("Non-negative integer:")
print(n)

# Print a message indicating the operation to be performed


print("Non-negative integers up to n inclusive:")

# Print the result of the test function applied to the 'n' value
print(test(n))

# Assign a different non-negative integer 'n' to the variable


n = 20

# Print the non-negative integer


print("\nNon-negative integer:")
print(n)

# Print a message indicating the operation to be performed


print("Non-negative integers up to n inclusive:")

# Print the result of the test function applied to the updated 'n' value
print(test(n))

Non-negative integer:
4
Non-negative integers up to n inclusive:
0 1 2 3 4

Non-negative integer:
20
Non-negative integers up to n inclusive:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

# License: [Link]

# Define a function named 'test' that takes a string 's' as input


def test(s):
# Check if there is a space in the string 's'
if " " in s:
# Split the string into a list of strings using space as the delimiter
return [Link](" ")
# Check if there is a comma in the string 's'
elif "," in s:
# Split the string into a list of strings using comma as the delimiter
return [Link](",")
else:

[Link] 15/17
28/10/2025, 11:57 [Link] - Colab
# Return a list of lowercase letters with odd ASCII values
return [c for c in s if [Link]() and ord(c) % 2 == 0]

# Assign a specific string 'strs' to the variable


strs = "a b c d"

# Print the original string 'strs'


print("Original string:")
print(strs)

# Print a message indicating the operation to be performed


print("Split the said string into strings if there is a space in the string, \notherwise split on commas if there is a comma, \noth

# Print the result of the test function applied to the 'strs' string
print(test(strs))

# Assign a different string 'strs' to the variable


strs = "a,b,c,d"

# Print the original string 'strs'


print("\nOriginal string:")
print(strs)

# Print a message indicating the operation to be performed


print("Split the said string into strings if there is a space in the string, \notherwise split on commas if there is a comma, \noth

# Print the result of the test function applied to the updated 'strs' string
print(test(strs))

# Assign another different string 'strs' to the variable


strs = "abcd"

# Print the original string 'strs'


print("\nOriginal string:")
print(strs)

# Print a message indicating the operation to be performed


print("Split the said string into strings if there is a space in the string, \notherwise split on commas if there is a comma, \noth

# Print the result of the test function applied to the updated 'strs' string
print(test(strs))

Original string:
a b c d
Split the said string into strings if there is a space in the string,
otherwise split on commas if there is a comma,
otherwise return the list of lowercase letters with odd order:
['a', 'b', 'c', 'd']

Original string:
a,b,c,d
Split the said string into strings if there is a space in the string,
otherwise split on commas if there is a comma,
otherwise return the list of lowercase letters with odd order:
['a', 'b', 'c', 'd']

Original string:
abcd
Split the said string into strings if there is a space in the string,
otherwise split on commas if there is a comma,
otherwise return the list of lowercase letters with odd order:
['b', 'd']

# License: [Link]

# Define a function named 'test' that takes a list of numbers 'nums' as input
def test(nums):
# List comprehension to create a list of maximum values for each prefix of the input list
# Iterate through the indices from 1 to the length of 'nums' + 1
# For each index 'i', find the maximum value in the prefix nums[:i]
return [max(nums[:i]) for i in range(1, len(nums) + 1)]

# Assign a specific list of numbers 'nums' to the variable


nums = [0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]

# Print the original list of numbers 'nums'


print("Original list:")
print(nums)
[Link] 16/17
28/10/2025, 11:57 [Link] - Colab
print(nums)

# Print a message indicating the operation to be performed


print("List whose ith element is the maximum of the first i elements of the said list:")

# Print the result of the test function applied to the 'nums' list
print(test(nums))

# Assign a different list of numbers 'nums' to the variable


nums = [6, 5, 4, 3, 2, 1]

# Print the original list of numbers 'nums'


print("\nOriginal list:")
print(nums)

# Print a message indicating the operation to be performed


print("List whose ith element is the maximum of the first i elements of the said list:")

# Print the result of the test function applied to the updated 'nums' list
print(test(nums))

# Assign another list of numbers 'nums' to the variable


nums = [1, 19, 5, 15, 5, 25, 5]

# Print the original list of numbers 'nums'


print("\nOriginal list:")
print(nums)

# Print a message indicating the operation to be performed


print("List whose ith element is the maximum of the first i elements of the said list:")

# Print the result of the test function applied to the updated 'nums' list
print(test(nums))

Original list:
[0, -1, 3, 8, 5, 9, 8, 14, 2, 4, 3, -10, 10, 17, 41, 22, -4, -4, -15, 0]
List whose ith element is the maximum of the first i elements of the said list:
[0, 0, 3, 8, 8, 9, 9, 14, 14, 14, 14, 14, 14, 17, 41, 41, 41, 41, 41, 41]

Original list:
[6, 5, 4, 3, 2, 1]
List whose ith element is the maximum of the first i elements of the said list:
[6, 6, 6, 6, 6, 6]

Original list:
[1, 19, 5, 15, 5, 25, 5]
List whose ith element is the maximum of the first i elements of the said list:
[1, 19, 19, 19, 19, 25, 25]

[Link] 17/17

You might also like