I'm currently working on a script that calculates the costs of an electric engine.
For that, I have to take into consideration the fees for each kWh of electricity spent. There are 5 possible fees, which I've stored in a dictionary, along with their respective prices.
I want the user to type the current fee, and from that, store the price as an independent variable, so I can multiply the kWh price by the engine's total running time.
The part of the script where the user chooses the fee is this one:
flags = {
"Green Flag" : "0.19829",
"Yellow Flag" : "0.22818",
"Red Flag 1" : "0.26329",
"Red Flag 2" : "0.29624",
"Drought Flag" : "0.34029"
}
print("CEMIG's power consumption flags are: \n")
for x in flags:
print (x, "\n", "-" * 20, "\n")
def flag():
while True:
print("What's the current flag at the farm's location? \n")
global choose_current_flag
choose_current_flag = input(">: ")
if choose_current_flag in flags:
print(f"Right, so we are in {choose_current_flag}. \n")
for value in flags[choose_current_flag]:
global cost_kwh
cost_kwh = value
print(cost_kwh)
else:
print("Be sure you've inserted the correct flag. \n")
Currently, the script gives me the following:
"CEMIG's power consumption flags are:
Green Flag
--------------------
Yellow Flag
--------------------
Red Flag 1
--------------------
Red Flag 2
--------------------
Drought Flag
--------------------
What's the current flag at the farm's location?
>: Green Flag
Right, so we are in Green Flag.
0
.
1
9
8
2
9"
I understand why this is happening. The value is a string, so the for loop will iterate through every character.
Using the value as a bool did not help me, since I'm not able to iterate through it anyways.
I've tried dozens of alternatives, ready many answers here and elsewhere, but I can't find a way to get a user input to store the value as a variable.
CodePudding user response:
So, here in your code, Instead of iterating and using this snippet :
for value in flags[choose_current_flag]:
global cost_kwh
cost_kwh = value
print(cost_kwh)
Use this :
print(flags[choose_current_flag])
This is used to get the value of the specific key in the python dictionary.
Hope this helps you :)
CodePudding user response:
flags holds string values, and on top of that I don't think you want a loop at all.
I think you are looking for...
cost_kwh = float(flags[choose_current_flag])
... in place of your loop