HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Print some elements from input

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elementsinputprintsomefrom

Problem

I am studying Python, so it is very easy task. I want to get best and most elegant way to solve each simple task.
The task is:


Write a program that reads the integers from the console one number per line.
For each entered number check:



  • if the number is less than 10, skip that number;



  • if the number is greater than 100, stop to read the numbers;





Print all numbers that does not satisfy those two conditions.

lst = []
num = 0
while num  100:
        break
    if num >= 10:
        lst.append(num)

print('\n'.join(str(value) for value in lst))

Solution

Your code is pretty good. Change num

  • itertools.takewhile` the input is good.



  • Filter input.



def user_input():
    while True:
        yield input()

def to_int(numbers):
    for num in numbers:
        try:
            yield int(num)
        except ValueError:
            continue

nums = itertools.takewhile(lambda n: n = 10))


Python is multi-paradigm, and so you can mix them. And so as-long as it works and is clear, it's fine. I personally would use:

def user_input():
    while True:
        try:
            yield int(input())
        except ValueError:
            continue

def filter_numbers(numbers):
    for num in numbers:
        if num > 100:
            break
        if num >= 10:
            yield num

print('\n'.join(str(n) for n in filter_numbers(user_input())))

Code Snippets

list_ = []
while True:
    try:
        num = int(input())
    except ValueError:
        continue
    if num > 100:
        break
    if num >= 10:
        list_.append(num)
def user_input():
    while True:
        yield input()

def to_int(numbers):
    for num in numbers:
        try:
            yield int(num)
        except ValueError:
            continue

nums = itertools.takewhile(lambda n: n <= 100, to_int(user_input()))
print('\n'.join(str(n) for n in nums if n >= 10))
def user_input():
    while True:
        try:
            yield int(input())
        except ValueError:
            continue

def filter_numbers(numbers):
    for num in numbers:
        if num > 100:
            break
        if num >= 10:
            yield num

print('\n'.join(str(n) for n in filter_numbers(user_input())))

Context

StackExchange Code Review Q#152245, answer score: 7

Revisions (0)

No revisions yet.