0% found this document useful (0 votes)
15 views1 page

20 Python Projects

The document provides a series of Python programming exercises covering various topics such as input/output operations, number comparisons, pattern generation, series calculations, and character counting. Each section includes code snippets that demonstrate how to implement the tasks, along with example inputs and outputs. The exercises range from basic to more complex concepts like perfect numbers, prime checking, and Fibonacci series generation.

Uploaded by

mihirtilotia
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)
15 views1 page

20 Python Projects

The document provides a series of Python programming exercises covering various topics such as input/output operations, number comparisons, pattern generation, series calculations, and character counting. Each section includes code snippets that demonstrate how to implement the tasks, along with example inputs and outputs. The exercises range from basic to more complex concepts like perfect numbers, prime checking, and Fibonacci series generation.

Uploaded by

mihirtilotia
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

1. Input a welcome message and display it.

In [5]:
# Get the message from the user
message = input("Enter a message: ")

# Display the message


print(message)

Enter a message: Welcome to Class 11


Welcome to Class 11

2.1 Input two numbers and display the larger number


In [3]:
# Get input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Use an if statement to compare the two numbers and print the larger one
if num1 > num2:
print(num1)
else:
print(num2)

Enter the first number: 4


Enter the second number: 6
6

You can also use the max() function to get the larger number. Here is an example of how you can do this:
In [5]:
# Get input from the user
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

# Use the max() function to get the larger number


larger_num = max(num1, num2)

# Print the larger number


print(larger_num)

Enter the first number: 5


Enter the second number: 6
6

2.2 Input two numbers and display the smaller number.


In [1]:
# Get user input for two numbers
num1 = input("Please enter the first number: ")
num2 = input("Please enter the second number: ")

# Convert the strings to integers, so we can compare them


num1 = int(num1)
num2 = int(num2)

# Find the smaller number


if num1 < num2:
smaller_num = num1
else:
smaller_num = num2

# Print the smaller number


print(f"The smaller number is: {smaller_num}")

Please enter the first number: 34


Please enter the second number: 23
The smaller number is: 23

3. Input three numbers and display the largest / smallest number


In [2]:
# Get user input for three numbers
num1 = input("Please enter the first number: ")
num2 = input("Please enter the second number: ")
num3 = input("Please enter the third number: ")

# Convert the strings to integers, so we can compare them


num1 = int(num1)
num2 = int(num2)
num3 = int(num3)

# Find the largest and smallest numbers


if num1 > num2:
if num1 > num3:
largest_num = num1
else:
largest_num = num3
else:
if num2 > num3:
largest_num = num2
else:
largest_num = num3

if num1 < num2:


if num1 < num3:
smallest_num = num1
else:
smallest_num = num3
else:
if num2 < num3:
smallest_num = num2
else:
smallest_num = num3

# Print the largest and smallest numbers


print(f"The largest number is: {largest_num}")
print(f"The smallest number is: {smallest_num}")

Please enter the first number: 143


Please enter the second number: 334
Please enter the third number: 292
The largest number is: 334
The smallest number is: 143

4. Generate the following patterns using nested loop


In [3]:
# Get the number of rows from the user
num_rows = int(input("Enter the number of rows: "))

# Use a nested loop to print the triangle pattern


for i in range(1, num_rows+1):
for j in range(1, i+1):
print("*", end="")
print()

Enter the number of rows: 6


*
**
***
****
*****
******
Note : For the above example you can generate this pattern with any symbol you like, by replacing * to any other symbol.

Below code will help you to generate above pattern in reverse


In [4]:
# Get the number of rows from the user
num_rows = int(input("Enter the number of rows: "))

# Nested loop to print the pattern


for i in range(num_rows, 0, -1):
for j in range(i):
print("*", end="")
print()

Enter the number of rows: 6


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

5. Write a program to input the value of x and n and print the sum of the following series:
1 + x + x^2 + x^3 + x^4 + ... + x^n

In [8]:
# Get the values of x and n from the user
x = float(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))

# Initialize the sum to 0


sum = 0

# Loop from 0 to n, and add x^i to the sum for each i


for i in range(n+1):
sum += x**i

# Print the sum


print(f"The sum of the series is: {sum}")

# This code will ask the user to input the values of x and n, and then it will use a loop to add up the terms
# of the series. The loop starts at 0 and goes up to n, and for each value of i, it adds x^i to the sum.
# The value of x can be any real number, and the value of n must be a non-negative integer.

Enter the value of x: 2


Enter the value of n: 4
The sum of the series is: 31.0

1-x+x^2+x^3+x^4+...+x^n
In [9]:
# Get user input for x and n
x = float(input("Please enter the value of x: "))
n = int(input("Please enter the value of n: "))

# Initialize the sum to 0


sum = 0

# Loop to calculate the sum


for i in range(n+1):
sum += x**i

# Print the sum


print(f"The sum of the series is: {sum}")

Please enter the value of x: 2


Please enter the value of n: 3
The sum of the series is: 15.0

x-x^2/2+x^3/3-x^4/4+...+x^n/n

In [13]:
def SUM(x, n):
total = 1
for i in range(1, n + 1):
total = total + ((x**i)/i)
return total

# Driver Code
x = 2
n = 5
s = SUM(x, n)
print(round(s, 2))

18.07

x-x^2/2!+x^3/3!-x^4/4!+...+x^n/n!
In [14]:
import math

# Function to get the series


def Series( x , n ):
sum = 1
term = 1
y = 2

# Sum of n-1 terms starting from 2nd term


for i in range(1,n):
fct = 1
for j in range(1,y+1):
fct = fct * j

term = term * (-1)


m = term * [Link](x, y) / fct
sum = sum + m
y += 2

return sum

# Driver Code
x = 9
n = 10
print('%.4f'% Series(x, n))

-5.1463

6. Determine whether a number is a perfect number, an armstrong number or a


palindrome
This code defines three functions: is_perfect, is_armstrong, and is_palindrome. The is_perfect function checks whether a number is a perfect number, the is_armstrong function
checks whether a number is an Armstrong number, and the is_palindrome function checks whether a number is a palindrome.

To test the functions, the code prompts the user to enter a number, and then it calls each of the functions with the entered number as an argument. The functions return a
Boolean value indicating whether the number is a perfect number, an Armstrong number, or a palindrome, respectively.

A perfect number is a positive integer that is equal to the sum of its proper positive divisors (that is, the sum of its divisors excluding the number itself). For example, the first
four perfect numbers are 6, 28, 496, and 8128.

An Armstrong number is a number that is equal to the sum of the cubes of its digits. For example, 153 is an Armstrong number, because 153 = 1^3 + 5^3 + 3^3.

A palindrome is a number that is the same when read forwards or backwards. For example, 12321 is a palindrome, because it is the same when read forwards or backwards.

Here is some example code in Python that will determine whether a number is a perfect number, an Armstrong number, or a palindrome:
In [15]:
# Function to check if a number is a perfect number
def is_perfect(num):
sum = 0
for i in range(1, num):
if num % i == 0:
sum += i
return sum == num

# Function to check if a number is an Armstrong number


def is_armstrong(num):
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
return sum == num

# Function to check if a number is a palindrome


def is_palindrome(num):
temp = num
rev = 0
while temp > 0:
rev = rev * 10 + temp % 10
temp //= 10
return rev == num

# Test the functions


num = int(input("Enter a number: "))
print("Perfect number?")
print(is_perfect(num))
print("Armstrong number?")
print(is_armstrong(num))
print("Palindrome?")
print(is_palindrome(num))

Enter a number: 12321


Perfect number?
False
Armstrong number?
False
Palindrome?
True

You can also modify above result by applying if else condition

7. Input a number and check if the number is a prime or composite number


In [16]:
# Function to check if a number is prime
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True

# Test the function


num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is a composite number.")

Enter a number: 17
17 is a prime number.
--- For example, if the user enters 7, the code will call is_prime(7), which will return True, indicating that the number is prime. The code will then print 7 is a prime number.. On
the other hand, if the user enters 10, the code will call is_prime(10), which will return False, indicating that the number is composite. The code will then print 10 is a composite
number..

8. Display the terms of a Fibonacci series


This code defines a function display_fibonacci that takes a single argument n and displays the first n terms of the Fibonacci series. The Fibonacci series is a sequence of
numbers in which each term is the sum of the previous two terms, with the first two terms being 0 and 1.

The function initializes the variables a and b to the first two terms of the series (0 and 1, respectively), and it prints these two terms. It then uses a for loop to iterate over the
values from 2 to n-1, and for each iteration it calculates the next term of the series by adding a and b, and then it prints the result. It then updates the values of a and b to the
current values of b and c, respectively, so that they can be used to calculate the next term in the next iteration.

To test the function, the code prompts the user to enter the number of terms, and then it calls the display_fibonacci function with this value as an argument. The function
calculates and displays the first n terms of the Fibonacci series.

In [18]:
# Function to display the terms of a Fibonacci series
def display_fibonacci(n):
# Initialize the first two terms
a = 0
b = 1

# Print the first two terms


print(a)
print(b)

# Calculate and print the remaining terms


for i in range(2, n):
c = a + b
print(c)
a = b
b = c

# Test the function


num_terms = int(input("Enter the number of terms: "))
display_fibonacci(num_terms)

Enter the number of terms: 5


0
1
1
2
3

9. Compute the greatest common divisor and least common multiple of two integers
This code defines two functions: gcd and lcm. The gcd function takes two integers a and b as arguments and returns their greatest common divisor using the Euclidean
algorithm. The lcm function takes two integers a and b as arguments and returns their least common multiple by dividing their product by their GCD (which is calculated using
the gcd function).

To test the functions, the code prompts the user to enter two integers, and then it calls the gcd and lcm functions with these integers as arguments. The functions return the
GCD and LCM of the two integers, respectively, and the code prints the results.

In [19]:
# Function to compute the GCD
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)

# Function to compute the LCM


def lcm(a, b):
return a * b // gcd(a, b)

# Test the functions


a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
print(f"The GCD of {a} and {b} is: {gcd(a, b)}")
print(f"The LCM of {a} and {b} is: {lcm(a, b)}")

Enter the first integer: 12


Enter the second integer: 16
The GCD of 12 and 16 is: 4
The LCM of 12 and 16 is: 48

10. Count and display the number of vowels, consonants, uppercase, lowercase
characters in string
This code defines a function count_chars that takes a string s as an argument and returns the number of vowels, consonants, uppercase, and lowercase characters in the string.
The function uses a for loop to iterate over the characters in the string, and it uses the isalpha, isupper, and islower methods to check the type of each character. For each
character, the function increments the appropriate count variable depending on whether the character is a vowel, consonant, uppercase, or lowercase character.

To test the function, the code prompts the user to enter a string, and then it calls the count_chars function with this string as an argument. The function returns the counts of the
various types of characters in the string, and the code prints these counts.

For example, if the user enters the string "Hello, World!", the code will call count_chars("Hello, World!"), which will return the counts (2, 7, 2, 8).

In [21]:
# Function to count the number of vowels, consonants, uppercase, and lowercase characters
def count_chars(s):
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0

for c in s:
if [Link]():
if c in ['a', 'e', 'i', 'o', 'u']:
vowels += 1
else:
consonants += 1
if [Link]():
uppercase += 1
if [Link]():
lowercase += 1

return vowels, consonants, uppercase, lowercase

# Test the function


s = input("Enter a string: ")
vowels, consonants, uppercase, lowercase = count_chars(s)
print(f"Number of vowels: {vowels}")
print(f"Number of consonants: {consonants}")
print(f"Number of uppercase characters: {uppercase}")
print(f"Number of lowercase characters: {lowercase}")

Enter a string: I am in Class 11


Number of vowels: 3
Number of consonants: 7
Number of uppercase characters: 2
Number of lowercase characters: 8

11. Input a string and determine whether it is a palindrome or not; convert the case of
characters in a string.
This code defines two functions: is_palindrome and toggle_case. The is_palindrome function takes a string s as an argument and returns a Boolean value indicating whether the
string is a palindrome or not. It does this by using the slice notation s[::-1] to reverse the string and then comparing it to the original string.

The toggle_case function takes a string s as an argument and returns a new string with the case of the characters in the original string toggled. It does this by using the
swapcase method to convert the characters in the string.

To test the functions, the code prompts the user to enter a string, and then it calls the is_palindrome and toggle_case functions with this string as an argument. The functions
return a Boolean value indicating whether the string is a palindrome, and a new string with the toggled case of the characters, respectively, and the code prints these values.

For example, if the user enters the string "racecar", the code will call is_palindrome("racecar"), which will return True, indicating that the string is a palindrome. It will also call
toggle_case("racecar"), which will return "RACECAR". The code will then print Palindrome? True and Toggled case: RACECAR.

In [22]:
# Function to check if a string is a palindrome
def is_palindrome(s):
return s == s[::-1]

# Function to convert the case of the characters in a string


def toggle_case(s):
return [Link]()

# Test the functions


s = input("Enter a string: ")
print(f"Palindrome? {is_palindrome(s)}")
print(f"Toggled case: {toggle_case(s)}")

Enter a string: racecar


Palindrome? True
Toggled case: RACECAR

12. Find the largest/smallest number in a list/tuple


This code defines a function find_extremes that takes a list or tuple of numbers as an argument and returns the largest and smallest numbers in the list or tuple. The function
initializes the variables largest and smallest to the first number in the list or tuple, and then it uses a for loop to iterate over the remaining numbers. For each number, it checks if
it is larger than the current value of largest, and if it is, it updates largest to the new value. It also checks if the number is smaller than the current value of smallest, and if it is, it
updates smallest to the new value.

To test the function, the code creates a list of numbers and calls the `find_extrem

In [24]:
# Function to find the largest and smallest number in a list or tuple
def find_extremes(numbers):
largest = numbers[0]
smallest = numbers[0]
for number in numbers:
if number > largest:
largest = number
if number < smallest:
smallest = number
return largest, smallest

# Test the function


numbers = [3, 5, 2, 8, 1, 4]
largest, smallest = find_extremes(numbers)
print(f"Largest number: {largest}")
print(f"Smallest number: {smallest}")

Largest number: 8
Smallest number: 1

13. Input a list of numbers and swap elements at the even location with the elements at
the odd location
Here is some example code in Python that will input a list of numbers and swap the elements at even locations with the elements at odd locations:

This code defines a function swap_elements that takes a list of numbers as an argument and returns a new list with the elements at even locations swapped with the elements at
odd locations. The function uses a for loop to iterate over the elements of the list by increments of 2 (that is, it iterates over the even-indexed elements). For each iteration, it
checks if the element at the next odd index exists (using the len function and an if statement), and if it does, it swaps the elements at the current even index and the next odd
index using tuple assignment.

To test the function, the code creates a list of numbers and calls the swap_elements function with this list as an argument. The function returns a new list with the elements at
even and odd locations swapped, and the code prints the original list and the swapped list.

In [25]:
# Function to swap elements at even and odd locations
def swap_elements(numbers):
for i in range(0, len(numbers), 2):
if i+1 < len(numbers):
numbers[i], numbers[i+1] = numbers[i+1], numbers[i]
return numbers

# Test the function


numbers = [1, 2, 3, 4, 5, 6]
print(f"Original list: {numbers}")
swapped = swap_elements(numbers)
print(f"Swapped list: {swapped}")

Original list: [1, 2, 3, 4, 5, 6]


Swapped list: [2, 1, 4, 3, 6, 5]
--- In this example, the original list is [1, 2, 3, 4, 5, 6], and the function swap_elements returns a new list with the elements at even and odd locations swapped: [2, 1, 4, 3, 6, 5].
The code then prints the original list and the swapped list.

14. Input a list/tuple of elements, search for a given element in the list/tuple
This code defines a function search_element that takes a list or tuple of elements and an element to search for as arguments, and it returns a Boolean value indicating whether
the element was found in the list or tuple. The function uses the in operator to check if the element is in the list or tuple, and it returns True if it is, or False if it is not.

To test the function, the code creates a list of elements and prompts the user to enter an element to search for. It then calls the search_element function with the list and the
element as arguments, and it prints a message indicating whether the element was found in the list or not.

In [26]:
# Function to search for an element in a list or tuple
def search_element(elements, element):
if element in elements:
return True
return False

# Test the function


elements = [1, 2, 3, 4, 5, 6]
element = int(input("Enter the element to search for: "))
if search_element(elements, element):
print(f"Element {element} found in list.")
else:
print(f"Element {element} not found in list.")

Enter the element to search for: 3


Element 3 found in list.
--- In this example, the list of elements is [1, 2, 3, 4, 5, 6], and the user enters 3 as the element to search for. The function search_element is called with these arguments, and it
returns True, indicating that the element was found in the list. The code then prints the message Element 3 found in list..

If the user had entered a different element, such as 7, the function would have returned False, and the code would have printed the message Element 7 not found in list..

15. Input a list of numbers and find the smallest and largest number from the list
Here is some example code in Python that will input a list of numbers and find the smallest and largest number from the list:

This code defines a function find_extremes that takes a list of numbers as an argument and returns the smallest and largest numbers in the list. The function initializes the
variables smallest and largest to the first number in the list, and then it uses a for loop to iterate over the remaining numbers. For each number, it checks if it is smaller than the
current value of smallest, and if it is, it updates smallest to the new value. It also checks if the number is larger than the current value of largest, and if it is, it updates largest to
the new value.

To test the function, the code creates a list of numbers and calls the find_extremes function with this list as an argument. The function returns the smallest and largest numbers
in the list, and the code prints these values.

For example, given the list [3, 5, 2, 8, 1, 4], the code will call find_extremes([3, 5, 2, 8, 1, 4]), which will return the tuple (1, 8). The code will then print Smallest number: 1 and
Largest number: 8.

In [27]:
# Function to find the smallest and largest number in a list
def find_extremes(numbers):
smallest = numbers[0]
largest = numbers[0]
for number in numbers:
if number < smallest:
smallest = number
if number > largest:
largest = number
return smallest, largest

# Test the function


numbers = [3, 5, 2, 8, 1, 4]
smallest, largest = find_extremes(numbers)
print(f"Smallest number: {smallest}")
print(f"Largest number: {largest}")

Smallest number: 1
Largest number: 8

16. Create a dictionary with the roll number, name and marks of n students in a class and
display the names of students who have scored marks above 75
Here is some example code in Python that will create a dictionary with the roll number, name, and marks of n students in a class, and will display the names of students who have
scored marks above 75:

This code defines a function create_students_dict that takes an integer n as an argument and returns a dictionary with n entries, where each entry is a tuple containing the roll
number, name, and marks of a student. The function uses a for loop to iterate n times, and for each iteration it prompts the user to enter the roll number, name, and marks of a
student. It then adds an entry to the dictionary with the roll number as the key and the tuple containing the name and marks as the value.

To test the function, the code prompts the user to enter the number of students, and then it calls the create_students_dict function with this number as an argument. The
function returns a dictionary with the roll numbers, names, and marks of the students, and the code stores this dictionary in the variable students.

The code then uses a for loop to iterate over the entries in the students dictionary, and it uses an if statement to check if the marks of a student are above 75. If they are, it prints
the name of the student.

For example, if the user enters 3 as the number of students and then enters the following details for the students:

Enter roll number: 1 Enter name: Alice Enter marks: 80 Enter roll number: 2 Enter name: Bob Enter marks: 70 Enter roll number: 3 Enter name: Charlie Enter marks: 85

The code will call create_students_dict(3), which will return the dictionary {1: ("Alice", 80), 2: ("Bob", 70), 3: ("Charlie", 85)}. The code will then iterate over this dictionary and
print the names of the students who have scored marks above 75:

Students with marks above 75: Alice Charlie

In [28]:
# Function to create a dictionary with the roll number, name, and marks of n students
def create_students_dict(n):
students = {}
for i in range(n):
roll_number = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
students[roll_number] = (name, marks)
return students

# Test the function


n = int(input("Enter number of students: "))
students = create_students_dict(n)

# Display the names of students who have scored marks above 75


print("Students with marks above 75:")
for roll_number, (name, marks) in [Link]():
if marks > 75:
print(name)

Enter number of students: 3


Enter roll number: 12
Enter name: Devkant
Enter marks: 98
Enter roll number: 23
Enter name: Chinmay
Enter marks: 45
Enter roll number: 14
Enter name: Mukund
Enter marks: 76
Students with marks above 75:
Devkant
Mukund

17. Write a code snippet to reverse a string


Here is some example code in Python that will reverse a string:

This code defines a function reverse_string that takes a string s as an argument and returns a new string with the characters in s reversed. It does this using the slice notation
s[::-1], which returns a new string with the characters in s reversed.

To test the function, the code creates a string and calls the reverse_string function with this string as an argument. The function returns a new string with the characters in the
original string reversed, and the code prints the original string and the reversed string.

For example, if the string is "Hello, world!", the code will call reverse_string("Hello, world!"), which will return the string "!dlrow ,olleH". The code will then print Original string:
Hello, world! and Reversed string: !dlrow ,olleH.

In [29]:
# Function to reverse a string
def reverse_string(s):
return s[::-1]

# Test the function


s = "Hello, world!"
reversed_s = reverse_string(s)
print(f"Original string: {s}")
print(f"Reversed string: {reversed_s}")

Original string: Hello, world!


Reversed string: !dlrow ,olleH

18. Write a code snippet to sort a list in Python


This code defines a function sort_list that takes a list l as an argument and returns a new list with the elements in l sorted in ascending order. It does this using the built-in sorted
function, which returns a new sorted list.

To test the function, the code creates a list and calls the sort_list function with this list as an argument. The function returns a new sorted list, and the code prints the original list
and the sorted list.

For example, given the list [3, 5, 2, 8, 1, 4], the code will call sort_list([3, 5, 2, 8, 1, 4]), which will return the list [1, 2, 3, 4, 5, 8]. The code will then print Original list: [3, 5, 2, 8, 1,
4] and Sorted list: [1, 2, 3, 4, 5, 8].

In [30]:
# Function to sort a list
def sort_list(l):
return sorted(l)

# Test the function


l = [3, 5, 2, 8, 1, 4]
sorted_l = sort_list(l)
print(f"Original list: {l}")
print(f"Sorted list: {sorted_l}")

Original list: [3, 5, 2, 8, 1, 4]


Sorted list: [1, 2, 3, 4, 5, 8]

19. Write a python code to remove duplicate elements from a list


Here is some example code in Python that will remove duplicate elements from a list:

This code defines a function remove_duplicates that takes a list l as an argument and returns a new list with the duplicate elements in l removed. It does this using the set
function, which constructs a new set from the elements in the list, and the list function, which constructs a new list from the elements in the set. Since sets do not allow
duplicate elements, this will remove the duplicates from the list.

To test the function, the code creates a list with duplicate elements and calls the remove_duplicates function with this list as an argument. The function returns a new list with
the duplicate elements removed, and the code prints the original list and the list with no duplicates.

For example, given the list [1, 2, 2, 3, 3, 3, 4, 4, 4, 4], the code will call remove_duplicates([1, 2, 2, 3, 3, 3, 4, 4, 4, 4]), which will return the list [1, 2, 3, 4]. The code will then print
Original list: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] and List with no duplicates: [1, 2, 3, 4].

In [31]:
# Function to remove duplicate elements from a list
def remove_duplicates(l):
return list(set(l))

# Test the function


l = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
no_duplicates = remove_duplicates(l)
print(f"Original list: {l}")
print(f"List with no duplicates: {no_duplicates}")

Original list: [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]


List with no duplicates: [1, 2, 3, 4]

20. How to remove spaces from a string in Python


This code defines a function remove_spaces that takes a string s as an argument and returns a new string with all the spaces removed. It does this using the [Link]
method, which returns a new string with all occurrences of a specified string replaced with another string. In this case, it replaces all occurrences of the space character " " with
an empty string "".

To test the function, the code creates a string with spaces and calls the remove_spaces function with this string as an argument. The function returns a new string with the
spaces removed, and the code prints the original string and the string with no spaces.

For example, given the string "Hello, world! ", the code will call remove_spaces("Hello, world! "), which will return the string "Hello,world!". The code will then print Original string:
Hello, world! and String with no spaces: Hello,world!.

In [33]:
# Function to remove spaces from a string
def remove_spaces(s):
return [Link](" ", "")

# Test the function


s = "Hello, world! "
no_spaces = remove_spaces(s)
print(f"Original string: {s}")
print(f"String with no spaces: {no_spaces}")

Original string: Hello, world!


String with no spaces: Hello,world!

You might also like