Python Functions: A Complete Notes
1. Defining and Calling Functions
A function in Python is defined using the def keyword. Functions help organize code
into reusable blocks.
Example:
def greet(name): # Defining the function
print(f"Hello, {name}!")
# Calling the function
greet("Alice")
2. Parameters and Return Values
Functions can take parameters (inputs) and return values (outputs).
Example with Parameters and Return Value:
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
3. Recursion in Python
Recursion is when a function calls itself to solve a problem.
Example: Factorial using Recursion
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Example: Fibonacci using Recursion
def fibonacci(n):
if n <= 0:
return "Invalid Input"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)
print(fibonacci(6)) # Output: 5
Key Takeaways:
Functions improve code reusability and readability.
Parameters allow passing values to functions.
Return values allow functions to output results.
Recursion is useful for problems like factorial, Fibonacci, and tree traversal.
1. A circular prime is a prime number that remains prime under all rotations of
its digits. For example, 197 is a circular prime because all its rotations (197, 971,
719) are prime.
Output:
197
197 is a Circular Prime
Code:
def is_prime(n):
#Check if a number is prime
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def get_rotations(n):
#Generate all rotations of a number
str_n = str(n)
return [int(str_n[i:] + str_n[:i]) for i in range(len(str_n))]
def is_circular_prime(n):
#Check if a number is a circular prime
return all(is_prime(rot) for rot in get_rotations(n))
num = 197
if is_circular_prime(num):
print(f"{num} is a Circular Prime")
else:
print(f"{num} is NOT a Circular Prime")
2. Python program that takes a single input from the user (withdrawal amounts
separated by spaces), converts it into a list, and checks if each withdrawal is
possible while updating the ATM balance.
Output:
Enter withdrawal amounts separated by spaces: 200 500 100 400
Enter initial ATM balance: 1000
Withdrawal of 200 is successful. Remaining balance: 800
Withdrawal of 500 is successful. Remaining balance: 300
Withdrawal of 100 is successful. Remaining balance: 200
Withdrawal of 400 is not possible. Insufficient balance.
Code:
def atm_withdrawal(withdrawals, atm_balance):
for amount in withdrawals:
if amount > atm_balance:
print(f"Withdrawal of {amount} is not possible. Insufficient balance.")
else:
atm_balance -= amount
print(f"Withdrawal of {amount} is successful. Remaining balance:
{atm_balance}")
# Get user input as a single string
user_input = input("Enter withdrawal amounts separated by spaces: ")
withdrawal_list = list(map(int, user_input.split()))
# Get ATM balance
atm_balance = int(input("Enter initial ATM balance: "))
# Process withdrawals
atm_withdrawal(withdrawal_list, atm_balance)
3. Python program that takes user input for the chocolate prices and the initial
amount of money, then calculates the leftover amount after buying two
chocolates with the minimum sum.
Output:
Enter chocolate prices separated by spaces: 4 3 7 5
Enter your initial amount of money: 10
3
Code:
def min_leftover_money(prices, money):
[Link]() # Sort the prices in ascending order
min_sum = prices[0] + prices[1] # Take the two cheapest chocolates
if min_sum <= money:
return money - min_sum # Return the leftover money
else:
return money # If not possible, return the original money
prices = list(map(int, input("Enter chocolate prices separated by spaces: ").split()))
money = int(input("Enter your initial amount of money: "))
# Calling the function and printing the result
print(min_leftover_money(prices, money))
4. Python program to calculate combinations (nCrnCrnCr) by taking input from
the user:Combinations: nCr = n! / (r! * (n – r)!)
Output:
Enter the value of n: 5
Enter the value of r: 2
nCr (5C2) = 10
Code:
Way 1:
import math
# Function to calculate nCr
def combination(n, r):
return [Link](n, r) # [Link] is available in Python 3.8+
# Taking input from the user
n = int(input("Enter the value of n: "))
r = int(input("Enter the value of r: "))
# Checking valid input
if r > n or n < 0 or r < 0:
print("Invalid input! r should be less than or equal to n, and both should be non-
negative.")
else:
print(f"nCr ({n}C{r}) = {combination(n, r)}")
Way 2:
# Function to calculate factorial
def factorial(num):
if num == 0 or num == 1:
return 1
result = 1
for i in range(2, num + 1):
result *= i
return result
# Function to calculate nCr
def combination(n, r):
return factorial(n) // (factorial(r) * factorial(n - r))
n = int(input("Enter the value of n: "))
r = int(input("Enter the value of r: "))
# Checking valid input
if r > n or n < 0 or r < 0:
print("Invalid input! r should be less than or equal to n, and both should be non-
negative.")
else:
print(f"nCr ({n}C{r}) = {combination(n, r)}")
5. Maximum digit sum of two combinations.
Output:
Input: 3 ([Link])
867
Output : 12
(8,6) (8,7) (6,7) => 8*6=48, 8*7= 56, 6*7 = 42
Digit sum the answers : 4+8 =12, 5+6 = 11, 4+2=6;
max = 12
Code:
# Function to calculate the sum of digits of a number
def digit_sum(n):
return sum(int(digit) for digit in str(n))
n = int(input()) # Number of inputs
arr = list(map(int, input().split())) # List of numbers
# Generate all 2-combinations manually and compute the maximum digit sum
max_digit_sum = 0
for i in range(n):
for j in range(i + 1, n):
product = arr[i] * arr[j]
max_digit_sum = max(max_digit_sum, digit_sum(product))
print(max_digit_sum)
6. Python program that generates a Fibonacci series iteratively based on user
input.
Output:
Enter the number of terms: 7
Fibonacci Series: [0, 1, 1, 2, 3, 5, 8]
Code:
def fibonacci_series(n):
fib_list = [0, 1]
for i in range(2, n):
fib_list.append(fib_list[-1] + fib_list[-2])
return fib_list[:n]
num = int(input("Enter the number of terms: "))
if num <= 0:
print("Please enter a positive integer.")
else:
print("Fibonacci Series:", fibonacci_series(num))
7. Generate Tuples of Numbers and Their Squares in a Range and store them in
a list.
Output:
Input 1: 2 4 Output 1: [(2,4),(3,9),(4,16)]
Input 2: 101 99 Output 2: Invalid Range (Explanation:First number greater than
second so invalid )
Input 3: 101 101 Output 3: Equal range
Code:
def generate_square_tuples(start, end):
if start > end:
return "Invalid Range"
elif start == end:
return "Equal range"
else:
return [(num, num**2) for num in range(start, end + 1)]
start, end = map(int, input().split())
print(generate_square_tuples(start, end))
8. Python function to print all integers from NNN to -1-1-1
Output:
-5
-4 -3 -2 -1
Code:
def print_integers_to_minus_one(N):
for i in range(N + 1, 0):
print(i, end=" ")
N = int(input("Enter a number: "))
print_integers_to_minus_one(N)
9. Python to count the number of uppercase and lowercase letters in a string.
Output:
"Hello World!"
Uppercase letters: 2, Lowercase letters: 8
Code:
def count_case(s):
upper_count = sum(1 for char in s if [Link]())
lower_count = sum(1 for char in s if [Link]())
return upper_count, lower_count
text = "Hello World!"
upper, lower = count_case(text)
print(f"Uppercase letters: {upper}, Lowercase letters: {lower}")
10. Given an array of strings words, return the words that can be typed using
letters of the alphabet on only one row of American keyboard like the image
below.
Note that the strings are case-insensitive, both lowercased and uppercased of the
same letter are treated as if they are at the same row.
In the American keyboard:
the first row consists of the characters "qwertyuiop",
the second row consists of the characters "asdfghjkl",
and the third row consists of the characters "zxcvbnm".
Output:
["Hello", "Alaska", "Dad", "Peace"]
['Alaska', 'Dad']
Code:
from typing import List
def findWords(words: List[str]) :
row1 = set("qwertyuiop")
row2 = set("asdfghjkl")
row3 = set("zxcvbnm")
result = []
for word in words:
lower_word = set([Link]()) # Convert word to lowercase and get unique
letters
if lower_word <= row1 or lower_word <= row2 or lower_word <= row3:
[Link](word)
return result
words = ["Hello", "Alaska", "Dad", "Peace"]
print(words)
print(findWords(words))
11. Given a string array words, return the maximum value of length(word[i]) *
length(word[j]) where the two words do not share common letters. If no such two
words exist, return 0.
Output:
Enter words separated by spaces: abcw baz foo bar xtfn apt
Maximum product of lengths of two words without common letters: 16
Code:
def max_product(words):
word_sets = [{char for char in word} for word in words]
max_product = 0
for i in range(len(words)):
for j in range(i + 1, len(words)):
if word_sets[i].isdisjoint(word_sets[j]): # No common letters
max_product = max(max_product, len(words[i]) * len(words[j]))
return max_product
words = input("Enter words separated by spaces: ").split()
result = max_product(words)
print("Maximum product of lengths of two words without common letters:", result)
12. Convert a non-negative integer num to its English words representation.
Output:
Enter a non-negative integer: 1234567
One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven
Code:
def numberToWords(num: int) -> str:
if num == 0:
return "Zero"
below_20 = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
"Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen",
"Seventeen", "Eighteen", "Nineteen"]
tens = ["", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty",
"Ninety"]
thousands = ["", "Thousand", "Million", "Billion"]
def helper(n):
if n == 0:
return ""
elif n < 20:
return below_20[n] + " "
elif n < 100:
return tens[n // 10] + " " + helper(n % 10)
else:
return below_20[n // 100] + " Hundred " + helper(n % 100)
res = ""
i=0
while num > 0:
if num % 1000 != 0:
res = helper(num % 1000) + thousands[i] + " " + res
num //= 1000
i += 1
return [Link]()
num = int(input("Enter a non-negative integer: "))
print(numberToWords(num))
13. Decimal to Binary with 7 presition
Output:
Enter a decimal number: 5
Binary (7-bit precision): 0000101
Code:
def decimal_to_binary_7bit(n):
# Convert decimal to binary and remove '0b' prefix
binary = bin(n)[2:]
# Ensure it's exactly 7 bits long (pad with leading zeros if necessary)
return [Link](7)
decimal_number = int(input("Enter a decimal number: "))
binary_result = decimal_to_binary_7bit(decimal_number)
print(f"Binary (7-bit precision): {binary_result}")
14. Given three integer arrays nums1, nums2, and nums3, return a distinct array
containing all the values that are present in at least two out of the three arrays.
You may return the values in any order.
Output:
Enter elements of first list separated by space: 1 2 3
Enter elements of second list separated by space: 4 2 5
Enter elements of third list separated by space: 3 6 7
Numbers appearing in at least two lists: [2, 3]
Code:
def two_out_of_three(nums1, nums2, nums3):
from collections import Counter
# Convert lists to sets to remove duplicates within each list
set1, set2, set3 = set(nums1), set(nums2), set(nums3)
# Count occurrences in how many sets each number appears
freq = Counter(set1) + Counter(set2) + Counter(set3)
# Select numbers that appear in at least two sets
result = [num for num, count in [Link]() if count >= 2]
return result
nums1 = list(map(int, input("Enter elements of first list separated by space: ").split()))
nums2 = list(map(int, input("Enter elements of second list separated by space:
").split()))
nums3 = list(map(int, input("Enter elements of third list separated by space: ").split()))
# Calling the function and printing the result
print("Numbers appearing in at least two lists:", two_out_of_three(nums1, nums2,
nums3))
15. print the longest word
Output:
'programming python'
programming
Code:
title ='programming python'
longest_word = max([Link](), key=len)
print(f"'{title}'")
print(longest_word)
16. consecutive consonace like Consecutive Characters
Output:
Enter a string: beautifulstrongsky
Longest consecutive consonants: 'ngsk' with length 4
Code:
def longest_consecutive_consonants(s):
vowels = {'a', 'e', 'i', 'o', 'u'}
max_len = 0
current_len = 0
max_substr = ""
current_substr = ""
for char in [Link](): # Convert to lowercase for uniformity
if [Link]() and char not in vowels: # Check if consonant
current_len += 1
current_substr += char
if current_len > max_len:
max_len = current_len
max_substr = current_substr
else:
current_len = 0
current_substr = ""
return max_substr, max_len
input_string = input("Enter a string: ")
result, length = longest_consecutive_consonants(input_string)
print(f"Longest consecutive consonants: '{result}' with length {length}")
17. Count of palindromic sub-strings from a given string
Output:
Enter a string: ababa
Count of palindromic substrings: 9
Code:
def is_palindrome(s):
return s == s[::-1]
def count_palindromic_substrings(s):
count = 0
n = len(s)
for i in range(n):
for j in range(i, n):
if is_palindrome(s[i:j+1]):
count += 1
return count
string = input("Enter a string: ")
result = count_palindromic_substrings(string)
print(f"Count of palindromic substrings: {result}")
18. Give me python code for getting the multiple of this numbers which in string
format.
Output:
input1:1,2,3,4,5(string) output:120
input2:0.5,1.5,2,3.5(string) output:5.25
Code:
from math import prod
def multiply_numbers(input_str):
# Convert string to list of numbers
numbers = list(map(float, input_str.split(',')))
# Calculate product
return prod(numbers)
input1 = "1,2,3,4,5"
input2 = "0.5,1.5,2,3.5"
print(multiply_numbers(input1))
print(multiply_numbers(input2))
19. Python program to calculate the total poisoned duration based on a given set
of time instances when a stone is thrown and a fixed duration for which the
poison remains active.
Output:
Enter stone times (space-separated): 1 4
Enter duration: 4
Total poisoned duration: 7
Code:
def poisoned_duration(stones, duration):
if not stones:
return 0
total_duration = 0
for i in range(len(stones) - 1):
total_duration += min(stones[i + 1] - stones[i], duration)
# Add the last stone's duration
total_duration += duration
return total_duration
stones = list(map(int, input("Enter stone times (space-separated): ").split()))
duration = int(input("Enter duration: "))
# Calculating poisoned duration
result = poisoned_duration(stones, duration)
print("Total poisoned duration:", result)
20. Python program to process the input list and classify the numbers into prime,
composite, and negative numbers sorted in order.
Output:
2 3 4 5 -3 -2 -7
[2,3,5]
[4]
[-2,-3,-7]
Code:
def is_prime(n):
if n<2:
return False
for i in range(2,int(n**0.5)+1):
if n%i==0:
return False
return True
def classify(num):
neg= []
pri= []
com= []
for n in num:
if n<0:
[Link](n)
elif is_prime(n):
[Link](n)
elif n>1:
[Link](n)
print(pri)
print(com)
print(sorted(neg))
num=list(map(int,input().split()))
classify(num)
21. calculate and print the area of a circle, triangle, and rectangle
Output:
Enter the radius of the circle: 4
Area of Circle: 50.27
Enter the base of the triangle: 5
Enter the height of the triangle: 10
Area of Triangle: 25.00
Enter the length of the rectangle: 7
Enter the width of the rectangle: 3
Area of Rectangle: 21.00
Code:
import math
def area_of_circle(radius):
return [Link] * radius ** 2
def area_of_triangle(base, height):
return 0.5 * base * height
def area_of_rectangle(length, width):
return length * width
radius = float(input("Enter the radius of the circle: "))
print(f"Area of Circle: {area_of_circle(radius):.2f}")
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
print(f"Area of Triangle: {area_of_triangle(base, height):.2f}")
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
print(f"Area of Rectangle: {area_of_rectangle(length, width):.2f}")
22. Given an integer array nums where nums[i] is either a positive integer or -1.
We need to find for each -1 the respective positive integer, which we call the last
visited integer.
To achieve this goal, let's define two empty arrays: seen and ans.
Start iterating from the beginning of the array nums.
If a positive integer is encountered, prepend it to the front of seen.
If -1 is encountered, let k be the number of consecutive -1s seen so far
(including the current -1),
If k is less than or equal to the length of seen, append the k-th
element of seen to ans.
If k is strictly greater than the length of seen, append -1 to ans.
Return the array ans.
Output:
Enter the numbers separated by space: 4 3 -1 -1 5 -1 -1 -1
[3, 4, 3, 5, 4]
Code:
def last_visited_integers(nums):
seen = []
ans = []
k = 0 # Count of consecutive -1s
for num in nums:
if num == -1:
k += 1
if k <= len(seen):
[Link](seen[k - 1]) # k-th element in seen
else:
[Link](-1)
else:
[Link](0, num) # Prepend to seen
k = 0 # Reset k since we encountered a positive integer
return ans
nums = list(map(int, input("Enter the numbers separated by space: ").split()))
print(last_visited_integers(nums))
23. if the word contains more than 3 consequent consonants print no else yes
Output:
Enter a word: banana
yes
Enter a word: strength
No
Code:
def three_consecutive_consonants(word):
vowels = "aeiouAEIOU"
count = 0
for char in word:
if char not in vowels: # It's a consonant
count += 1
if count > 3:
return "no"
else:
count = 0 # Reset count if a vowel is found
return "yes"
word = input("Enter a word: ")
print(three_consecutive_consonants(word))
24. MATRIX MULTIPLICATION
Output:
Enter the number of rows for Matrix A: 2
Enter the number of columns for Matrix A: 3
Enter the number of rows for Matrix B: 3
Enter the number of columns for Matrix B: 2
Enter the elements of A matrix row-wise:
123
456
Enter the elements of B matrix row-wise:
78
9 10
11 12
Resultant Matrix:
58 64
139 154
Code:
def get_matrix(rows, cols, name):
print(f"Enter the elements of {name} matrix row-wise:")
matrix = []
for i in range(rows):
row = list(map(int, input().split()))
if len(row) != cols:
print(f"Error: Please enter exactly {cols} values per row.")
return get_matrix(rows, cols, name)
[Link](row)
return matrix
def multiply_matrices(A, B, r1, c1, c2):
result = [[0] * c2 for _ in range(r1)]
for i in range(r1):
for j in range(c2):
for k in range(c1):
result[i][j] += A[i][k] * B[k][j]
return result
r1 = int(input("Enter the number of rows for Matrix A: "))
c1 = int(input("Enter the number of columns for Matrix A: "))
r2 = int(input("Enter the number of rows for Matrix B: "))
c2 = int(input("Enter the number of columns for Matrix B: "))
if c1 != r2:
print("Matrix multiplication is not possible (columns of A must match rows of B).")
else:
# Input matrices
A = get_matrix(r1, c1, "A")
B = get_matrix(r2, c2, "B")
# Multiply matrices
result = multiply_matrices(A, B, r1, c1, c2)
# Display result
print("Resultant Matrix:")
for row in result:
print(" ".join(map(str, row)))
25. MINIMUM ELEMENT SHARED BY BOTH ARRAYS
Output:
Enter elements of first array separated by space: 1 2 3 4 5
Enter elements of second array separated by space: 6 2 3 7 8
Minimum common element: 2
Code:
def min_common_element(arr1, arr2):
# Convert both lists to sets for quick lookup
common_elements = set(arr1) & set(arr2)
# If there are common elements, return the minimum, else return -1
return min(common_elements) if common_elements else -1
arr1 = list(map(int, input("Enter elements of first array separated by space: ").split()))
arr2 = list(map(int, input("Enter elements of second array separated by space:
").split()))
# Finding the minimum common element
result = min_common_element(arr1, arr2)
print("Minimum common element:", result)
26. You have three types of cups that need to be filled with water. The cups
require a specific number of seconds to be filled:
amount[0] cups of the first type.
amount[1] cups of the second type.
amount[2] cups of the third type.
Each second, you can simultaneously fill up to two different types of cups. You
need to determine the minimum amount of time required to fill all the cups.
Output:
Enter the amounts of cold, warm, and hot water (space-separated): 1 4 2
Minimum seconds needed: 4
Code:
Way 1
from typing import List
def fillCups(amount: List[int]) :
[Link]()
if amount[2] >= amount[0] + amount[1]:
return amount[2]
return sum(amount) // 2 + sum(amount) % 2
user_input = list(map(int, input("Enter the amounts of cold, warm, and hot water
(space-separated): ").split()))
# Ensure user gave exactly 3 values
if len(user_input) != 3:
print("Please enter exactly 3 integers.")
else:
print("Minimum seconds needed:", fillCups(user_input))
Way 2
def fillCups(amount):
return max(max(amount), (sum(amount) + 1) // 2)
user_input = input("Enter the amounts of water for cold, warm, and hot(space-
separated) : ")
amount = list(map(int, user_input.strip().split()))
# Call the function and print result
print(fillCups(amount))
27. Quadratic Equation Solver
Output:
Enter coefficient a: 2
Enter coefficient b: 3
Enter coefficient c: 4
Two complex roots: -0.75 + 1.1989578808281798i, -0.75 - 1.1989578808281798i
Code:
import math
# Function to solve the quadratic equation
def solve_quadratic(a, b, c):
# Calculate the discriminant
d = b**2 - 4*a*c
if d > 0:
root1 = (-b + [Link](d)) / (2*a)
root2 = (-b - [Link](d)) / (2*a)
return f"Two real and distinct roots: {root1}, {root2}"
elif d == 0:
root = -b / (2*a)
return f"One real and repeated root: {root}"
else:
real_part = -b / (2*a)
imag_part = [Link](abs(d)) / (2*a)
return f"Two complex roots: {real_part} + {imag_part}i, {real_part} -
{imag_part}i"
# Taking inputs
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
# Handling the case when a is zero
if a == 0:
print("Not a quadratic equation.")
else:
print(solve_quadratic(a, b, c))
28. prime number in range
Output:
Enter the start of the range: 5
Enter the end of the range: 20
Prime numbers between 5 and 20: [5, 7, 11, 13, 17, 19]
Code:
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def prime_numbers_in_range(start, end):
primes = [num for num in range(start, end + 1) if is_prime(num)]
return primes
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))
# Finding and displaying prime numbers in range
print(f"Prime numbers between {start} and {end}: {prime_numbers_in_range(start,
end)}")
29. permutation in string
Output:
Enter a string: abc
abc
acb
bac
bca
cab
cba
Code:
Way 1
from itertools import permutations
# Function to get all permutations of a string
def get_permutations(s):
return [''.join(p) for p in permutations(s)]
input_str = input("Enter a string: ")
# Generating and printing permutations
permuted_strings = get_permutations(input_str)
for perm in permuted_strings:
print(perm)
Way 2
# Function to generate permutations
def permute(s, left, right):
if left == right:
print("".join(s)) # Print the permutation
else:
for i in range(left, right + 1):
s[left], s[i] = s[i], s[left] # Swap
permute(s, left + 1, right) # Recur
s[left], s[i] = s[i], s[left] # Backtrack
input_str = input("Enter a string: ")
# Converting string to a list for swapping
char_list = list(input_str)
# Generating and printing permutations
permute(char_list, 0, len(char_list) - 1)
30. Count substring occurrences in a string
Output:
The substring "hello" appears 3 times.
Code:
def count_substring_occurrences(string, substring):
return [Link](substring)
main_string = "hello hello world hello"
sub_string = "hello"
count = count_substring_occurrences(main_string, sub_string)
print(f'The substring "{sub_string}" appears {count} times.')
31. Remove consecutive repeated elements
Output:
aaabbcddddee
abcde
Code:
def dup(s):
if not s:
return "NO dup"
dupli = False
result = [s[0]]
for i in range(1, len(s)):
if s[i] != s[i - 1]:
[Link](s[i])
else:
dupli = True
out = "".join(result)
return out if dupli else "NO dup"
s = input("Enter a string: ")
print(dup(s))
[Link] the characters in the string with other characters or
symbols
Output:
Hello, World
#3110, W0r1$!
Code:
def replace_chars(text, replacements):
for old_char, new_char in [Link]():
text = [Link](old_char, new_char)
return text
original_text = "Hello, World!"
replacements = {'H': '#', 'e': '3', 'o': '0', 'l': '1', 'd': '$'}
new_text = replace_chars(original_text, replacements)
print(new_text)
[Link] the only digit
Output:
input 1:123hii output :no
input2: 123456 output :yes
Code:
def contains_only_digits(s):
if [Link]():
return "yes"
else:
return "no"
input1 = input("Enter a string: ")
print("Output:", contains_only_digits(input1))
34. Count Words with a Given Prefix in a Sentence
Output:
input : pay attend the
class at periodic time (sentence) at(prefix) output : 2
Code:
def count_words_with_prefix(sentence, prefix):
words = [Link]()
count = sum(1 for word in words if [Link](prefix))
return count
sentence = input("Enter a sentence: ")
prefix = input("Enter a prefix: ")
print(count_words_with_prefix(sentence, prefix))
[Link] a Python program that takes n lines of input and capitalizes
the first letter of each word in every line. Print the modified lines.
Output:
Enter number of lines: 2
hello world
welcome to python
Hello World
Welcome To Python
Code:
def capitalize_first_letter():
n = int(input("Enter number of lines: "))
lines = [input() for _ in range(n)]
for line in lines:
print([Link]())
capitalize_first_letter()