I made this calculator to try and calculate trigonometry in python. I've only just started learning how to use this program and I haven't been able to find anything so far that makes sense to me. The problem with this is that I keep getting different answers to those that come up on my scientific calculator.
while True:
print('type "sine1" to find the value of the Opposite')
print('type "sine2" to find the value of the Hypotenuse')
print('type "cosine1" to find the value of the Adjacent')
print('type "cosine2" to find the value of the Hypotenuse')
print('type "tangent1" to find the value of the Opposite')
print('type "tangent2" to find the value of the Adjacent')
user_input = input(": ")
from math import sin, cos, tan
if user_input == 'sine1':
degrees = float(input('Enter the degrees: '))
hypotenuse = float(input('Enter the value of the hypotenuse: '))
result = str(hypotenuse * sin(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'sine2':
degrees = float(input('Enter the degrees: '))
opposite = float(input('Enter the value of the opposite: '))
result = str(opposite / sin(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'cosine1':
degrees = float(input('Enter the degrees: '))
hypotenuse = float(input('Enter the value of the hypotenuse: '))
result = str(hypotenuse * cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'cosine2':
degrees = float(input('Enter the degrees: '))
adjacent = float(input('Enter the value of the adjacent: '))
result = str(adjacent / cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'tangent1 ':
degrees = float(input('Enter the degrees: '))
adjacent = float(input('Enter the value of the adjacent: '))
result = str(hypotenuse * tan(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
elif user_input == 'tangent2':
degrees = float(input('Enter the degrees: '))
opposite = float(input('Enter the value of the opposite: '))
result = str(adjacent / cos(degrees))
print('The answer is ' + result)
print(input('Press enter to quit: '))
break
else:
print('invalid input, please close the program and try again... maybe learn how to spell first :P')
print(input('press enter to quit'))
All trigonometric function from the math module require their argument to be in radians, not in degrees. You can use math.radians to do the conversion.
import math
degrees = 90
radians = math.radians(degrees)
print(math.sin(radians)) # 1.0
Python's trig functions assume that the input is in radians, and you're entering degrees.
First convert your degrees to radians by multiplying degrees by math.pi/180.0 and see if those match better.
Related
I'm new in programming, using Python 3.9.
So, I'm doing a simple math program from what I understand on reading and tutorials.
here's the code:
print('\n Simple Math ')
def num():
if choice == 1:
sum = first_num + second_num
print('Sum is: ', sum)
elif choice == 2:
diff = first_num - second_num
print('Difference is: ', diff)
elif choice == 3:
mul = first_num * second_num
print('Product is: ', mul)
elif choice == 4:
div = first_num / second_num
print('Quotient is: ', div)
while True:
print('\n 1. Add: \n 2. Subtract: \n 3. Multiply: \n 4. Divide: \n')
choice = int(input('Select an operator: '))
if choice > 4 or choice < 1:
choice = int(input('Input only valid selection from above! \nSelect again: '))
first_num = float(input('Enter first number: '))
second_num = float(input('Enter second number: '))
num()
break
My problem above is, when I added that "Input only valid selection from above!" portion if the user inputs beyond the number of the selection, it doesn't do anything when I try to input from 1 to 4. But if I input 5, it works good.
I already tried to put the first_num and second_num outside the while loop or above the def, tried to put num() before the while, still gives me an error. I'm doubting the portion "if choice > 4 or choice < 1:" that makes my code returns nothing when entering the right selections. Tho I'm kinda stuck and don't know what to do next.
Appreciate any help...
thanks
Pardon me, I'm really an absolute beginner... 😅
You code was a pretty good start. However, there were a few flaws.
you need to pass the variables to use to your num function
you should individualize the logic for inputting the 3 numbers (I used a separate function here)
Below is a working version.
Now you can try to improve it, for example by adding checks on the first_num/second_num values (let's say forbid 0 i second_num for division). You can also try to move the checks into the validate_input function.
print('\n Simple Math ')
def num(choice, first_num, second_num):
if choice == 1:
sum = first_num + second_num
print('Sum is: ', sum)
elif choice == 2:
diff = first_num - second_num
print('Difference is: ', diff)
elif choice == 3:
mul = first_num * second_num
print('Product is: ', mul)
elif choice == 4:
div = first_num / second_num
print('Quotient is: ', div)
def validate_input(prompt='?: ', input_type=int):
while True:
try:
return input_type(input(prompt))
except ValueError:
print('Incorrect input')
while True:
print('\n 1. Add: \n 2. Subtract: \n 3. Multiply: \n 4. Divide: \n')
choice = -1
while choice > 4 or choice < 1:
choice = validate_input('Select an operator: ')
first_num = validate_input('Enter first number: ', float)
second_num = validate_input('Enter second number: ', float)
num(choice, first_num, second_num)
No need to say pardon, you said you're a beginner, mistakes do happen with advanced coders. You have to pass those numbers in the function to use it. Also in the if condition, it is better to use while because, once you put wrong input, it'll show error and then it'll ask for input again. Now even if you put wrong input, it'll accept because it will not check again if it is correct. Try doing this:
print('\n Simple Math ')
def num(first_num, second_num):
if choice == 1:
sum = first_num + second_num
print('Sum is: ', sum)
elif choice == 2:
diff = first_num - second_num
print('Difference is: ', diff)
elif choice == 3:
mul = first_num * second_num
print('Product is: ', mul)
elif choice == 4:
div = first_num / second_num
print('Quotient is: ', div)
while True:
print('\n 1. Add: \n 2. Subtract: \n 3. Multiply: \n 4. Divide: \n')
choice = int(input('Select an operator: '))
while choice > 4 or choice < 1:
choice = int(input('Input only valid selection from above! \nSelect again: '))
first_num = float(input('Enter first number: '))
second_num = float(input('Enter second number: '))
num(first_num,second_num)
break
I was having a small issue while I was trying to write a program to calculate simple interest in Python.
def si(p,r=100,t=2):
return (p*r*t)/100
x=float(input("Enter principal amount"))
y=float(input("Enter rate"))
z=float(input("Enter time"))
print (si(x,y,z))
I want to make y and z optional. Any idea how can I do? If I leave it blank and press enter it shows error.
The easiest way is using or
def si(p,r,t):
return (prt)/100
x = float(input("Enter principal amount: "))
y = float(input("Enter rate: ") or 100)
z = float(input("Enter time: ") or 2)
print (si(x,y,z))
Enter principal amount: 1
Enter rate:
Enter time:
2.0
But correct way is validating input before converting it to float
def si(p,r=100,t=2):
return (p*r*t)/100
x = input("Enter principal amount: ")
y = input("Enter rate: ")
z = input("Enter time: ")
def validate(param):
return float(param) if param else 1
print (si(validate(x), validate(y), validate(z)))
Output:
Enter principal amount: 1
Enter rate:
Enter time:
0.01
I have a homework problem and I need to add a while loop to my function that will give the user 3 additional tries to enter another value if the value originally entered is not a number. The original function of the code is to determine the area of a triangle or trapezoid.
loopCount = 0
# The "while" statement keeps looping until its condition (loopCount<4) made False.
while loopCount<4:
# loopCount will increase 1 for each loop
loopCount += 1
Though I'm not even sure where to fit the above lines in my code.
# This program calculates the area of a triangle or trapezoid
# Statement: print function outputs the statement on screen
print("This program finds the area of a triangle or trapezoid.")
print()
# Module: math module imported
import math
# Determine the objects shape
print("Please enter the shape from the following menu")
print("Triangle = type 1")
print("Trapezoid = type 2")
# If user types a number other than 1 or 2, this will prompt them again to pick a valid choice
user_input = 0
while user_input not in (1,2) :
user_input = int(input("Enter your choice: "))
# Variables: asigns new value to a variable depending on which shape we are caluclating the area of
if (user_input == 1):
print("Alright, you want to calculate the area of a triangle: ")
height = float(input("Please enter the height of the triangle: "))
base = float(input("Please enter the base length of the triangle: "))
if (user_input == 2):
print("Alright, you want to calculate the area of a trapezoid: ")
base_1 = float(input("Please enter the base length of the trapezoid: "))
base_2 = float(input("Please enter the second base length of the trapezoid: "))
height = float(input("Please enter the height of the trapezoid: "))
# Expression and operators: calculates area based on shape choosen. Triangle_area = (base*height)/2, Trapezoid_area = ((base1+base2)/2)*height
if (user_input == 1):
area_triangle = 0.5 * height * base
if (user_input == 2):
area_trapezoid = ((base_1+base_2)/2)*height
# Function: math function returns a statement defining the height, base(s) and area of the triangle or trapezoid
if (user_input == 1):
print("The area of a triangle with height", height, "and base", base, "is", area_triangle)
if (user_input == 2):
print("The area of a trapezoid with height", height, ", base 1", base_1, "and base 2", base_2, "is", area_trapezoid)
If the user enters a value that could not be converted to numeric type, allow 3 additional opportunities to enter a new value. If the user fails to enter a correct value after 4 attempts, inform them of such failure and allow the program to end without crashing.
You can use a try/except on the input to handle the ValueError when float() fails to convert the value to a float or an OverflowError "if the argument is outside the range of a Python float".
loopCount = 0
while loopCount < 4:
try:
height = float(input("Please enter the height of the triangle: "))
break
except:
print("That is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
You can check for all the inputs at once inside the try block (if you don't care which one specifically is invalid or you don't need to point it out to the user):
loopCount = 0
while loopCount < 4:
try:
base_1 = float(input("Please enter the base length of the trapezoid: "))
base_2 = float(input("Please enter the second base length of the trapezoid: "))
height = float(input("Please enter the height of the trapezoid: "))
break
except:
print("One of the inputs is not a number.")
loopCount += 1
if loopCount == 4:
print("You failed to input valid values")
# return with an error or maybe abort with sys.exit(1)
else:
print("Great! I can now compute stuff.")
To avoid lots of repeated try-except's, I suggest creating a method for getting a float input (or all of the inputs), and then just calling it from your main method.
I'm trying to write a code in Python three that converts temperatures and distances from one unit to another. I'm told that I need to use functions and that the user will input either F (Fahrenheit), C (Celsius), or K (Kelvin) and the temperature will be converted from whatever they choose to F, C or K. So I wrote a function for each scenario. A function for if it's converted from F, another if it's converted from C, and another if it's converted from K. I also did this for inches, feet, yards, and miles.
So after I wrote all of the functions I wrote an if, elif, and else statement which I want to call each function depending on what the user types. So if the user inputs "F" I want it to call the convert_from_F() function, or if they put "K" I want it to use the convert_from_K(), or if the user types "inch" I want it to use the convert_from_inch() function. I thought that the way to do this would be to use the if, elif, and else statement. However, no matter what I type I'm always given the error message:
NameError: name 'F' is not defined
I would have thought that the iterations would continue past each statement if it found that the user didn't input that particular instruction. It also doesn't work if I (as the user) put 'F.' I'm not sure how to fix this code. What am I missing from it?
Also, I'm using an online python 3 compiler to write my program: OnlineGDB
def convert_from_F():
F = float(input("Please input the temperature in F: "))
print("Temperature in F is", F)
print("Temperature in C is", (F-32)*5/9)
print("Temperature in K is", (F-32)*5/9 + 273.15)
def convert_from_C():
C = float(input("Please input the temperature in C: "))
print("Temperature in F is", (C*9/5) + 32)
print("Temperature in C is", C)
print("Temperature in K is", C+273.15)
def convert_from_K():
K = float(input("Please input the temperature in K: "))
print("Temperature in F is", (K-273.15)*9/5 + 32)
print("Temperature in C is", K-273.15)
print("Temperature in K is", K)
def convert_from_inch():
inch = float(input("Please input the distance in inches: "))
print("Distance in inches is:", inch)
print("Distance in feet is:", inch/12)
print("Distance in yards is:", inch/36)
print("Distance in miles is:", inch/63360)
def convert_from_ft():
ft = float(input("Please input the distance in feet: "))
print("Distance in inches is:", ft*12)
print("Distance in feet is:", ft)
print("Distance in yards is:", ft/3)
print("Distance in miles is:", ft/5280)
def convert_from_yd():
yd = float(input("Please input the distance in yards: "))
print("Distance in inches is:", yd*36)
print("Distance in feet is:", yd*3)
print("Distance in yards is:", yd)
print("Distance in miles is:", yd*1760)
def convert_from_mi():
mi = float(input("Please input the distance in miles: "))
print("Distance in inches is:", mi*63360)
print("Distance in feet is:", mi*5280)
print("Distance in yards is:", mi*1760)
print("Distance in miles is:", mi)
print("To convert distance input inch, ft, yd, or mi. To convert \
temperatures please input F, C, or K. ")
user_input = input("Your input: ")
def user_conversion():
if user_input == F or f:
convert_from_F()
elif user_input == C or c:
convert_from_C()
elif user_input == K or k:
convert_from_K()
elif user_input == inch:
convert_from_inch()
elif user_input == ft:
convert_from_ft
elif user_input == yd:
convert_from_yd()
elif user_input == mi:
convert_from_mi()
else:
print("Invalid input.")
print(user_conversion())
Edit: I saw that this was marked as a possible duplicate. The duplicate question doesn't help me, I wasn't trying to make this into a set, I was trying to figure out how I could make an if statement run. The solutions given for my problem aren't like the ones for the other question. However, I'm new to Python so it's entirely possible that I can't make the connections that more experienced people can make. The answers I received here did help me.
Your if construct is wrong. It has to be if user_input == 'F' or user_input == 'f':
Alternatively you can write it shortly as
if user_input in ['F', 'f']:
Or as specified in the comment as
if user_input.lower() == 'f':
It's reading F etc. as variable names. To fix this:
Rewrite them as "F" etc.
Fix your comparisons; or is used for multiple comparisons and can't be used how you're using it. Consider using user_input.casefold() == "f" instead.
You need to quote the value and to fix the test, so
if user_input == F or f:
become
if user_input == "F" or user_input == "f":
same for other lines
You have to have the condition on both sides of the or. So:
def user_conversion():
if user_input == 'F' or user_input == 'f':
convert_from_F()
...
or you could just use
def user_conversion():
if user_input.lower() == 'f':
convert_from_F()
...
You want to make sure you're comparing to a string. So, your if-statement would look like:
if user_input == "F" or user_input == "f":
convert_from_F(user_input)
However, this is somewhat verbose. Instead, try:
if user_input.lower() == "f":
convert_from_F(user_input)
This version converts the value of user_input to its lowercase variant, or leaves it alone if it's already lowercase. You could do something similar by saving user_input.upper() == "F" too.
A shorter and simpler version could be
if user_input in ["F","f"]:
And so on for the other conditions too.
Reason you are getting that error because the symantics of if statement works onuser boolean True or False.
Let us assume the condition on left hand side (LHS) of 'or' and right hand side (RHS) of it to be boolean.
So in your syntax,
LHS is user_input == "F" that returns True or False.
But RHS of or is "f". And here is where problem arise. RHS is not symatically correct.
I am trying to write a program which asks an input of two numbers and then prints the sum, product and average by running it. I wrote a program but it asks an input for 2 numbers everytime i need a sum or average or product. How can I get all 3 at once, just making two inputs once.
sum = int(input("Please enter the first Value: ")) + \
int(input("Please enter another number: "))
print("sum = {}".format(sum))
product = int(input("Please enter the first Value: ")) * \
int(input("Please enter another number: "))
print ("product = {}".format(product))
Use variables to store the input:
first_number = int(input("Please enter the first Value: "))
second_number = int(input("Please enter another number: "))
sum = first_number + second_number
product = first_number * second_number
average = (first_number + second_number) / 2
print('Sum is {}'.format(sum))
print('product is {}'.format(product))
print('average is {}'.format(average))
You need to assign your numbers to variables and then reuse them for the operations.
Example
x = int(input("Please enter the first Value: "))
y = int(input("Please enter another number: "))
print("sum = {}".format(x+y))
print("product = {}".format(x*y))
print("average = {}".format((x+y)/2))
You're going to want to get the numbers first, then do your operation on them. Otherwise you're relying on the user to alway input the same two numbers:
a = int(input("Please enter the first Value: "))
b = int(input("Please enter the second Value: "))
print ("sum = {}".format(a+b))
print ("product = {}".format(a*b))
print ("average = {}".format((a*b)/2))