I am trying to implement a function printGreater()
that takes a list of numbers and a numeric value as parameter. It prints the numbers in the list that are greater than the value, all on one line with a space between them. If an empty list is provided as the first parameter, the function doesn't print anything.
This is what I have so far:
def printGreater(nums, value):
lstN = (int[nums],value)
if nums > value:
print(nums, end=", ")
def printGreater(nums, value):
#First create an empty list to hold onto all the numbers larger than value
greater = [];
#Loop overall the input values, saving all large ones
for num in nums:
if num > value:
#Convert to a string for printing
greater.append(str(num))
#Print them out with spaces in between
print( ' '.join(greater) )
#Then test with this
printGreater([1, 2, 3, 4, 5, 6, 7], 3)
Here, you'll want to use a for loop. I'll place the code, then explain what's going on.
def print_greater(nums_list, value):
string = ''
for num in nums_list:
if num > value:
string += str(num) + ' '
return string
First, I'm initializing a new string variable:
string = ''
Next, I start an iteration loop:
for num in nums_list:
...
What that iteration (for) loop is going to do, is to start with the first item in a list a give it, and make that item 'num'. Then I can do whatever I want with that item. Once I'm finished, it will move on to the second item, and so on.
if num > value:
string += str(num) + ' '
In this case, I want to compare num to value. If num is great, I want to add onto the string I initialized earlier. That's what the += means...
string += str(num) + ' '
is the same as
string = string + str(num) + ' '
Finally, at the end, I return the string.
Hope that helps!