When I am executing this code in http://www.pyschools.com/quiz/view_question/s2-q1. It gives error for both the answers... Please help
The questions is:
Write a function to convert temperature from Celsius to Fahrenheit scale.
oC to oF Conversion: Multipy by 9, then divide by 5, then add 32.
Examples
>>> Cel2Fah(28.0)
'82.40'
>>> Cel2Fah(0.00)
'32.00'
My Answer
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
x = 9.00
y = 5.00
z = 32.00
a = temp * x
a = a / y
a = a + z
return(a)
At the top it says:
# Note: Return a string of 2 decimal places.
You are not returning a string. You are returning a value of type float.
Since this looks like homework, I'll let you figure out how to fix this (hint: use the string formatting operator).
Return this instead.
return '%.2f' %a
change your return statement to read
return '%.2f' %a
There is nothing wrong syntactically with that code. It should work if you pass a number as parameter. It won't work if you pass anything but a number.
def Cel2Fah(temp):
cel=(round((((temp*9)/5) +32),2))
return '%.2f' %cel
print Cel2Fah(36.9)
print Cel2Fah(29.0)
Related
for example:
((360/2)*x)/2 # output : 90.0*x
# I want the output to be : 90*x
int(((360/2)*x)/2) # TypeError
Is there any function that I can use to convert 90.0x to 90x
You can use xreplace to go through your expression and make the changes:
>>> eq
2.0*x
>>> eq.xreplace({i: int(i) for i in eq.atoms(Float) if i == int(i)})
2*x
Thanks to #OscarBenjamin
nsimplify(((360/2)*x)/2) # output : 90*n
The aim is to return the middle letter of a string, or " " if the string's even. I'm failing to see why my code doesn't work. Any sort of clarification would be great, thanks!
def mid(ml):
x=len(ml)
y=x+1
z=y/2
if isinstance(z,int)==True:
return (ml[z-1])
else:
return (" ")
print (mid("abc"))
/ doesn't return an int; even if the number it returns can be represented as one:
>>> 4 / 2
2.0 # A float
It would be better to explicitly check if the number is even or not:
# Read as: "If z is odd", or, "If division of z by 2 has a remainder of 1"
if z % 2 == 1:
return ml[z-1]
else:
return " "
This behavior occurs, because the / operator returns a float. Although the smarter way to solve this would be the use of the modulo operator, if you want to stick to your code, could use the is_integer() method of float like this:
def mid(ml):
x=len(ml)
y=x+1
z=y/2
if z.is_integer():
return (ml[int(z)-1])
else:
return (" ")
print (mid("abc"))
Better way to do it:
def mid(ml):
return ml[len(ml)//2] if len(ml) % 2 else ""
Following the answer from #Carcigenicate above you can try following code:
def mid(ml):
x=len(ml)
y=x+1
z=y/2
return (ml[int(z-1)])
print (mid("abc"))
I wish to find a way to achieve the following: With the likes of 5.0, return 5. With the likes of 5.1, which cannot equal any integer, return Error.
Currently I use int() together with an "if integer != float". However this has problems, for instance I won't be able to tell whether the inequality was caused by the likes of 5.1 or the likes of 1111111111111111.0(and even larger numbers).
Also this is extremely troublesome compared with a potential, simple, one-line command. So is there a command in Python that does this?
Float objects in Python have an is_integer() predicate.
def strict_int(x):
if x.is_integer():
return int(x)
raise ValueError
Note that int objects do not have this method. You'll get an attribute error if you try to call this on an int.
If you wanted some error value instead of an exception, you can use a one-liner like this
int(x) if x.is_integer() else 'Error'
Simply use math as suggested in this answer by #Anthony V like this:
>>> frac, whole = math.modf(5.0)
>>> if frac ==0.0:
... print("this is a whole")
... else:
... print("this is not whole and should return the Error")
This should work easily.
I'm not sure whether there's a more idiomatic way to do this, but intuitively, you can just compare the value of the int and the float and return only when they are equal.
That is
def weird_cast(my_float):
if int(my_float) == my_float:
return int(my_float)
return None # or some error
def return_int(a):
if int(a)==a:
print(int(a)) #you can store the integer value in separate variable #also b = int(a)
#instead of using print you can use return b or int(a)
else:
print('Error') #or you can use return 'Error'
a = 5.0
return_int(a)
Maybe another easier way is to minus with the round down number with itself.
if the remainder is more than 0.0 and less than 1.0, then we can call it a float otherwise integer
def IntegerSanityCheck ( num ):
remainder = abs ( round ( num ) - num )
if ( remainder > 0.0 ) and ( remainder < 1.0 ):
print "Float"
else:
print "Integer"
or you can use math as suggested by user2906838
I'm a noobie, learning to code and i stumbled upon an incorrect output while practicing a code in python, please help me with this. I tried my best to find the problem in the code but i could not find it.
Code:
def compare(x,y):
if x>y:
return 1
elif x==y:
return 0
else:
return -1
i=raw_input("enter x\n")
j=raw_input("enter y\n")
print compare(i,j)
Output:
-> python python.py
enter x
10
enter y
5
-1
The output that i had to receive is 1 but the output that i receive is -1. Please help me with the unseen error in my code.
Thank you.
raw_input returns a string always.
so you have to convert the input values into numbers.
i=raw_input("enter x\n")
j=raw_input("enter y\n")
print compare(i,j)
should be
i=int(raw_input("enter x\n"))
j=int(raw_input("enter y\n"))
print compare(i,j)
Your issue is that raw_input() returns a string, not an integer.
Therefore, what your function is actually doing is checking "10" > "5", which is False, therefore it falls through your if block and reaches the else clause.
To fix this, you'll need to cast your input strings to integers by wrapping the values in int().
i.e.
i = int(raw_input("enter x\n")).
Use the inbuilt cmp builtin function.
>>> help(cmp)
Help on built-in function cmp in module __builtin__:
cmp(...)
cmp(x, y) -> integer
Return negative if x<y, zero if x==y, positive if x>y.
So your function will look like this.
>>> def compare(x,y):
... return cmp(x,y)
...
>>>
Then get two variables using raw_input() which returns string, So If you are typing two numbers with a blankspace in the middle, splitting based on blank space will save two numbers in these x and y, and then apply map function which takes two parameters, one int function and the sequence which is nothing but a list created out of split().
>>> x,y = map(int, raw_input().split())
3 2
Now Comparing the x and y, Since x = 3 and y =2, Now since as per the documentation of cmp(), It Return negative if xy.
>>> compare(x,y)
1
>>> compare(y,x)
-1
>>> compare(x-1,y)
0
>>>
Is there any other way to convert string to int? I need to do this without using this:
x = '345'
y = int(x)
Then it should work like this:
>>> function('456') + 5
461
You could use eval, but int works just fine for what you are trying.
>>> eval('123') + 5
128
def not_int(s):
if s.isdigit():
return eval(s)
raise ValueError("invalid literal: %r" % (s,))
Update: as posted in the comments, this only works for positive integers. It can be made to work with negative literals, but it gets more contrived for nothing, because int does exist! By the way, this does not even handle bases other than 10.
The following works better, and does not actually use int ;-)
def not_int(s):
return eval("int(%r)" % (s,))