Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exception handling
#1
try:
    power = float(input ("Please entre Power in kW: "))
    voltage = float (input ("Please entre Voltage: "))
    phase = int(input("1 or 3 phase? "))

except:
    print("Oops!  That was no valid number.  Try again...")
    
if phase==1:
	current = (power/voltage)*1000
	print("The current is :" ,round(current, 2),"Amp")

if phase==3:
	current = (power/(1.732*voltage))*1000
	print("The current is :" ,round(current, 2),"Amp")

input()
Hi All,
What to retry after exception. How to write the code. Let says the user input wrongly in voltage, just want to go back to voltage after exception. not from start. Also for the phase, I just want to accept 1 or 3, how to code.
Reply
#2
Try this
def input_float(message):
    while True:
        try:
            return float(input(message))
        except ValueError:
            print('Oops, that was not a valid number. Try again...')

voltage = input_float('Please enter voltage:')
Reply
#3
while True:
    def input_power(value):
        while True:
            try:
                return float(input(value))
            except ValueError:
                print('Oops, that was not a valid number. Try again...')
 
    power = input_power('Please enter power in kW:')

    def input_voltage(value):
        while True:
            try:
                return float(input(value))
            except ValueError:
                print('Oops, that was not a valid number. Try again...')
 
    voltage = input_voltage('Please enter voltage:')

    def input_phase(value):
        while True:
            try:
                return float(input(value))
            except ValueError:
                print('Oops, that was not a valid number. Try again...')
 
    phase = input_phase('1 or 3 phase? ')
    
   
    if phase==1:
	    current = (power/voltage)*1000
	    print("The current is :" ,round(current, 2),"Amp")

    if phase==3:
	    current = (power/(1.73205*voltage))*1000
	    print("The current is :" ,round(current, 2),"Amp")

input()
Finally, got it. learned new things. Thanks!
Reply
#4
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Star python exception handling handling .... with traceback mg24 3 1,215 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  TicTacToe Game Add Exception Handling and Warning Function ShaikhShaikh 5 2,376 Nov-03-2021, 05:02 PM
Last Post: deanhystad
  Exception handling in regex using python ShruthiLS 1 2,328 May-04-2020, 08:12 AM
Last Post: anbu23
  Exception handling Calli 2 2,409 Apr-20-2020, 06:13 PM
Last Post: Calli
  Handling exception from a module dchi2 11 5,494 Nov-25-2019, 08:47 AM
Last Post: dchi2
  problem using custom exception handling in python srm 3 2,995 Jul-03-2019, 09:10 PM
Last Post: ichabod801
  an easy way to disable exception handling Skaperen 6 5,295 Jun-02-2019, 10:38 PM
Last Post: Gribouillis
  Database operation exception handling LostInCode 1 2,448 Jan-03-2019, 07:50 PM
Last Post: jeanMichelBain
  During handling of the above exception, another exception occurred Skaperen 7 26,723 Dec-21-2018, 10:58 AM
Last Post: Gribouillis
  Exception Handling grkiran2011 3 2,921 Oct-05-2018, 03:23 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020