This is a calculator for Ohm's Law and Power Law. It works but I'd like some suggestions on making the code look a little cleaner, or run more efficiently.
# ohm's law calculator
#These functions perform ohm's law and power law calculations based on variables from user input.
def voltage(i, r):
return i * r
def current(r, v):
return r / v
def resistance(i, v):
return i / v
def power(v, i):
return v * i
def pvolt(w, i):
return w / i
def pcurrent(w, v):
return w / v
# First user interface menu. let's user choose between ohm's law and power law calculations.
print "Ohm's Law Calculations:"
print "1. Voltage"
print "2. Current"
print "3. Resistance"
print "Power Law Calculations:"
print "4. Wattage"
print "5. Voltage"
print "6. Current"
#Line 48 is taking the user's menu choice and passing it to the "choice" options below.
choice = raw_input(">>> ")
#These if statements are calling the functions.
#This gives values to "i" "v" "w" and "r" from user input as floating point numbers the print line calls the "voltage" function and prints out the results of its calculation using the "format" function which automatically displays the needed decimal places.
if choice == "1":
i=float(raw_input("Enter current:"))
r=float(raw_input("Enter resistance:"))
print "{0} volts" .format(voltage(i, r))
elif choice == "2":
r=float(raw_input("Enter resistance:"))
v=float(raw_input("Enter voltage:"))
print "{0} amps" .format(current(r, v))
elif choice == "3":
i=float(raw_input("Enter current:"))
v=float(raw_input("Enter voltage:"))
print "{0} ohms" .format(resistance(i, v))
elif choice == "4":
i=float(raw_input("Enter current:"))
v=float(raw_input("Enter voltage:"))
print "{0} watts" .format(power(i, v))
#Line 82 solves voltage according to power law
elif choice == "5":
w=float(raw_input("Enter wattage:"))
i=float(raw_input("Enter current:"))
print "{0} volts" .format(pvolt(w, i))
#Line 89 solves current according to power law. I am attempting to make it round of the answer
elif choice == "6":
w=float(raw_input("Enter wattage:"))
v=float(raw_input("Enter voltage:"))
print "{0} amps" .format(pcurrent(w, v))
#This line is here partly because its funny, and partly because I thought it would be cool to create my own error message
else:
print "Invalid number. Your computer will now self destruct."