3
\$\begingroup\$

I'm practicing loops in Python and started trying to have a better approach with user inputs, is there better ways of dealing with inputs when coding? And I tried using deques too, it worked very well, but don't know if I should or need to; are deques better in this case or should I keep using lists?

sum_numbers: list = list()

for question in range(1, 11):
    while True:
        try:
            print(f'{question}º number: ')
            asnwer = float(input('->  ').strip().replace(',', '.'))
        except ValueError:
            print('Invalid input! Try again...\n')
            continue
        else:
            sum_numbers.append(asnwer)
            break

print(
    '\nNumbers:\n'
    f'{sum_numbers}\n'.replace('[', '').replace(']', '') +
    f'\nSum: {sum(sum_numbers)}.'
)
\$\endgroup\$
3
  • \$\begingroup\$ Do you intend on supporting comma decimals like 9,263 ? \$\endgroup\$
    – Reinderien
    Aug 31, 2022 at 0:46
  • \$\begingroup\$ @Reinderien I wanted to make sure that even if the user types a number like 9,263 could have the same results as someone typing 9.263. In the script perspective, 9,263 will be read as 9.263 after the ',' is replaced with the '.' to let the code work as intended. But I think that I didn't understood your question, did i answered it correctly? \$\endgroup\$
    – eddyxide
    Aug 31, 2022 at 1:22
  • \$\begingroup\$ Kind of. If I had to guess, your locale is pt-PT, whose decimal separator is a comma. I have suggestions on how to better handle this. \$\endgroup\$
    – Reinderien
    Aug 31, 2022 at 1:24

1 Answer 1

2
\$\begingroup\$

performatic isn't a word, and in the software development industry this is more frequently written performant. Anyway, performance is not at all a concern in this program and you should be more concerned about correctness, maintainability and legibility.

If you're trying to accommodate commas as decimals, that's localisation (L10N). Python has support for localisation, and you should use it.

Consider rewriting your input loop as an iterator function.

asnwer is spelled answer.

Don't convert a list to a string and then .replace() on it - instead .join() the sequence with a separator of your choice.

You don't need a continue/else: you can break right out of the try.

Suggested

from locale import atof, format_string, setlocale, LC_ALL
from typing import Iterator


def get_numbers(n: int) -> Iterator[float]:
    for question in range(1, n + 1):
        while True:
            try:
                yield atof(input(f'{question}º número: '))
                break
            except ValueError:
                print('Entrada inválida! Tente novamente...')


def main() -> None:
    setlocale(LC_ALL, 'pt-PT')
    numbers = tuple(get_numbers(10))
    formatted_numbers = ", ".join(
        format_string('%.1f', x) for x in numbers
    )
    print(
        '\nNúmeros:'
        f'\n{formatted_numbers}'
        f'\nSoma: {format_string("%.1f", sum(numbers))}.'
    )


if __name__ == '__main__':
    main()

Output

1º número: 7.5
2º número: 3,50
3º número: 4,2
4º número: 5
5º número: 5
6º número: 5
7º número: 5
8º número: 5
9º número: 5
10º número: 5

Números:
7,5, 3,5, 4,2, 5,0, 5,0, 5,0, 5,0, 5,0, 5,0, 5,0
Soma: 50,2.
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Thank you, Reinderien. All the tips and the suggested code made me see more clearly the need for study about the code itself and the correct way of spelling or using some words when talking about software development. Getting back to studies right now! \$\endgroup\$
    – eddyxide
    Aug 31, 2022 at 1:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.