I've been trying to make a circle area calculator, and I've got the basics. But if the user enters something like 5m, then I see an error. Instead of exiting with an error, I want to return "Enter a Number". Here is my code.
from math import pi
r = float(input("Input the radius of the circle : "))
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
if r==(str):
print("Enter a Number")
This here
if r==(str):
doesn't do what you are expecting.
You want to use string module for this check (Note that this should be done before attempting to convert input to a float):
import string
if set(r).issubset(string.digits)
Or there is a method on string object for this check:
r.isdigit()
But there is a better way:
from math import pi
try:
radius = float(input("Input the radius of the circle : "))
except ValueError:
print("Invalid input, enter a Number!")
else:
print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2))
This shows how to handle invalid inputs. You may want to put this in a loop until you get a valid input.
You can repeatedly ask until a string that can be converted to a float is entered. You can detect failure to convert the string to a float by catching ValueError, which is the exception thrown when a type conversion fails.
while True:
try:
r = float(input("Input the radius of the circle : "))
break
except ValueError:
pass
Do this in place of your current line containing the input call, and get rid of the r == (str) test, which does not actually do anything close to what you are intending.
Also note if you are using Python2 you will need the raw_input function rather than input.
Related
So, I have a homework where I'm assigned to write multiple python codes to accomplish certain tasks.
one of them is: Prompt user to input a text and an integer value. Repeat the string n
times and assign the result to a variable.
It's also mentioned that the code should be written in a way to avoid any errors (inputting integer when asked for text...)
Keep in mind this is the first time in my life I've attempted to write any code (I've looked up instructions for guidance)
import string
allowed_chars = string.ascii_letters + "'" + "-" + " "
allowed_chars.isalpha()
x = int
y = str
z = x and y
while True:
try:
x = int(input("Enter an integer: "))
except ValueError:
print("Please enter a valid integer: ")
continue
else:
break
while True:
try:
answer = str
y = answer(input("Enter a text: "))
except ValueError:
print("Please enter a valid text")
continue
else:
print(x*y)
break
This is what I got, validating the integer is working, but I can't validate the input for the text, it completes the operation for whatever input. I tried using the ".isalpha()" but it always results in "str is not callable"
I'm also a bit confused on the assigning the result to a variable part.
Any help would be greatly appreciated.
Looks like you are on the right track, but you have a lot of extra confusing items. I believe your real question is: how do I enforce alpha character string inputs?
In that case input() in python always returns a string.
So in your first case if you put in a valid integer say number 1, it actually returns "1". But then you try to convert it to an integer and if it fails the conversion you ask the user to try again.
In the second case, you have a lot of extra stuff. You only need to get the returned user input string y and check if is has only alpha characters in it. See below.
while True:
x = input("Enter an integer: ")
try:
x = int(x)
except ValueError:
print("Please enter a valid integer: ")
continue
break
while True:
y = input("Enter a text: ")
if not y.isalpha():
print("Please enter a valid text")
continue
else:
print(x*y)
break
I am creating a massive calculator in python, but I have come a across an issue. I am trying to use the law of cosines to find the angle in an SSS triangle and I cannot see where i am going wrong.
elif qchoice5 == 4:
while True:
try:
print("======================================================================")
a = float(input("what is side a?"))
break
except ValueError:
print("======================================================================")
print("please enter a valid option")
while True:
try:
print("======================================================================")
b = float(input("what is side b?"))
break
except ValueError:
print("======================================================================")
print("Please enter a valid option")
while True:
try:
print("======================================================================")
c = float(input("what is side c?"))
break
except ValueError:
print("======================================================================")
print("Please enter a valid option")
print(((b**2)+(c**2)-(a**2))/(2*a*b))
ans = math.acos((((b**2)+(c**2)-(a**2))/(2*a*b)))
print(ans)
Whenever run it it gives the error
ans = math.degrees(math.acos((((b*b)+(c*c)-(a*a))/(2*a*b))))
ValueError: math domain error
Can anyone give me any pointers on how to get this working?
Without a valid MCVE, I can only do this from a QA standpoint. I see some problems:
You never validate your input. A non-triangle, such as sides of 2, 3, 100, will leave you taking acos of a value out of range.
Your computation is incorrect: b^2 + c^2 - a^2 would need to be divided by 2bc, not 2ab.
FYI, if you're working with integers in Python 2, you'll run into a problem: the division is integer division, and pretty much everything will return acos(0), which is math.pi/2
Try this to correct the last two problems (#2 and the integer division):
ans = math.acos((((b**2)+(c**2)-(a**2))/(2.0*b*c)))
This is a piece of code I encountered in the 7th lecture on introduction to computer science on MIT OCW. This small program gets input for base and height then calculate the hypotenuse with Pythagoras theorem.
For some reason, it couldn't recognize entry of float.
The code is as follows:
#! /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
import math
#Get base
inputOK = False
while not inputOK:
base = input("Enter base: ")
if type(base) == type(1.0):
inputOK = True
else:
print("Error. Base must be a floating point number.")
#Get Height
inputOK = False
while not inputOK:
height = input("Enter height: ")
if type(height) == type(1.0):
inputOK = True
else:
print("Error. height must be a floating point number.")
hyp = math.sqrt(base*base + height*height)
print("Base: " + str(base) + ", height: " + str(height) + ", hypotenuse:" + str(hyp))
This is one of those cases where it is easier to ask for forgiveness than permission. Instead of trying to look at the object and assert it is a float before you act, try to use it as a float and catch any exceptions.
That is, instead of using ifs use:
try:
base = float(base)
inputOK = True
except ValueError as e:
print("Error. Base must be a floating point number.")
This applies similarly to the height value you're trying to get afterwards.
Regardless, input() returns a string so type(input()) will always return str. It is better to cast it to a float (note: ints are also applicable and will be made to floats) and see if it is acceptable than trying to discern its type with if checks.
Mandatory aside, if you even need to check for types, don't use type(obj_a) == type(obj_b), it is arguably always better to use isinstance(obj_a, type(obj_b)).
The code appears to be written for Python 2, not Python 3, as it requires input() to return something other than a string. In Python 3, input() always returns a string, it never applies eval() to that result like Python 2 would.
It has other issues as well, like using type(base) == type(1.0), completely ignoring the availability of the float object and using is to test for identity, and misses out completely on the far superior isinstance() function.
Just use exception handling instead:
while True:
try:
base = float(input("Enter base: "))
break
except ValueError:
print("Error. Base must be a floating point number.")
Note that there is no need for a inputOK boolean either.
So today in science class I thought of making a python script for basic perimeter of a quadrilateral. Later in future I want to expand into circle and other shape but I got stuck in error. Please help.
My code:
print ("This is a program to find the perimeter of a quadrilateral. Input the length and breath and get the desired perimeter")
len = input("What is the length?")
bre = input("What is the breath?")
length = len + len
breath = bre + bre
perimeter = length + breath
print ("The perimeter of the quadrilateral is :" + perimeter)
https://repl.it/xHG
And the output comes funky. If l=2 and b=1 then output comes as 2211.
Also, how do you expand it into different shapes? I was thinking of using if and else options so if choice = circle then execute circle code elif if choice = triangle then execute triangle code. Does anyone have a better idea?
You need to convert you input to an int or float.
len = float(input("What is the length?"))
In your code
len = input("What is the length?")
len is a string, and therefor when you perform len + len you are performing String concatenation
Remember to convert data types
print ("This is a program to find the perimeter of a quadrilateral. Input the length and breath and get the desired perimeter")
len = input("What is the length?")
bre = input("What is the breath?")
len=int(len)
bre=int(bre)
length = len + len
breath = bre + bre
perimeter = length + breath
print ("The perimeter of the quadrilateral is :" + str(perimeter))
In Python 3, input returns a string (this is different in Python 2.x, which may be part of the confusion).
That means that length = len + len is actually performing string concatenation, ie. '2' + '2' = '22'.
Using either int(input("...")) or float(input("...")) will turn them into numbers. (note that both functions will create errors if the user puts in strings that can't be converted to numbers.
I am trying to teach myself Python on code academy and have written the following basic code, which is not working as whatever the input the outcome is 'Please Enter a Valid Number' and I get a message saying "Oops, try again! Make sure area_of_circle takes exactly one input (radius)."
import math
radius = raw_input("Enter the radius of your circle")
def area_of_circle(radius):
if type(radius) == int:
return math.pi() * radius**2
elif type(radius) == float:
return math.pi() * radius**2
else:
return "'Please enter a valid number'"
print "Your Circle area is " + area_of_circle(radius) + " units squared"
The original assignment is:
Write a function called area_of_circle that takes radius as input and returns the area of a circle. The area of a circle is equal to pi times the radius squared. (Use the math.pi in order to represent Pi.)
Errors in your program:
raw_input() returns a string, you've to convert to a float or int first.
Type checking is a bad idea in python
math.pi() is not a function just use math.pi
Use exception handling to convert the string into a number:
import math
radius = raw_input("Enter the radius of your circle: ")
def area_of_circle(radius):
try :
f = float(radius) #if this conversion fails then the `except` block will handle it
return math.pi * f**2 #use just math.pi
except ValueError:
return "'Please enter a valid number'"
print "Your Circle area is {0} units squared".format(area_of_circle(radius))
raw_input() always returns a str. You need to pass it to another type's constructor in order to convert it.
radius_val = float(radius)
You can type cast it while reading the input:
radius = float(raw_input("Enter the radius of your circle"))
Seeing as you want different paths for if the input is a int or float (which doesn't make much sense)
if type(radius) == int:
return math.pi() * radius**2
elif type(radius) == float:
As the interpretation of raw_input()'s string could be either int or float you should evaluate it like so:
import ast
radius = ast.literl_eval(raw_input("Enter the radius of your circle"))
This way you can avoid trying to check if it is a float or int etc...
>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 2.5
<type 'float'>
>>> type(ast.literal_eval(raw_input("Number: ")))
Number: 5
<type 'int'>