In this python function program, we will create a function to check whether a combination of two numbers has a sum of 10 from the given list.
What is Function?
It is a block of code that executes when it is called.
To create a function use def keyword.
Steps to solve the program
- Create a function check_sum.
- Use the def keyword to define the function.
- Pass two parameters i.e. list and the sum number to the function.
- Use a for loop with the range function to iterate over the elements in the list.
- Use a nested for loop with the range function to iterate over the next numbers from the list i.e first loop un the first iteration will use the first element and with the help of the nested loop we will iterate over the number the numbers from the second element.
- Now check whether the sum of 1st element and any others elements from the nested loop is equal to 10.
- If yes then return True else return False.
- Pass the list and the sum number to the function while calling the function.
def check_sum(nums, k):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] + nums[j] == k:
return True
return False
print(check_sum([2, 5, 6, 4, 7, 3, 8, 9, 1], 10))
Output :
True
Related Articles
Python function program to get unique values from the given list.
Python function program to get the duplicate characters from the string.
Python function program to get the square of all values in the given dictionary.
Python function program to create dictionary output from the given string.
Python function program to print a list of prime numbers from 1 to 100
Python function program to get a list of odd numbers from 1 to 100.