Yes it is possible, but first, I’d like to talk about some quick improvements you can make to your code. First of all, it is not necessary to use parentheses when creating the string and calculating the temperature.
Second, if the user option is not valid, the if
's will be executed anyway, and the user must open the program again to choose the option again. So what you could do is create a block while
for the program to repeat the selection screen while the user has not chosen a valid option.
Third, in Python, you must create the real numbers using a dot .
and no comma. Another interesting detail is that, in Python, we can make multiple comparisons in a single line. So we can transform if mensagem > 6 or mensagem < 0
therein if not 0 < option < 7
.
Those were some mistakes, but there are others too that you can see below in the answer.
Now back to the focus of the question, yes it is possible to create a function to reduce the conditional and make the code more beautiful and organized. See below:
def obterTemperatura(option):
temp = float(input("Qual é a temperatura ? "))
if option == 1:
return temp * 1.8 + 32
elif option == 2:
return 5 * (temp - 32) / 9
elif option == 3:
return temp + 273.15
elif option == 4:
return temp - 273.15
elif option == 5:
return (temp + 459.67) / 1.8
elif option == 6:
return temp * 1.8 - 459.67
try:
option = int(input(mensagem))
if not 0 < option < 7:
raise ValueError
print(obterTemperatura(option))
except:
print("Escolha uma opção válida.")
In the above code, I fixed some errors and reused some lines, placing them within the function obterTemperatura
. But still, it is possible to further reduce this code, using dictionaries and anonymous functions (Arabic).
With dictionaries, we can get a value from a key. Then we can make it a kind of "conditional" (you will already understand this idea). What I’m going to do is I’m going to pass the calculation options as dictionary keys, and I’m going to create anonymous functions for each of these keys. See below how it will look:
def obterTemperatura(option):
temp = float(input("Qual é a temperatura ? "))
calculos = {
1: lambda temp: temp * 1.8 + 32,
2: lambda temp: 5 * (temp - 32) / 9,
3: lambda temp: temp + 273.15,
4: lambda temp: temp - 273.15,
5: lambda temp: (temp + 459.67) / 1.8,
6: lambda temp: temp * 1.8 - 459.67
}
return calculos[option](temp)
In this role, I created a dictionary called calculos
that contains keys from 0 to 6. In each of these keys, there is a function that will return the result of the temperature calculation of its respective option.
Hence, if option
for 4
, for example, the program will get the key value 4
which will be the function lambda temp: temp - 273.15
, and this will be executed by returning the function result.
In many cases a large amount of conditionals could be replaced by a hash table data structure.
– Fabricio Paiva