Nestes if's in python not working and math module faulty - python

in this code i first ask the user for the trigonometric function and then ask for the angle in radians or degrees. according to the code, the console should print error, but on running the code, the first if statements accept any input as true.the final coputed value is also worng. please suggest what to do and any other relevant changes that can be made to the code.
from math import *
trigFunc = str(input("What function do you want to use? Sine, Cosine or Tangent: "))
if trigFunc.lower == "sine" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.sin(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.sin(radAngle))
else:
print("error")
elif trigFunc.lower == "cosine" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.cos(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.cos(radAngle))
else:
print("error")
elif trigFunc.lower == "tangent" :
radOrDeg = str(input("Do you want to input the value as radians or degrees? "))
if radOrDeg.lower == "radians" :
angle = int(input("Please input the value of the angle: "))
print(math.tan(angle))
elif radOrDeg.lower == "degrees" :
angle = int(input("Please input the value of the angle: "))
radAngle = int(math.radians(angle))
print(math.tan(radAngle))
else:
print("error")
else:
print("ERROR, the function cannot be used")
input("press enter to exit")

.lower is a function and you need to call it to return a string. Right now you are comparing a function to a string which will return False.
Change trigFunc.lower to trigFunc.lower().
https://docs.python.org/3/library/stdtypes.html#str.lower

There are several errors in your code. Here are the things I changed to get your code working:
Use trigFunc.lower() instead of trigFunc.lower. You need to call the method to get the result you desire.
Use import math instead of from math import *, since you refer to math library throughout.
Use math.radians(int(angle)) instead of int(math.radians(angle)), since math.radians does not take a string as an input.

Related

Why does the following code not follow the specified order?

I want it to say welcome, ask for the user input (a,b,c), validate the user input and if the validation returns that the input is reasonable then carry out the quadratic formula on a,b,c. I suspect the problem is in the while-loop. The program just welcomes, asks for input then says welcome again and so on.
from math import sqrt
def quadratic_formula(a,b,c):
a=float(a) #The quadratic formula
b=float(b)
c=float(c)
x1_numerator = -1*b + sqrt((b**2)-4*(a*c))
x2_numerator = -1*b - sqrt((b**2)-4*(a*c))
denominator = 2*a
x1_solution = x1_numerator/denominator
x2_solution = x2_numerator/denominator
print("x= "+str(x1_solution)+" , x= "+str(x2_solution))
def number_check(a,b,c,check): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check == False
else:
check == True
check = False
while check == False:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
number_check(a,b,c,check)
else:
quadratic_formula(a,b,c)
You are correct in your suspicion. You have a problem in your while loop. does not work the way your code assumes.
Instead you need to write something like:
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
check = False
else:
check = True
return check
check = False
print("Welcome to the Quadratic Equation Calculator!")
while check == False:
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
check = number_check(a,b,c)
quadratic_formula(a,b,c)
Note, that in addition to changing the while loop you also need to update number_check as input parameters are not updated in calling scope. Instead the function has to explicitly return the updated value.
Try using return, not attempting to modify a global variable.
There's a way to use global variables (see global statement), but it's not necessary for this code.
The check variable itself isn't really necessary, though
def number_check(a,b,c):
a=float(a)
b=float(b)
c=float(c)
return (b**2)-4*a*c >= 0 # return the check
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if not number_check(a,b,c):
print("The values you have entered result in a complex solution. Please check your input.")
else:
break # getting out of the loop
There are two problems with the way you're using the check variable in the number_check function.
First, you're not assigning new values to it, because you're using == (which tests equality) rather than =.
But also, since it's a parameter variable, it's local to the function. So assigning it inside the function does not modify the global variable that you test in the while loop. Rather than use a global variable, you can simply test the result of number_check directly, and use break when you want to end the loop.
If you make this change, you need to move the call to quadratic_formula out of the else: clause, because that's only executed when the while condition fails, not when we end the loop with break.
def number_check(a,b,c): #carries out a check
a=float(a)
b=float(b)
c=float(c)
if (b**2)-4*a*c < 0:
print("The values you have entered result in a complex solution. Please check your input.")
return False
else:
return True
while True:
print("Welcome to the Quadratic Equation Calculator!")
a = input("Please enter the x^2 coefficient: ")
b = input("Please enter the x coefficient: ")
c = input("Please enter the constant: ")
if number_check(a,b,c):
break
quadratic_formula(a,b,c)

How to make my code ask the user for input again python

I'm creating a python program that gives you the area for any shape you enter and I want to know how to make the program return to asking the user what shape they want
import math
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print"Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again"
#Code that returns to first question here?
Also if possible, since the code is very long because it is just repeating the if statements as elif statements for new shapes, is there a way to shorten it so it isn't lots of elif statements.
Thanks
import math
done = 'n'
while done == 'n':
user_choice = input("Choose a shape")
if user_choice == "rectangle" or "square":
a = input("enter your length in centimeters here")
b = input("enter your width in centimeters here")
area = int(a) * int (b)
print(area, "cm²")
else
print("Sorry, you may have made a spelling error, or have chose a shape that we cannot calculate. Please try again")
done = input("Done? (Y/N)").lower()

How do i have my python program restart to a certain line?

print ("Enter the object you are tyring to find.")
print ("1 = Radius")
print ("2 = Arch Length")
print ("3 = Degree")
print ("4 = Area")
x = int(input("(1,2,3,4):"))
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
if x == 2:
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
I am making a basic math program but i want it to repeat infinitely. This is not the complete code but i want to do the same thing for the rest of the "if" statements. i want it to end after each function is completed and repeat back to the first line. thanks!
Put a
while True:
at the spot you want to restart from; indent all following lines four spaces each.
At every point in which you want to restart from just after the while, add the statement:
continue
properly indented also, of course.
If you also want to offer the user a chance to end the program cleanly (e.g with yet another choice besides the 4 you're now offering), then at that spot have a conditional statement (again properly indented):
if whateverexitcondition:
break
You will need to add a way to let the user quit and break the loop but a while True will loop as long as you want.
while True:
# let user decide if they want to continue or quit
x = input("Pick a number from (1,2,3,4) or enter 'q' to quit:")
if x == "q":
print("Goodbye")
break
x = int(x)
if x == 1:
print ("You are finding the Radius.")
ra = int(input("Enter the arch length: "))
rd = int(input("Enter the degree: "))
rr = ra/math.radians(rd)
print ("The Radius is:",rr)
elif x == 2: # use elif, x cannot be 1 and 2
print ("You are finding the Arch Length.")
sr = int(input("Enter the radius: "))
sd = int(input("Enter the degree: "))
ss = math.radians(sd)*sr
print ("The Arch Length is:",ss)
elif x == 3:
.....
elif x == 4:
.....
If you are going to use a loop you can also verify that the user inputs only valid input using a try/except:
while True:
try:
x = int(input("(1,2,3,4):"))
except ValueError:
print("not a number")
continue

Python elif statement not working

I don't understand why my following piece of code does not work:
running = True
name = input("Whats your name?: ")
print ("Hi", name, "Which Program Would You Like to Use")
print ("1. Upper to Lower Case converter")
print ("2. Lower to Upper Case converter")
print ("3. Character Count")
x = input("Enter the Number: ")
if x==1:
print ("You have selected the Upper to Lower Case converter")
y = input("Enter the text you would like converted: ")
print (y.lower())
elif x==2:
pass print ("You have selected the Lower to Upper Case converter")
z = input("Enter the text you would like converted: ")
print (z.lower()
running = False
you need here:
x = int(input("Enter the Number: "))
input takes as string
if x==1: you were comparing string with integer
You probably are missing a closing bracket here: print (z.lower()
In this statement if x==1:, you are comparing x, which is a string, with an int, and, as you already might have understood, you cannot do it.
One solution for this problem is to convert x to and int directly when you get the input from the user:
x = int(input("Enter a number: "))
Or comparing the x with a string number:
if x== "1":
# do stuff
It depends of course in what you want to do.

Integrating a for loop into an if statement

This is kind of a double-barreled question, but it's got me puzzled. I currently have the following code:
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
Now, I'd like to have some kind of loop (I'm guessing it's a for loop, but I'm not entirely sure) so that after a function has been completed, it'll return to the top, so the user can enter a new function number and do a different equation. How would I do this? I've been trying to think of ways for the past half hour, but nothing's come up.
Try to ignore any messiness in the code... It needs some cleaning up.
It's better to use a while-loop to control the repetition, rather than a for-loop. This way the users aren't limited to a fixed number of repeats, they can continue as long as they want. In order to quit, users enter a value <= 0.
from __future__ import division
import math
function = int(raw_input("Type function no.: "))
while function > 0:
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer = b/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
print 'Enter a value <= 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
You can tweak this (e.g., the termination condition) as needed. For instance you could specify that 0 be the only termination value etc.
An alternative is a loop that runs "forever", and break if a specific function number is provided (in this example 0). Here's a skeleton/sketch of this approach:
function = int(raw_input("Type function no.: "))
while True:
if function == 1:
...
elif function == 2:
...
elif function == 0:
break # terminate the loop.
print 'Enter 0 for function number to quit.'
function = int(raw_input("Type function no.: "))
Note: A for-loop is most appropriate if you are iterating a known/fixed number of times, for instance over a sequence (like a list), or if you want to limit the repeats in some way. In order to give your users more flexibility a while-loop is a better approach here.
You simply need to wrap your entire script inside a loop, for example:
from __future__ import division
import math
for _ in range(10):
function = int(raw_input("Type function no.: "))
if function == 1:
a = float(raw_input ("Enter average speed: "))
b = float(raw_input ("Enter length of path: "))
answer= float(b)/a
print "Answer=", float(answer),
elif function == 2:
mass_kg = int(input("What is your mass in kilograms?" ))
mass_stone = mass_kg * 2.2 / 14
print "You weigh", mass_stone, "stone."
else: print "Please enter a function number."
This will run your if statement 10 times in a row.
I'd try this:
while True:
function = ...
if function == 0:
break
elif ...

Categories

Resources