Python Function inputs - python

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'>

Related

How can I make sure that the error i created is only given when letters are typed but not deciamls?

if CF == '2':
#taking temperature in fahrenheit
while True:
try:
fahrenheit = input("Enter temperature degree in fahrenheit:")
except ValueError:
print("Error: Please use numbers")
continue
if fahrenheit.isdigit():
break
else:
print("Error: Please use numbers")
continue
fahrenheit = float(fahrenheit)
#Coversion formula
conv_for = (fahrenheit - 32) * 5/9
#calculation for celsius
celsius = conv_for
print("%02f degrees in fahrenheit is equal to %02f degrees in celsius" %(fahrenheit,celsius))
if "%02f degrees in fahrenheit is equal to %02f degrees in celsius" %(fahrenheit,celsius) ==\
"%02f degrees in fahrenheit is equal to %02f degrees in celsius" %(fahrenheit,celsius):
input('Press ENTER to exit')
When I run the script it gives me the error when I type letters, as expected, but when I type any number with a decimal point it also gives me the error. How can I fix this? Thank you. The error is meant to be there for letters but just not for any numbers
isdigit() returns True only if all digits are numbers, thus a floating point number string will return False.
You can simply move fahrenheit = float(fahrenheit) inside the try-except and remove the else and it will work
isdigit() returns True only if all digits are numbers, thus a floating point number string will return False.
so you can use this also:
if (isinstance(fahrenheit, int)) or (isinstance(fahrenheit, float)):
Just replace the
if fahrenheit.isdigit():
with
if fahrenheit.replace('.', '', 1).isdigit():
This should do the job with minimal change in your code.

Python If/else statements with math

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.

Python 3 recognizing float with type()

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.

Perimeter of a quadrilateral and other shapes

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.

TypeError: can't multiply sequence by non-int of type 'float' 3.3

Ok I have edited the code to where it would hopefully work but I get the TypeError: can't multiply sequence by non-int of type 'float'.
Heres the code that I have:
uTemp = input("Enter Temperature Variable: ")
cOrF = input("Do you want C for celcius, or F for Farehnheit?: ")
if cOrF:
F = 1.8 * uTemp + 32
The error is telling you that you can't multiply uTemp, a string, by a floating-point number (1.8). Which makes perfect sense, right? What is eight tenths of a string? Convert uTemp to a float:
uTemp = float(input("Enter Temperature Variable: "))
Your next problem is that cOrF is treated as a Boolean (true/false) value, which means F will be calculated if the user enters anything at that prompt since all non-empty strings are truthy in Python. So instead you would write:
if cOrF == "F":
F = 1.8 * uTemp + 32
input() returns a string in python 3.x.
Convert it to float (or to int - depends on your needs):
uTemp = float(input("Enter Temperature Variable: "))

Categories

Resources