Functions Practice

I am posting some problem on functions for practice. I hope you find it useful. the function format is also mentioned on the side. reply with the answer for 4th question for now. Rest can be used for further practice or discussion among your classes to understand and learn better.

  1. Write a function to see if numbers of two integers add up to the same number. function_name(number1, number2). example : individual numbers of number 321 and 123 add up to 6.
  2. Write a function to return all possible combinations of two numbers in a list that adds up to a target number.
    function_name(list, target)
  3. write a function to convert weights from kilogram to pound and viceversa. function_name(weight). ask for user input and convert accordingly.
  4. write a function to return number of words in a sentence. function_name(‘string’)
4 Likes

def add_num(n1,n2):
n1_sum=sum([int(x) for x in str(n1)])
n2_sum=sum([int(x) for x in str(n2)])
if n1_sum==n2_sum:
return True,n1_sum,n1,n2
else:
print(“These are not the numbers!”)
return False,n1_sum,n1,n2
n1=input(“Enter num1:”)
n2=input(“Enter num2:”)
X=add_num(n1,n2)
if X[0]==True:
print(“sum of {} and sum of {} is equal to {}”.format(X[2],X[3],X[1]))

def list_num(list1,num):
list2=[]
for i in range(len(list1)):
a=list1[i]
for b in list1:
if a+b==num and a!=b:
list2.append((a,b))
return list2
list1=[2,3,4,6,5]
num=7
print(list_num(list1,num))

3 Likes

#Kg to Pound and viceversa
def kg_po(weight):
return weight*2.2046226218

def po_kg(weight):
return weight/2.2046226218

x=int(input(‘kg to pound(1) or pound to kg(2)’))
if x==1:
weight=float(input(‘Enter weight in kg’))
print(kg_po(weight),‘pounds’)
if x==2:
weight=float(input(‘Enter weight in pound’))
print(po_kg(weight),‘kg’)

3 Likes

#write a function to return number of words in a sentence. function_name(‘string’)
def string(s1):
lis=s1.split()
return len(lis)
s1=input(“Enter a string.\n”)
print(string(s1))

4 Likes

Good going @cmsathwik44 . Keep it up

1 Like

def eqsum(a,b):
d={}
d[“a”]=str(a)
d[“b”]=str(b)
l=[]
for key,val in d.items():
c=0
for i in range(len(val)):
c+=int(val[i])
l.append(int(c))
if l[0]==l[1]:
print(“Numbers have equal sum”)
else:
print(‘Numers do not have equal sum’)

def target(n,l1):
l2=[]
for i in l1:
for j in l1:
if i+j==n and i!=j:
l2.append((i,j))
print(l2)

def wght(w):
print(“Press k for lb to kg\nPress p for kg to lb”)
a=input(“”)
if a==“k” or a==“K”:
print(“lb to kg”)
v=0.453592w
print(w,“lb =”,v," kg")
elif a==‘p’ or a==‘P’:
print(‘kg to lb’)
v=2.20462
w
print(w,“kg =”,v," lb")
else:
print(‘please enter a valid input’)

def wrdcount(s1):
a=list(s1.split())
print("Number of words={} ".format(len(a)))

2 Likes

keep practicing @maulik.workstuff

1 Like