0% found this document useful (0 votes)
5 views26 pages

Chat History

The document contains a series of discussions and examples related to Python functions and Object-Oriented Programming (OOP) concepts. It includes exercises on defining functions, handling parameters, recursion, and creating classes, along with user input examples. Additionally, it references various articles and topics related to Python programming, highlighting their last updated dates.

Uploaded by

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

Chat History

The document contains a series of discussions and examples related to Python functions and Object-Oriented Programming (OOP) concepts. It includes exercises on defining functions, handling parameters, recursion, and creating classes, along with user input examples. Additionally, it references various articles and topics related to Python programming, highlighting their last updated dates.

Uploaded by

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

Chat history

1.

1.

2.

3.

4.

5.

6.

7.

8.

9.

10.
11.

12.

13.

14.

1.

2.

3.

4.

5.

6.

7.

8.
9.

10.

11.

12.

13.

ChatGPT
Share

You said:
Python Functions Exercises This section offers a variety of exercises focused on Python
functions to help you master this essential programming concept. You’ll learn how to define
functions, work with parameters and return values, and explore advanced topics like lambda
functions, decorators, and recursion. How to get list of parameters name from a function in
Python? How to Print Multiple Arguments in Python? Python program to find the power of a
number using recursion Sorting objects of user defined class in Python Functions that accept
variable length key value pair as arguments GIVE EASY PROGRAM WITH OUTPUT
ChatGPT said:
ChatGPT
Memory updated

Here are solutions and examples for the requested Python function exercises:

1. Get List of Parameter Names from a Function in Python


You can use the inspect module to get the parameter names of a function.

python
Copy code
import inspect def example_function ( a, b, c=10 ): return a + b + c params =
inspect.signature(example_function).parameters print ( "Parameter names:" ,
list (params.keys()))

Output:
less
Copy code
Parameter names : ['a', 'b', 'c']

2. Print Multiple Arguments in Python


Use the print() function with multiple arguments.

python
Copy code
def print_multiple_args ( *args ): print (*args) print_multiple_args( "Hello" , "world!" ,
"This" , "is" , "Python." )

Output:

csharp
Copy code
Hello world! This is Python.

3. Python Program to Find the Power of a Number Using Recursion


python
Copy code
def power ( base, exp ): if exp == 0 : return 1 return base * power(base, exp - 1 )
print ( "2^3 =" , power( 2 , 3 ))

Output:

Copy code
2^3 = 8

4. Sorting Objects of a User-Defined Class in Python


python
Copy code
class Student : def __init__ ( self, name, grade ): self.name = name self.grade = grade
def __repr__ ( self ): return f"{self.name}: {self.grade}" students = [Student( "Alice" ,
90 ), Student( "Bob" , 85 ), Student( "Charlie" , 95 )] students_sorted = sorted (students,
key= lambda student: student.grade) print ( "Sorted Students by Grade:" ,
students_sorted)

Output:

yaml
Copy code
Sorted Students by Grade: [ Bob: 85 , Alice: 90 , Charlie: 95 ]

5. Function that Accepts Variable Length Key-Value Pairs


python
Copy code
def print_key_value_pairs ( **kwargs ): for key, value in kwargs.items(): print ( f"{key} =
{value}" ) print_key_value_pairs(name= "John" , age= 25 , country= "USA" )

Output:

makefile
Copy code
name = John age = 25 country = USA

Let me know if you need further explanations or additional exercises!

You said:
GIVE WITH USER INPUT
ChatGPT said:
ChatGPT

Here are the modified examples that include user input:

1. Get List of Parameter Names from a Function with User Input


To demonstrate this with user input, you could ask the user for a function definition and
display its parameters (more complex to handle). For simplicity, here is a straightforward
way:

python
Copy code
import inspect def example_function ( a, b, c=10 ): return a + b + c params =
inspect.signature(example_function).parameters print ( "Parameter names:" ,
list (params.keys()))

Modify the example_function code as needed for user-specific input.

2. Print Multiple Arguments with User Input


python
Copy code
def print_multiple_args ( *args ): print (*args) user_input = input ( "Enter multiple words
separated by spaces: " ) args = user_input.split() print_multiple_args(*args)

Example Run:

bash
Copy code
Enter multiple words separated by spaces: Hello world Python functions Output: Hello
world Python functions

3. Python Program to Find the Power of a Number Using Recursion


with User Input
python
Copy code
def power ( base, exp ): if exp == 0 : return 1 return base * power(base, exp - 1 ) base
= int ( input ( "Enter the base number: " )) exp = int ( input ( "Enter the exponent: " ))
print ( f"{base}^{exp} =" , power(base, exp))

Example Run:

yaml
Copy code
Enter the base number: 3 Enter the exponent: 4 Output: 3^4 = 81

4. Sorting Objects of a User-Defined Class with User Input


python
Copy code
class Student : def __init__ ( self, name, grade ): self.name = name self.grade = grade
def __repr__ ( self ): return f"{self.name}: {self.grade}" students = [] n =
int ( input ( "Enter the number of students: " )) for _ in range (n): name = input ( "Enter
student's name: " ) grade = int ( input ( "Enter student's grade: " ))
students.append(Student(name, grade)) students_sorted = sorted (students,
key= lambda student: student.grade) print ( "Sorted Students by Grade:" ,
students_sorted)

Example Run:

yaml
Copy code
Enter the number of students: 3 Enter student's name: Alice Enter student's grade:
90 Enter student's name: Bob Enter student's grade: 85 Enter student's name:
Charlie Enter student's grade: 95 Output: Sorted Students by Grade: [ Bob: 85 , Alice:
90 , Charlie: 95 ]

5. Function that Accepts Variable Length Key-Value Pairs with User


Input
python
Copy code
def print_key_value_pairs ( **kwargs ): for key, value in kwargs.items(): print ( f"{key} =
{value}" ) n = int ( input ( "Enter the number of key-value pairs: " )) pairs = {} for _ in
range (n): key = input ( "Enter the key: " ) value = input ( "Enter the value: " ) pairs[key] =
value print_key_value_pairs(**pairs)

Example Run:

yaml
Copy code
Enter the number of key-value pairs: 3 Enter the key: name Enter the value: John
Enter the key: age Enter the value: 25 Enter the key: country Enter the value: USA
Output: name = John age = 25 country = USA
Feel free to modify or extend these examples as needed!

You said:
Python OOPS Exercises Here in this practice section, you’ll find exercises focused on
Object-Oriented Programming (OOP) concepts in Python. These exercises are designed to
help you understand and implement key OOP principles such as classes, objects, inheritance,
polymorphism, encapsulation, and abstraction. Python program to build flashcard using class
in Python Shuffle a deck of card with OOPS in Python How to create an empty class in
Python? Student management system in Python GIVE EASY PROGRAM WITH USER
INPUT WITH OUTPUT
ChatGPT said:
ChatGPT
Memory updated

Here are Python programs that implement OOP concepts with user input:

1. Python Program to Build a Flashcard Using a Class


python
Copy code
import random class Flashcard : def __init__ ( self, question, answer ): self.question =
question self.answer = answer def display ( self ): user_answer = input ( f"Question:
{self.question} \nYour Answer: " ) if user_answer.lower() == self.answer.lower():
print ( "Correct!" ) else : print ( f"Wrong! The correct answer is: {self.answer}" ) flashcards
= [ Flashcard( "Capital of France?" , "Paris" ), Flashcard( "5 + 3?" , "8" ),
Flashcard( "Python keyword for function?" , "def" ) ] random_flashcard =
random.choice(flashcards) random_flashcard.display()

Example Run:

yaml
Copy code
Question: Capital of France? Your Answer: Paris Output: Correct!

2. Shuffle a Deck of Cards Using OOP in Python


python
Copy code
import random class Deck : def __init__ ( self ): self.cards = [ f"{rank} of {suit}" for suit
in [ 'Hearts' , 'Diamonds' , 'Clubs' , 'Spades' ] for rank in [ '2' , '3' , '4' , '5' , '6' , '7' , '8' ,
'9' , '10' , 'J' , 'Q' , 'K' , 'A' ]] def shuffle ( self ): random.shuffle(self.cards) def deal ( self,
num=1 ): dealt_cards = self.cards[:num] self.cards = self.cards[num:] return dealt_cards
deck = Deck() deck.shuffle() print ( "Shuffled deck dealt cards:" , deck.deal( 5 ))

Example Run:

less
Copy code
Shuffled deck dealt cards : ['7 of Hearts', 'Q of Spades', '3 of Diamonds', 'A of Clubs',
'10 of Hearts']
3. How to Create an Empty Class in Python?
python
Copy code
class EmptyClass : pass # Example of usage obj = EmptyClass() print ( "An instance of
EmptyClass was created:" , obj)

Example Run:

csharp
Copy code
An instance of EmptyClass was created: <__main__.EmptyClass object at
0x7f1234567890 >

4. Simple Student Management System in Python


python
Copy code
class Student : def __init__ ( self, name, student_id ): self.name = name self.student_id =
student_id def display_info ( self ): print ( f"Student ID: {self.student_id}, Name:
{self.name}" ) students = [] while True : print ( "\n1. Add Student\n2. Display Students\
n3. Exit" ) choice = input ( "Enter your choice: " ) if choice == '1' : name = input ( "Enter
student's name: " ) student_id = input ( "Enter student's ID: " )
students.append(Student(name, student_id)) elif choice == '2' : print ( "\nList of
Students:" ) for student in students: student.display_info() elif choice == '3' : break
else : print ( "Invalid choice. Please try again." )

Example Run:

mathematica
Copy code
1. Add Student 2. Display Students 3. Exit Enter your choice: 1 Enter student's
name: Alice Enter student's ID: S101 1. Add Student 2. Display Students 3. Exit
Enter your choice: 2 List of Students: Student ID: S101, Name: Alice 1. Add
Student 2. Display Students 3. Exit Enter your choice: 3

These examples help illustrate OOP principles while allowing user interaction. Let me know
if you need further modifications or additional explanations!

You said:
Python function-programs 25 posts Popular Articles Recent Articles How to get list of
parameters name from a function in Python? Last Updated: 02 July 2024 In this article, we
are going to discuss how to get list parameters from a function in Python. The inspect module
helps in checking the obje ...read more Technical Scripter Python Python-Functions Picked
Python function-programs Technical Scripter 2020 How to Print Multiple Arguments in
Python? Last Updated: 10 July 2024 An argument is a value that is passed within a function
when it is called.They are independent items, or variables, that contain data or cod ...read
more Python Python-Functions Picked Python function-programs Python program to find the
power of a number using recursion Last Updated: 02 May 2023 Given a number N and power
P, the task is to find the power of a number ( i.e. NP ) using recursion.Examples:Input: N =
2 , P = 3Output: 8In ...read more Technical Scripter Python Python Programs Picked Python
function-programs Technical Scripter 2020 Sorting objects of user defined class in Python
Last Updated: 03 July 2024 The following article discusses how objects of a user-defined
class can be arranged based on any of the variables of the class, which obviou ...read more
Python Python-Functions Python function-programs Python functools-module Assign
Function to a Variable in Python Last Updated: 03 July 2024 In this article, we are going to
see how to assign a function to a variable in Python. In Python, we can assign a function to a
variable. An ...read more Python Python-Functions Python function-programs Returning a
function from a function - Python Last Updated: 10 July 2024 Functions in Python are first-
class objects. First-class objects in a language are handled uniformly throughout. They may
be stored in data ...read more Python Python-Functions Python function-programs Explicitly
define datatype in a Python function Last Updated: 10 July 2024 Unlike other languages
Java, C++, etc. Python is a strongly, dynamically-typed language in which we don't have to
specify the data type of t ...read more Python Python-Functions Python function-programs
How to find the number of arguments in a Python function? Last Updated: 10 July 2024 In
this article, we are going to see how to count the number of arguments of a function in
Python. We will use the special syntax called *ar ...read more Python Python-Functions
Python function-programs How to check if a Python variable exists? Last Updated: 02 July
2024 Variables in Python can be defined locally or globally. There are two types of variables
first one is a local variable that is defined insid ...read more Python Python-Functions Python
function-programs Python - Get Function Signature Last Updated: 29 December 2020 Let’s
consider a scenario where you have written a very lengthy code and want to know the
function call details. So what you can do is scr ...read more Python Python-Functions Python
function-programs Python Decorators Python program to convert any base to decimal by
using int() method Last Updated: 13 July 2020 Given a number and its base, the task is to
convert the given number into its corresponding decimal number. The base of number can be
anythi ...read more Python Python Programs Python-Built-in-functions Python function-
programs Python Program to find volume, surface area and space diagonal of a cuboid Last
Updated: 14 August 2022 Given the length, base, and height of a cuboid. The task is to find
the Surface Area, Volume and space diagonal of the cuboid.Examples:Input...read more
image Python Python Programs Python function-programs Passing function as an argument
in Python Last Updated: 14 August 2024 A function can take multiple arguments, these
arguments can be objects, variables(of same or different data types) and functions. Python
fu ...read more Python Python function-programs Python | How to get function name ? Last
Updated: 06 April 2023 One of the most prominent styles of coding is following the OOP
paradigm. For this, nowadays, stress has been to write code with modularity, ...read more
Python Python function-programs Use of min() and max() in Python Last Updated: 06 June
2021 Prerequisite: min() max() in PythonLet's see some interesting facts about min() and
max() function. These functions are used to compute the ...read more Python Python
function-programs Python function-programs 25 posts Popular Articles Recent Articles
Regular Threads vs Daemon Threads in Python Last Updated: 09 October 2024 In Python,
threading allows multiple operations to run concurrently in a program. Threads are useful for
tasks like I/O-bound processes and ...read more Python Picked Python function-programs
Iterate over Two Lists with Different Lengths in Python Last Updated: 06 October 2024
Iterating over two lists of different lengths is a common scenario in Python. However, we
may face challenges when one list is shorter than ...read more Python Picked Python
function-programs Operator.length_hint() method in Python Last Updated: 27 August 2024
length_hint() method is part of the operator module, which contains a collection of functions
that correspond to standard operations and can ...read more Python Python function-programs
Transfer Kwargs Parameter to a Different Function in Python Last Updated: 22 February
2024 In Python, **kwargs is a special syntax that allows a function to accept any number of
keyword arguments. When transferring **kwargs paramet ...read more Python Python
Programs Picked Python function-programs Python splitfields() Method Last Updated: 17
April 2023 The splitfields() method is a user-defined method written in Python that splits any
kind of data into a list of fields using a delimiter. Th ...read more Python Python function-
programs What are the allowed characters in Python function names? Last Updated: 22 June
2021 The user-defined names that are given to Functions or variables are known as
Identifiers. It helps in differentiating one entity from anothe ...read more Python Python-
Functions Python function-programs Defining a Python function at runtime Last Updated: 29
December 2020 In Python,we can define a python function at runtime execute with the help
of FunctionType(). First we import types module then perform comp ...read more Python
Python-Functions Python function-programs Functions that accept variable length key value
pair as arguments Last Updated: 15 November 2022 To pass a variable-length key-value pair
as an argument to a function, Python provides a feature called **kwargs.kwargs stands for
Keyword a ...read more Python Python-Functions Python function-programs Find the average
of an unknown number of inputs in Python Last Updated: 07 April 2023 Prerequisites: *args
and **kwargs in PythonThe special syntax *args in function definitions in python is used to
pass a variable number of a ...read more Python Python-Functions Python function-programs
Python program to find number of local variables in a function Last Updated: 10 January
2019 Given a Python program, task is to find the number of local variables present in a
function.Examples:Input : a = 1 b = 2.1 str ...read more Python Python Programs Python
function-programs GIVE EASY PROGRAM WITH OUTPUT
ChatGPT said:
ChatGPT

Here are some easy Python function programs with user input and their output:

1. Python Program to Get List of Parameter Names from a Function


python
Copy code
import inspect def sample_function ( x, y, z=10 ): return x + y + z params =
inspect.signature(sample_function).parameters print ( "Parameter names:" ,
list (params.keys()))

Output:

less
Copy code
Parameter names : ['x', 'y', 'z']

2. Python Program to Print Multiple Arguments


python
Copy code
def print_multiple_args ( *args ): print (*args) user_input = input ( "Enter words separated
by spaces: " ).split() print_multiple_args(*user_input)

Example Run:
vbnet
Copy code
Enter words separated by spaces: Hello Python Functions Output: Hello Python
Functions

3. Python Program to Find the Power of a Number Using Recursion


python
Copy code
def power ( base, exp ): if exp == 0 : return 1 return base * power(base, exp - 1 ) base
= int ( input ( "Enter the base: " )) exp = int ( input ( "Enter the exponent: " ))
print ( f"{base}^{exp} =" , power(base, exp))

Example Run:

yaml
Copy code
Enter the base: 2 Enter the exponent: 3 Output: 2^3 = 8

4. Python Program to Sort Objects of a User-Defined Class


python
Copy code
class Book : def __init__ ( self, title, pages ): self.title = title self.pages = pages def
__repr__ ( self ): return f"{self.title} ({self.pages} pages)" books = [] n =
int ( input ( "Enter the number of books: " )) for _ in range (n): title = input ( "Enter book
title: " ) pages = int ( input ( "Enter number of pages: " )) books.append(Book(title, pages))
sorted_books = sorted (books, key= lambda book: book.pages) print ( "Books sorted by
number of pages:" , sorted_books)

Example Run:

yaml
Copy code
Enter the number of books: 2 Enter book title: Python Basics Enter number of pages:
300 Enter book title: Advanced Python Enter number of pages: 450 Output: Books
sorted by number of pages: [ Python Basics (300 pages) , Advanced Python (450
pages) ]

5. Python Program to Create and Display an Empty Class


python
Copy code
class EmptyClass : pass obj = EmptyClass() print ( "An instance of EmptyClass was
created:" , obj)

Output:

csharp
Copy code
An instance of EmptyClass was created: <__main__.EmptyClass object at
0x7f1234567890 >

Let me know if you'd like more examples or further explanations!

You said:
GIVE 20 FUNCTION EXERCISE WITH USERINPUT AND OUTPUT
ChatGPT said:
ChatGPT

Here are 20 Python function exercises that involve user input along with sample outputs:

1. Find the Square of a Number


python
Copy code
def square ( num ): return num ** 2 num = int ( input ( "Enter a number: " ))
print ( "Square of the number:" , square(num))

Output:

mathematica
Copy code
Enter a number: 4 Square of the number: 16

2. Calculate Factorial of a Number Using Recursion


python
Copy code
def factorial ( n ): if n == 0 : return 1 return n * factorial(n - 1 ) n = int ( input ( "Enter a
number: " )) print ( "Factorial of the number:" , factorial(n))

Output:

mathematica
Copy code
Enter a number: 5 Factorial of the number: 120

3. Check if a Number is Even or Odd


python
Copy code
def is_even ( num ): return "Even" if num % 2 == 0 else "Odd" num =
int ( input ( "Enter a number: " )) print ( "The number is:" , is_even(num))

Output:

yaml
Copy code
Enter a number: 7 The number is: Odd
4. Find the Greatest of Three Numbers
python
Copy code
def greatest ( a, b, c ): return max (a, b, c) a = int ( input ( "Enter first number: " )) b =
int ( input ( "Enter second number: " )) c = int ( input ( "Enter third number: " )) print ( "The
greatest number is:" , greatest(a, b, c))

Output:

yaml
Copy code
Enter first number: 12 Enter second number: 25 Enter third number: 18 The greatest
number is: 25

5. Reverse a String
python
Copy code
def reverse_string ( s ): return s[::- 1 ] s = input ( "Enter a string: " ) print ( "Reversed
string:" , reverse_string(s))

Output:

c
Copy code
Enter a string : hello Reversed string : olleh

6. Check if a String is a Palindrome


python
Copy code
def is_palindrome ( s ): return "Palindrome" if s == s[::- 1 ] else "Not a Palindrome" s =
input ( "Enter a string: " ) print ( "The string is:" , is_palindrome(s))

Output:

csharp
Copy code
Enter a string : racecar The string is : Palindrome

7. Find the Sum of Digits of a Number


python
Copy code
def sum_of_digits ( num ): return sum ( int (digit) for digit in str (num)) num =
int ( input ( "Enter a number: " )) print ( "Sum of digits:" , sum_of_digits(num))

Output:
yaml
Copy code
Enter a number: 1234 Sum of digits: 10

8. Check if a Number is Prime


python
Copy code
def is_prime ( n ): if n < 2 : return "Not Prime" for i in range ( 2 , int (n ** 0.5 ) + 1 ): if
n % i == 0 : return "Not Prime" return "Prime" n = int ( input ( "Enter a number: " ))
print ( "The number is:" , is_prime(n))

Output:

mathematica
Copy code
Enter a number: 11 The number is: Prime

9. Find the Fibonacci Sequence up to N Terms


python
Copy code
def fibonacci ( n ): sequence = [ 0 , 1 ] for i in range ( 2 , n): sequence.append(sequence[-
1 ] + sequence[- 2 ]) return sequence[:n] n = int ( input ( "Enter the number of terms: " ))
print ( "Fibonacci sequence:" , fibonacci(n))

Output:

mathematica
Copy code
Enter the number of terms: 5 Fibonacci sequence: [0, 1, 1, 2, 3]

10. Convert Celsius to Fahrenheit


python
Copy code
def celsius_to_fahrenheit ( celsius ): return (celsius * 9 / 5 ) + 32 celsius =
float ( input ( "Enter temperature in Celsius: " )) print ( "Temperature in Fahrenheit:" ,
celsius_to_fahrenheit(celsius))

Output:

yaml
Copy code
Enter temperature in Celsius: 0 Temperature in Fahrenheit: 32.0

11. Find the Area of a Circle


python
Copy code
import math def area_of_circle ( radius ): return math.pi * radius ** 2 radius =
float ( input ( "Enter the radius of the circle: " )) print ( "Area of the circle:" ,
area_of_circle(radius))

Output:

arduino
Copy code
Enter the radius of the circle: 5 Area of the circle: 78.53981633974483

12. Check if a Year is a Leap Year


python
Copy code
def is_leap_year ( year ): return "Leap Year" if (year % 4 == 0 and (year % 100 != 0
or year % 400 == 0 )) else "Not a Leap Year" year = int ( input ( "Enter a year: " ))
print ( "The year is:" , is_leap_year(year))

Output:

sql
Copy code
Enter a year : 2024 The year is : Leap Year

13. Count the Number of Vowels in a String


python
Copy code
def count_vowels ( s ): vowels = 'aeiouAEIOU' return sum ( 1 for char in s if char in
vowels) s = input ( "Enter a string: " ) print ( "Number of vowels:" , count_vowels(s))

Output:

mathematica
Copy code
Enter a string: hello world Number of vowels: 3

14. Find the GCD of Two Numbers


python
Copy code
import math def find_gcd ( a, b ): return math.gcd(a, b) a = int ( input ( "Enter first
number: " )) b = int ( input ( "Enter second number: " )) print ( "GCD of the numbers:" ,
find_gcd(a, b))

Output:

mathematica
Copy code
Enter first number: 48 Enter second number: 18 GCD of the numbers: 6
15. Generate a Multiplication Table for a Number
python
Copy code
def multiplication_table ( n ): for i in range ( 1 , 11 ): print ( f"{n} x {i} = {n * i}" ) n =
int ( input ( "Enter a number: " )) multiplication_table(n)

Output:

python
Copy code
Enter a number: 3 3 x 1 = 3 3 x 2 = 6 ... 3 x 10 = 30

16. Calculate Simple Interest


python
Copy code
def simple_interest ( principal, rate, time ): return (principal * rate * time) / 100 principal
= float ( input ( "Enter principal amount: " )) rate = float ( input ( "Enter rate of interest: " ))
time = float ( input ( "Enter time in years: " )) print ( "Simple Interest:" ,
simple_interest(principal, rate, time))

Output:

yaml
Copy code
Enter principal amount: 1000 Enter rate of interest: 5 Enter time in years: 2 Simple
Interest: 100.0

17. Check if Two Strings are Anagrams


python
Copy code
def are_anagrams ( str1, str2 ): return "Anagrams" if sorted (str1) == sorted (str2) else
"Not Anagrams" str1 = input ( "Enter first string: " ) str2 = input ( "Enter second string: " )
print ( "The strings are:" , are_anagrams(str1, str2))

Output:

sql
Copy code
Enter first string: listen Enter second string: silent The strings are : Anagrams

18. Find the LCM of Two Numbers


python
Copy code
import math def find_lcm ( a, b ): return abs (a * b) // math.gcd(a, b) a =
int ( input ( "Enter first number: " )) b = int ( input ( "Enter second number: " )) print ( "LCM
of the numbers:" , find_lcm(a, b))
Output:

mathematica
Copy code
Enter first number: 4 Enter second number: 6 LCM of the numbers: 12

19. Convert Binary to Decimal


python
Copy code
def binary_to_decimal ( binary_str ): return int (binary_str, 2 ) binary_str = input ( "Enter
a binary number: " ) print ( "Decimal value:" , binary_to_decimal(binary_str))

Output:

yaml
Copy code
Enter a binary number: 1010 Decimal value: 10

20. Print Prime Numbers in a Given Range


python
Copy code
def print_primes ( start, end ): for num in range (start, end + 1 ): if all (num % i != 0
for i in range ( 2 , int (num ** 0.5 ) + 1 )) and num > 1 : print (num, end= ' ' ) start =
int ( input ( "Enter start of range: " )) end = int ( input ( "Enter end of range: " ))
print ( "Prime numbers in the range:" ) print_primes(start, end)

Output:

sql
Copy code
Enter start of range : 10 Enter end of range : 20 Prime numbers in the range : 11 13
17 19

These exercises cover a variety of topics and help practice key concepts in Python. Let me
know if you need further details or explanations for any of these!

You said:
GIVE MORE PROGRAMS
ChatGPT said:
ChatGPT

Here are additional Python function exercises with user input and sample outputs:

21. Count the Number of Words in a Sentence


python
Copy code
def count_words ( sentence ): return len (sentence.split()) sentence = input ( "Enter a
sentence: " ) print ( "Number of words:" , count_words(sentence))

Output:

mathematica
Copy code
Enter a sentence: Python is an amazing programming language Number of words:
6

22. Convert Decimal to Binary, Octal, and Hexadecimal


python
Copy code
def convert_number ( num ): return bin (num), oct (num), hex (num) num =
int ( input ( "Enter a decimal number: " )) binary, octal, hexadecimal =
convert_number(num) print ( f"Binary: {binary}, Octal: {octal}, Hexadecimal:
{hexadecimal}" )

Output:

yaml
Copy code
Enter a decimal number: 15 Binary: 0b1111, Octal: 0o17, Hexadecimal: 0xf

23. Find the Maximum and Minimum in a List


python
Copy code
def find_min_max ( numbers ): return min (numbers), max (numbers) numbers =
list ( map ( int , input ( "Enter numbers separated by spaces: " ).split())) minimum,
maximum = find_min_max(numbers) print ( f"Minimum: {minimum}, Maximum:
{maximum}" )

Output:

yaml
Copy code
Enter numbers separated by spaces: 3 5 1 9 2 Minimum: 1, Maximum: 9

24. Check if a Number is an Armstrong Number


python
Copy code
def is_armstrong ( num ): return num == sum ( int (digit) ** len ( str (num)) for digit in
str (num)) num = int ( input ( "Enter a number: " )) print ( f"The number is {'an Armstrong
number' if is_armstrong(num) else 'not an Armstrong number'}" )

Output:
typescript
Copy code
Enter a number : 153 The number is an Armstrong number

25. Convert Kilometers to Miles


python
Copy code
def km_to_miles ( km ): return km * 0.621371 km = float ( input ( "Enter distance in
kilometers: " )) print ( "Distance in miles:" , km_to_miles(km))

Output:

yaml
Copy code
Enter distance in kilometers: 5 Distance in miles: 3.106855

26. Find the Second Largest Number in a List


python
Copy code
def second_largest ( numbers ): unique_numbers = list ( set (numbers))
unique_numbers.sort() return unique_numbers[- 2 ] if len (unique_numbers) > 1 else
None numbers = list ( map ( int , input ( "Enter numbers separated by spaces: " ).split()))
print ( "Second largest number:" , second_largest(numbers))

Output:

yaml
Copy code
Enter numbers separated by spaces: 5 3 9 1 9 Second largest number: 5

27. Check if a String is a Pangram


python
Copy code
import string def is_pangram ( s ): return
set (string.ascii_lowercase).issubset( set (s.lower())) s = input ( "Enter a sentence: " )
print ( "The sentence is a pangram" if is_pangram(s) else "The sentence is not a
pangram" )

Output:

less
Copy code
Enter a sentence : The quick brown fox jumps over the lazy dog The sentence is
a pangram

28. Find the Sum of All Even Numbers in a List


python
Copy code
def sum_even_numbers ( numbers ): return sum (num for num in numbers if num % 2
== 0 ) numbers = list ( map ( int , input ( "Enter numbers separated by spaces: " ).split()))
print ( "Sum of even numbers:" , sum_even_numbers(numbers))

Output:

mathematica
Copy code
Enter numbers separated by spaces: 2 3 4 5 6 Sum of even numbers: 12

29. Count the Frequency of Each Character in a String


python
Copy code
from collections import Counter def char_frequency ( s ): return Counter(s) s =
input ( "Enter a string: " ) frequency = char_frequency(s) print ( "Character frequency:" ,
frequency)

Output:

css
Copy code
Enter a string: hello Character frequency: Counter ({'l': 2 , 'h' : 1 , 'e' : 1 , 'o' : 1 })

30. Convert a List of Celsius Temperatures to Fahrenheit


python
Copy code
def convert_temperatures ( celsius_list ): return [((c * 9 / 5 ) + 32 ) for c in celsius_list]
celsius_list = list ( map ( float , input ( "Enter Celsius temperatures separated by spaces:
" ).split())) print ( "Temperatures in Fahrenheit:" , convert_temperatures(celsius_list))

Output:

yaml
Copy code
Enter Celsius temperatures separated by spaces: 0 25 30 100 Temperatures in
Fahrenheit: [ 32.0 , 77.0 , 86.0 , 212.0 ]

31. Find the Length of the Longest Word in a Sentence


python
Copy code
def longest_word_length ( sentence ): words = sentence.split() return max ( len (word)
for word in words) sentence = input ( "Enter a sentence: " ) print ( "Length of the longest
word:" , longest_word_length(sentence))

Output:
kotlin
Copy code
Enter a sentence: Python programming is fun Length of the longest word: 11

32. Print a Pattern Using Nested Loops


python
Copy code
def print_pattern ( n ): for i in range ( 1 , n + 1 ): print ( '*' * i) n = int ( input ( "Enter the
number of rows: " )) print_pattern(n)

Output:

markdown
Copy code
Enter the number of rows: 5 * ** *** ** ** **** *

33. Find the Mode of a List


python
Copy code
from statistics import mode def find_mode ( numbers ): return mode(numbers)
numbers = list ( map ( int , input ( "Enter numbers separated by spaces: " ).split()))
print ( "Mode of the list:" , find_mode(numbers))

Output:

mathematica
Copy code
Enter numbers separated by spaces: 1 2 2 3 3 3 4 4 Mode of the list: 3

34. Remove Duplicates from a List


python
Copy code
def remove_duplicates ( lst ): return list ( set (lst)) lst = list ( map ( int , input ( "Enter
numbers separated by spaces: " ).split())) print ( "List without duplicates:" ,
remove_duplicates(lst))

Output:

mathematica
Copy code
Enter numbers separated by spaces: 1 2 2 3 4 4 5 List without duplicates: [1, 2,
3, 4, 5]

35. Merge Two Lists Alternately


python
Copy code
def merge_alternate ( lst1, lst2 ): merged = [] for a, b in zip (lst1, lst2):
merged.extend([a, b]) merged.extend(lst1[ len (lst2):] or lst2[ len (lst1):]) return merged
lst1 = input ( "Enter elements of first list separated by spaces: " ).split() lst2 =
input ( "Enter elements of second list separated by spaces: " ).split() print ( "Merged list:" ,
merge_alternate(lst1, lst2))

Output:

less
Copy code
Enter elements of first list separated by spaces : a b c Enter elements of second
list separated by spaces : 1 2 3 4 Merged list : ['a', '1', 'b', '2', 'c', '3', '4']

36. Swap Two Variables Without a Temporary Variable


python
Copy code
def swap ( a, b ): a, b = b, a return a, b a = input ( "Enter the first value: " ) b =
input ( "Enter the second value: " ) a, b = swap(a, b) print ( "Swapped values:" , a, b)

Output:

sql
Copy code
Enter the first value : 5 Enter the second value : 10 Swapped values : 10 5

Let me know if you need more programs or specific variations!

You said:
GIVE MORE PROGRAMS
ChatGPT said:
ChatGPT

Here are additional Python function exercises with user input and sample outputs:

37. Calculate Factorial Using Recursion


python
Copy code
def factorial ( n ): if n == 0 or n == 1 : return 1 else : return n * factorial(n - 1 ) num
= int ( input ( "Enter a number to find its factorial: " )) print ( "Factorial:" , factorial(num))

Output:

css
Copy code
Enter a number to find its factorial: 5 Factorial: 120

38. Count Vowels in a String


python
Copy code
def count_vowels ( s ): vowels = "aeiouAEIOU" return sum ( 1 for char in s if char in
vowels) s = input ( "Enter a string: " ) print ( "Number of vowels:" , count_vowels(s))

Output:

mathematica
Copy code
Enter a string: Hello World Number of vowels: 3

39. Find the GCD of Two Numbers


python
Copy code
import math def find_gcd ( a, b ): return math.gcd(a, b) a = int ( input ( "Enter the first
number: " )) b = int ( input ( "Enter the second number: " )) print ( "GCD:" , find_gcd(a, b))

Output:

mathematica
Copy code
Enter the first number: 48 Enter the second number: 18 GCD: 6

40. Reverse a String


python
Copy code
def reverse_string ( s ): return s[::- 1 ] s = input ( "Enter a string: " ) print ( "Reversed
string:" , reverse_string(s))

Output:

c
Copy code
Enter a string : Python Reversed string : nohtyP

41. Check if Two Strings are Anagrams


python
Copy code
def are_anagrams ( s1, s2 ): return sorted (s1) == sorted (s2) s1 = input ( "Enter the first
string: " ) s2 = input ( "Enter the second string: " ) print ( "The strings are anagrams" if
are_anagrams(s1, s2) else "The strings are not anagrams" )

Output:

sql
Copy code
Enter the first string: listen Enter the second string: silent The strings are anagrams
42. Find the Fibonacci Series up to N Terms
python
Copy code
def fibonacci_series ( n ): series = [ 0 , 1 ] for i in range ( 2 , n): series.append(series[- 1 ]
+ series[- 2 ]) return series[:n] n = int ( input ( "Enter the number of terms: " ))
print ( "Fibonacci series:" , fibonacci_series(n))

Output:

mathematica
Copy code
Enter the number of terms: 7 Fibonacci series: [0, 1, 1, 2, 3, 5, 8]

43. Check if a Number is Prime


python
Copy code
def is_prime ( n ): if n <= 1 : return False for i in range ( 2 , int (n** 0.5 ) + 1 ): if n % i
== 0 : return False return True num = int ( input ( "Enter a number: " )) print ( "The
number is prime" if is_prime(num) else "The number is not prime" )

Output:

csharp
Copy code
Enter a number: 13 The number is prime

44. Sum of Digits of a Number


python
Copy code
def sum_of_digits ( n ): return sum ( int (digit) for digit in str (n)) num =
int ( input ( "Enter a number: " )) print ( "Sum of digits:" , sum_of_digits(num))

Output:

yaml
Copy code
Enter a number: 1234 Sum of digits: 10

45. Find the HCF (Highest Common Factor) of Two Numbers


python
Copy code
def hcf ( x, y ): while (y): x, y = y, x % y return x x = int ( input ( "Enter the first number:
" )) y = int ( input ( "Enter the second number: " )) print ( "HCF:" , hcf(x, y))

Output:
yaml
Copy code
Enter the first number: 60 Enter the second number: 48 HCF: 12

46. Convert Time from 24-Hour to 12-Hour Format


python
Copy code
def convert_to_12_hour ( time_24 ): hour, minute = map ( int , time_24.split( ':' )) suffix =
"AM" if hour < 12 else "PM" hour = hour % 12 if hour != 12 else 12 return
f"{hour}:{minute:02d} {suffix}" time_24 = input ( "Enter time in 24-hour format
(HH:MM): " ) print ( "12-hour format:" , convert_to_12_hour(time_24))

Output:

lua
Copy code
Enter time in 24 -hour format (HH:MM): 14 : 30 12 -hour format : 2 : 30 PM

47. Convert Temperature from Fahrenheit to Celsius


python
Copy code
def fahrenheit_to_celsius ( f ): return (f - 32 ) * 5 / 9 f = float ( input ( "Enter temperature
in Fahrenheit: " )) print ( "Temperature in Celsius:" , fahrenheit_to_celsius(f))

Output:

yaml
Copy code
Enter temperature in Fahrenheit: 98.6 Temperature in Celsius: 37.0

48. Find the Median of a List


python
Copy code
def find_median ( lst ): lst.sort() n = len (lst) if n % 2 == 0 : return (lst[n// 2 - 1 ] +
lst[n// 2 ]) / 2 else : return lst[n// 2 ] lst = list ( map ( int , input ( "Enter numbers separated
by spaces: " ).split())) print ( "Median:" , find_median(lst))

Output:

mathematica
Copy code
Enter numbers separated by spaces: 1 3 5 7 9 Median: 5

49. Generate a Random Password


python
Copy code
import random import string def generate_password ( length ): characters =
string.ascii_letters + string.digits + string.punctuation return
'' .join(random.choice(characters) for _ in range (length)) length = int ( input ( "Enter the
length of the password: " )) print ( "Generated password:" , generate_password(length))

Output:

perl
Copy code
Enter the length of the password: 12 Generated password: A$w4pQ #1bV9L

50. Capitalize Each Word in a Sentence


python
Copy code
def capitalize_words ( sentence ): return sentence.title() sentence = input ( "Enter a
sentence: " ) print ( "Capitalized sentence:" , capitalize_words(sentence))

Output:

kotlin
Copy code
Enter a sentence: python programming is fun Capitalized sentence: Python
Programming Is Fun

Let me know if you need more programs or different types of exercises!

2/2
ChatGPT can make mistakes. Check important info.
?
`1

You might also like