I am fairly new to Python and programming. I created this simple calculator inspired by my physics class. However, I feel this code could have been done more efficiently. Is there any advice for efficiency?
import math
#calculates vector x component
#x = side length y = angle
def fxcomponent(x, y):
number = x
y = math.cos(math.radians(y))
result = number * y
return result
#calculates vector y component
def fycomponent(x, angle):
number = x
angle = math.sin(math.radians(angle))
result = number * angle
return result
prompt = 'Welcome to my Python vector components calculator!'
prompt += '\nPlease select what you wish to find: \n-type x for x-component
prompt += '\n-type y for y-component'\n-type quit to end program'
flag = True
while flag == True:
number = input(prompt + '\n>')
#ends program when quit
if number.lower() == 'quit':
flag = False
#calculates x component and continues with y component if desired
elif number.lower() == 'x':
print ('Please tell me the x and the angle:')
x, angle = [int(x) for x in input('>').split()]
result = fxcomponent(x, angle)
print('The x component of %d at %d° is: %d' % (x, angle, result))
answer = input('Now do you wish to find the y component? \nType Y/N\n>')
if answer.lower() == 'y':
print ('Please tell me the y and the angle:')
y, angle = [int(x) for x in input('>').split()]
result = fycomponent(y, angle)
print('The y component of %d at %d° is: %d' % (y, angle, result))
elif answer.lower() == 'n':
print('Thanks for using my program! See you later!')
flag = False
elif answer.lower() != 'y' or 'n':
print('Invalid command! try again')
#calculates y component and continues with x component if desired
elif number.lower() == 'y':
print ('Please tell me the y and the angle:')
y, angle = [int(x) for x in input('>').split()]
result = fycomponent(y, angle)
print('The y component of %d at %d° is: %d' % (y, angle, result))
answer = input('Now do you wish to find the x component? \nType Y/N\n>')
if answer.lower() == 'y':
print ('Please tell me the y and the angle:')
y, angle = [int(x) for x in input('>').split()]
result = fycomponent(y, angle)
print('The x component of %d at %d° is: %d' % (x, angle, result))
elif answer.lower() == 'n':
print('Thanks for using my program! See you later!')
flag = False
elif answer.lower() != 'y' or 'n':
print('Invalid command! try again')
else:
print ('Invalid command; try again!')
continue
prompt
strings are malformed, and one of yourelif
indentations doesn't line up. Please ensure that your code has been posted correctly as intended. The easiest way to post code is to paste it into the question editor, highlight it, and press Ctrl-K to mark it as a code block. – 200_success♦ Mar 4 at 7:40