20 Python Projects
20 Python Projects
In [5]:
# Get the message from the user
message = input("Enter a message: ")
# Use an if statement to compare the two numbers and print the larger one
if num1 > num2:
print(num1)
else:
print(num2)
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: "))
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: "))
# 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.
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: "))
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
return sum
# Driver Code
x = 9
n = 10
print('%.4f'% Series(x, n))
-5.1463
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
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..
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
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)
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
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]
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
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
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
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
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:
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
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]
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)
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))
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](" ", "")