Home > Software engineering >  Simple Input with integers as input and list as output
Simple Input with integers as input and list as output

Time:10-08

lst =[]
inputs =(input("user please give me integer!:"))
if int(inputs) <5:
    print(lst.append(inputs))
    print(lst)
if int(inputs)>5:
    print("You was false")

Hello, I need help. I am absolute Beginner and i want to solve an python task. Could anyone give me a hint or the solution. How I could make the output to a list or make the inputs to a list? :

Take a list, say for example this one:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

and write a program that prints out all the elements of the list that are less than 5.

Extras:

  • Instead of printing the elements one by one, make a new list that has all the elements less than 5 from this list in it and print out this new list.
  • Write this in one line of Python.
  • Ask the user for a number and return a list that contains only elements from the original list a that are smaller than that number given by the user.

CodePudding user response:

take a look at the code below which has three functions, each which address one of your bullet points. Note that instead of using filter you can also use a list comprehension like this new_list = [x for x in a if x < 5]

# Print each element individually it it meets the critera
def printEach(a, num):
    for elem in a:
        if elem < num:
            print(elem)

# Generate a new list in one line based on the critera
def newList(a, num):
    new_list = list(filter(lambda x: x < num, a))
    print(new_list)
    return new_list

# Get user input and generate a new list based on the input
def newListFromInput(a):
    num = int(input('Enter number: '))
    return newList(a, num)
    
def main():
    a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
    num = 5
    printEach(a, num)
    newList(a, num)
    newListFromInput(a)

if __name__ == '__main__':
    main()

CodePudding user response:

Four solutions:

a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

# Print elements less than 5
for e in a:
    if e < 5:
        print(e)

# Make a list
lst = []  # Start with an empty list
for e in a:
    if e < 5:
        lst.append(e)  # Append elements < 5
print(lst)

# One liner:
print(list(filter(lambda x: x<5, a)))  # Use the built in filter function

# Ask:
n = input('Enter an integer: ')
print(list(filter(lambda x: x<int(n), a)))  # Ask for a number for the filter

Output:

1
1
2
3
[1, 1, 2, 3]
[1, 1, 2, 3]
Enter an integer: 6
[1, 1, 2, 3, 5]
  • Related