Problem when declaring 2 variables

Asked

Viewed 67 times

0

The problem is this, I need to do a function to sum 2 numbers that the user must insert by separating them through commas, eg: 2.3, for such values 2 + 3 = 5, so the result should show 5 as a result. Even that part was no problem. The problem is that the program also needs to understand that the user can put only 1 number or none and this part is giving error. Follow the lines below the code made so far.

Code

def soma (num1,num2):    
    return num1 + num2

num1,num2 = [int(num1) for num1 in input("Insira 2 valores separados por vírgula: ").split(",")]

print(soma(num1,num2))

2 answers

1


The problem is that the program also needs to understand that the user can put only 1 number or none

Good, for this you need to analyze what was typed, before converting to int and go out doing the math.

First you get the input and does the split:

valores = input("Insira 2 valores separados por vírgula: ").split(",")

What happens if only one number is entered? For example, if you type only 2, then valores will be a list with only one element: ['2'] (do this test, put a print(valores) after the line above and type only 2).

And if the user does not type anything (just give ENTER)? The string will be empty, and valores will only have an empty string: [''].

What if I type something other than a number, or numbers but separated by anything other than a comma, or more than two numbers? There are many cases that can go wrong, and from what I understand, the program should only work if the resulting list has exactly two numbers separated by comma.

So that’s what you should validate: if the list returned by split has 2 elements, and if both are integer numbers. Then it could be something like:

def soma(num1, num2):
    return num1 + num2

valores = input("Insira 2 valores separados por vírgula: ").split(",")
if len(valores) == 2: # foram digitados 2 valores separados por vírgula, agora temos que ver se são números
    try:
        # converte para números
        num1, num2 = map(int, valores)
        # se chegou aqui, é porque a conversão para int deu certo
        print(soma(num1, num2))
    except ValueError: # se não tiver número, vai lançar um ValueError
        print('Algum dos valores digitados não é um número')
else:
    print('você deve digitar exatamente 2 valores separados por vírgula')

I decided to only print error messages if you don’t have exactly two numbers (because if you have less, you don’t have anything to add, and if you have more, it’s not clear what to do with the surpluses). But once you know how to validate, you can treat each case individually the way you prefer.

For example, it was mentioned in the comments that if it is just a number, it must be the result itself. Then just add a special case for when it has only one value:

def soma(num1, num2):
    return num1 + num2

valores = input("Insira 2 valores separados por vírgula: ").split(",")

if len(valores) == 1: # foi digitado apenas um valor
    try:
        print(int(valores[0])) # imprime somente o número (acho que nem precisa chamar a função soma, é desnecessário)
    except ValueError:
        print('O valor não é um número')
elif len(valores) == 2: # foram digitados 2 valores separados por vírgula, agora temos que ver se são números
    try:
        # converte para números
        num1, num2= map(int, valores)
        # se chegou aqui, é porque a conversão para int deu certo
        print(soma(num1, num2))
    except ValueError: # se não tiver número, vai lançar um ValueError
        print('Algum dos valores digitados não é um número')
else:
    print('você deve digitar exatamente 1 número, ou 2 separados por vírgula')
  • In fact, if you only have 1 number ex: 2, it should return the 2 since it will be 2 + 0. But thank you, you’ve already helped me pass 1 more step.

  • 1

    @user235404 In this case, you must edit the question and put all the criteria and what to do in each of the cases, so people can give more accurate answers

  • You really helped me a lot friend, but in case he didn’t enter anything, I would put as == None?

  • @user235404 If the person does not type anything (just give ENTER), input returns an empty string, so it could look something like this: https://ideone.com/Sdvt6q

0

Changing only a little

import sys

def soma (num1, num2):    
    return num1 + num2


try:
    s1, s2 = input("Insira 2 valores separados por vírgula: ").split(",")
except:
    print("Erro na entrada de dados.")
    sys.exit(0)

try:
    print(soma(float(s1),float(s2)))
except:
    print("Tem certeza que os valores digitados são numéricos?")
  • 1

    @Augustovasques, thanks for the remark. Post updated.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.