122k views
0 votes
6. Larger Than n In a program, write a function that accepts two arguments: a list, and a number n. Assume that the list contains numbers. The function should display all of the numbers in the list that are greater than the number n.

2 Answers

4 votes

Final answer:

To display numbers in a list that are greater than a given number, you can write a program using a loop and an if statement.

Step-by-step explanation:

To write a program that displays all the numbers in a list that are greater than a given number, you can use a loop to iterate through each element in the list. Inside the loop, you can use an if statement to check if the current element is greater than the given number. If it is, you can print or store the element.

Example:

def larger_than_n(numbers, n):
for num in numbers:
if num > n:
print(num)
# Example usage
numbers = [1, 2, 3, 4, 5]
n = 3
display_larger_numbers(numbers, n)

User Jaber Al Nahian
by
3.8k points
3 votes

Answer:

The solution code is written in Python

  1. def largerThanN(myList, n):
  2. output = ""
  3. for x in myList:
  4. if(x > n):
  5. output += str(x) + " "
  6. print(output)
  7. l = [5, 12, 11, 4, 56, 32]
  8. n = 15
  9. largerThanN(l, n)

Step-by-step explanation:

Firstly, create a function largerThanN that accepts two arguments, a list (myList) and a number (n) (Line 1).

Next, create a output variable to hold the string of numbers in the list that are greater than the input number n (Line 2).

Create a for loop to traverse through each number in the list and then check if the current x is bigger than n. If so concatenate the x to output string along with a single space " " (Line 4 -6)

After the loop, print the output string (Line 8)

We test the function by using a sample list and n = 15 (Line 10 - 12). The program will display 56 32 .

User DJElbow
by
3.4k points