(May-07-2019, 01:40 AM)KyawMyo Wrote: Finally, got it. learned new things. Thanks!
One of main principles is don't repeat yourself (DRY) and you are doing exactly that. Think what your function should do and how you want it to be customizable. That's what Gribouillis's example is - general implementation that can be customized by passing an argument (message/prompt to be displayed). You can use it virtually everywhere to get float number input from user.
Then couple of more issues:
- Your script will run infinitely, because you have infinite loop and don't provide user a way out of the loop. the last line
input()
will never be executed
- lines 30-36 can be rewritten as single function that takes phase as argument
def get_float(message):
while True:
try:
return float(input(message))
except ValueError:
print('Oops, that was not a valid number. Try again...')
def calculate_current(phase):
phase = int(phase)
if phase not in (1, 3):
raise ValueError(f'Incorrect phase. Expecting 1 or 3, got {phase}')
k = 1.73205 if phase == 3 else 1 # use appropiate symbol, if there is accepted one - I just don't know
return (power/(k * voltage))*1000
if __name__ == '__main__':
while True:
power = get_float('Please enter power in kW:')
voltage = get_float('Please enter voltage:')
phase = get_float('1 or 3 phase? ')
try:
current = calculate_current(phase)
except ValueError as ve:
print(ve)
else:
print(f'The current is {current:.2f} Amp')
if input('Do you want to calculate again (yes/no)? ').lower() in ('no', 'n'):
break
There are things that eventually can be made better or differently, but you get the idea