Can't convert Celsius to Fahrenheit - python

Here's my code:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = float((temp*9/5)+32)
fah_two = (%.2f) % fah
fah_string = str(fah_two)
return fah_string
Here's what I should get:
>>> Cel2Fah(28.0)
'82.40'
>>> Cel2Fah(0.00)
'32.00'
But I get an error:
Traceback (most recent call last):
File "Code", line 4
fah_two = (%.2f) % fah
^
SyntaxError: invalid syntax
I'm not sure what is going on...
This doesn't seem to work either for some reason:
# Note: Return a string of 2 decimal places.
def Cel2Fah(temp):
fah = temp*9/5+32
fah_cut = str(fah).split()
while len(fah_cut) > 4:
fah_cut.pop()
fah_shorter = fah_cut
return fah_shorter

It looks like you want:
fah_two = "%.2f" % fah
The result of the % formatting operator is a string, so you don't need fah_string because fah_two is already a string.

sucmac:~ ajung$ cat x.py
def toF(cel):
return '%.2f' % (cel * 1.8 +32)
print toF(0)
print toF(50)
print toF(100)
sucmac:~ ajung$ python x.py
32.00
122.00
212.00

Further, I think temp * 9 / 5 should be temp * 9 / 5.0.

Related

Rounding to 2 decimal places in Python

This isn't a duplicate because I have checked everything before this post on this site. I think I have managed to do the first two bullet points. The first one I will do through a string but I am willing to change that if you know another way. The 2nd one is using comma seperators for the $'s. So I will use a float but once again am willing to change if better way is found.
But I am stuck.
And the "print("%.2f") % str) is something I found but I need work on rounding to two decimal spaces and the last bullet point.
Code:
import random
def random_number():
random_dollars = random.uniform(1.00, 10000.00)
print(round(random_dollars, 2))
print("%.2f") % str
print(random_number())
Shell:
C:\Users\jacke\PycharmProjects\ASLevelHomeworkWeek18\venv\Scripts\python.exe C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py 6567.62 Traceback (most recent call last): %.2f File
C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 10, in <module> print(random_number()) File
C:/Users/jacke/PycharmProjects/ASLevelHomeworkWeek18/ASLevelHomeworkWeek18.py", line 7, in random_number print("%.2f") % str TypeError: unsupported operand type(s) for %: 'NoneType' and 'type' Process finished with exit code 1
You can format currency like this:
def random_number():
random_dollars = random.uniform(1, 10000)
result = '$ {:0>9}'.format('{:,.2f}'.format(random_dollars))
print(result)
{:0>10} means: pad string left to width 9 with 0's.
{:,.2f} rounds to two decimal places (.2f) and adds a comma as thousands-separator.
Just one side note: by using random.uniform(1, 10000) most of your numbers will be large (>1000), if you want to test your script with small amounts you could use random_dollars = 10**random.uniform(0, 4) instead:
def random_number():
random_dollars = 10**random.uniform(0, 4)
result = '$ {:0>9}'.format('{:,.2f}'.format(random_dollars))
print(result)
If I get what you are saying you want to round a number to 2 decimal places. Here is how I would do it.
import random
def random_number():
random_dollars = random.uniform(1, 10000)
split = str(random_dollars).split(".")
if (len(split) == 2 ):
if (len(split[1]) == 1 ):# checks if 1 digit after decimal place
answer = split[0] + ".0"
split[1] = str(int(int(split[1]) / (10 ** (len(split[1]) - 3) )))
# Gets 3 decimal places
if int(split[1][-1:]) => 5: #Checks if last digit is above or equal to 5
split[1] = int(split[1][:-1])
split[1] += 1
else:
split[1] = int(split[1][:-1])
answer = split[0] + '.' + str(split[1])
else:
answer = split[0] + ".00"
print(answer)
random_number()
This makes it so if the random number is somehow 100 it will add 2 zeros. If the number is like 100.1 it will add one zero. It will also round it.
def random_number():
random_dollars = random.uniform (1.00, 10000.00)
n = round(random_dollars,2)
bd, d = str(n).split('.')
if len(d) == 1:
n = bd + "." + d + '0'
return n
else:
return n
for i in range(1, 20):
print(random_number())
7340.55
7482.70
3956.81
3044.50
4108.57
4864.90
235.00
9831.98
960.97
1172.28
5221.31
3663.50
5410.50
3448.52
8288.13
293.48
1390.68
9216.15
6493.65
TL;DR: you have to put the % directly after the string and you have to put a real variable there, not the type str
from the last line of your error message you can see that the problem is the % operator. You can also see that it tried to do the operation with two objects of types 'NoneType' and 'type'. Since you put the entire print statement in front of the % and print returns None (which is of type NoneType), the first operand is of type NoneType. then, the second operand is the type str, which is, as just said, a type. You can fix this by moving the % operator after the string and replacing str with your variable random_dollars since that is what you want to insert into the string.
import random
def random_number():
random_dollars = random.uniform(1.00, 10000.00)
print(round(random_dollars, 2))
# this:
print("%.2f" % random_dollars)
print(random_number())

python script giving typerror on nested if statements

I'm trying to write a simple multiplication program first time in python and I get the following error, not sure why. My code is also posted below.
#!/usr/bin/env python
from math import *
def main():
multiplier = raw_input('multiplier?')
multiplicand = raw_input('multiplicand?')
print (recursive(multiplier, multiplicand))
def recursive(multiplier, multiplicand):
if (multiplier == 0):
answer = 0
if (multiplier == 1):
answer = multiplicand
if ((multiplier > 1) & ((multiplier % 2) == 0)):
answer = recursive((multiplier/2), (multiplicand*2))
if ((multiplier > 1) & ((multiplier % 2) == 1)):
answer = (multiplicand + (recursive((multiplier/2), (multiplicand*2))))
return answer
main()
Error:
multiplier?5
multiplicand?5
Traceback (most recent call last):
File "./multiplication.py", line 20, in <module>
main()
File "./multiplication.py", line 7, in main
print (recursive(multiplier, multiplicand))
File "./multiplication.py", line 14, in recursive
if ((multiplier > 1) & ((multiplier % 2) == 0)):
TypeError: not all arguments converted during string formatting
Multiplier is a string so the modulus operator is attempting to put a value in the string here like you'd see in a string string = "%s%d...". Hence the conversion error. Instead of a doing a mod operation. You need to convert the variable multiplier to an int (or float).
multiplier is being passed as a string, not a number. This is because raw_input() always returns a string. To convert it, do float(raw_input()).
The error is because the % operator returns the remainder for two numbers, but your string isn't a valid format string.
7 % 2 == 1
but it does string formatting when the first one is a string
'%d dogs ' % 2 == '2 dogs'

Selecting part of a string for calculations (python)

I'm working on a for-fun-project that I will be doing some calculations with and I need some help.
one module from my program:
def ARK(rawArk):
refArk = rawArk/200
arkTrit = refArk*300
arkMeg = refArk*333
arkZyd = refArk*166
print "Totals from your Arkonor:"
print "Tritanium=", arkTrit
print "Megacyte=", arkMeg
print "Zydrine=", arkZyd
return arkTrit, arkMeg, arkZyd
Right now it is just doing simple division and multiplication. What I want to do is be able to do this with remainders.
So if 'refArk = rawArk/200' gives a total of 16.3, I want to be able to separate the 16.0 and the 0.3 and use them as separate variables for separate calculations.
So far:
def ARK(rawArk):
refArk = float(rawArk/200)
arkTrit = refArk*300
arkMeg = refArk*333
arkZyd = refArk*166
print "Totals from your Arkonor:"
print "Tritanium=", arkTrit
print "Megacyte=", arkMeg
print "Zydrine=", arkZyd
strval = str(refArk)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)
print whole
print frac
return arkTrit, arkMeg, arkZyd
def main():
rawArk=input("How much Arkonor?")
ARK(rawArk)
return
main()
USING '450' as my input value
returns
How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600.0
Megacyte= 666.0
Zydrine= 332.0
2.0
0.0
The 2.0 is right but the 0.0 should be 0.25
Removing the float() from the 'rawArk/200' spits out an error:
How much Arkonor?450
Totals from your Arkonor:
Tritanium= 600
Megacyte= 666
Zydrine= 332
Traceback (most recent call last):
File "E:\eve stuff\Calculator\test.py", line 23, in <module>
main()
File "E:\eve stuff\Calculator\test.py", line 20, in main
ARK(rawArk)
File "E:\eve stuff\Calculator\test.py", line 11, in ARK
head,tail = strval.split(".")
ValueError: need more than 1 value to unpack
Numerically
val1 = 22.0
val2 = 7.0
whole,frac = divmod(val1,val2)
frac = frac/val1
Kind of a hack but with strings
val = 22.0/7.0
strval = str(val)
head,tail = strval.split(".")
whole = float(head)
frac = float("."+tail)
either way
>>> frac
0.14285714286000001
>>> whole
3.0
May be first use round function then use split
refArk = refArk.split(".")
Why not just do:
intpart=int(variable)
decimalpart=variable-intpart
I would guess this to be more efficient than casting to a string and then splitting.
The following session at the IDLE should show how to solve your problem.
>>> lis=str(refArk).split('.')
>>> lis[-1]='.'+lis[-1]
>>> map(float,lis)
[16.0, 0.3]

drop trailing zeros from decimal

I have a long list of Decimals and that I have to adjust by factors of 10, 100, 1000,..... 1000000 depending on certain conditions. When I multiply them there is sometimes a useless trailing zero (though not always) that I want to get rid of. For example...
from decimal import Decimal
# outputs 25.0, PROBLEM! I would like it to output 25
print Decimal('2.5') * 10
# outputs 2567.8000, PROBLEM! I would like it to output 2567.8
print Decimal('2.5678') * 1000
Is there a function that tells the decimal object to drop these insignificant zeros? The only way I can think of doing this is to convert to a string and replace them using regular expressions.
Should probably mention that I am using python 2.6.5
EDIT
senderle's fine answer made me realize that I occasionally get a number like 250.0 which when normalized produces 2.5E+2. I guess in these cases I could try to sort them out and convert to a int
You can use the normalize method to remove extra precision.
>>> print decimal.Decimal('5.500')
5.500
>>> print decimal.Decimal('5.500').normalize()
5.5
To avoid stripping zeros to the left of the decimal point, you could do this:
def normalize_fraction(d):
normalized = d.normalize()
sign, digits, exponent = normalized.as_tuple()
if exponent > 0:
return decimal.Decimal((sign, digits + (0,) * exponent, 0))
else:
return normalized
Or more compactly, using quantize as suggested by user7116:
def normalize_fraction(d):
normalized = d.normalize()
sign, digit, exponent = normalized.as_tuple()
return normalized if exponent <= 0 else normalized.quantize(1)
You could also use to_integral() as shown here but I think using as_tuple this way is more self-documenting.
I tested these both against a few cases; please leave a comment if you find something that doesn't work.
>>> normalize_fraction(decimal.Decimal('55.5'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55.500'))
Decimal('55.5')
>>> normalize_fraction(decimal.Decimal('55500'))
Decimal('55500')
>>> normalize_fraction(decimal.Decimal('555E2'))
Decimal('55500')
There's probably a better way of doing this, but you could use .rstrip('0').rstrip('.') to achieve the result that you want.
Using your numbers as an example:
>>> s = str(Decimal('2.5') * 10)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
25
>>> s = str(Decimal('2.5678') * 1000)
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
2567.8
And here's the fix for the problem that #gerrit pointed out in the comments:
>>> s = str(Decimal('1500'))
>>> print s.rstrip('0').rstrip('.') if '.' in s else s
1500
Answer from the Decimal FAQ in the documentation:
>>> def remove_exponent(d):
... return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5.00'))
Decimal('5')
>>> remove_exponent(Decimal('5.500'))
Decimal('5.5')
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')
Answer is mentioned in FAQ (https://docs.python.org/2/library/decimal.html#decimal-faq) but does not explain things.
To drop trailing zeros for fraction part you should use normalize:
>>> Decimal('100.2000').normalize()
Decimal('100.2')
>> Decimal('0.2000').normalize()
Decimal('0.2')
But this works different for numbers with leading zeros in sharp part:
>>> Decimal('100.0000').normalize()
Decimal('1E+2')
In this case we should use `to_integral':
>>> Decimal('100.000').to_integral()
Decimal('100')
So we could check if there's a fraction part:
>>> Decimal('100.2000') == Decimal('100.2000').to_integral()
False
>>> Decimal('100.0000') == Decimal('100.0000').to_integral()
True
And use appropriate method then:
def remove_exponent(num):
return num.to_integral() if num == num.to_integral() else num.normalize()
Try it:
>>> remove_exponent(Decimal('100.2000'))
Decimal('100.2')
>>> remove_exponent(Decimal('100.0000'))
Decimal('100')
>>> remove_exponent(Decimal('0.2000'))
Decimal('0.2')
Now we're done.
Use the format specifier %g. It seems remove to trailing zeros.
>>> "%g" % (Decimal('2.5') * 10)
'25'
>>> "%g" % (Decimal('2.5678') * 1000)
'2567.8'
It also works without the Decimal function
>>> "%g" % (2.5 * 10)
'25'
>>> "%g" % (2.5678 * 1000)
'2567.8'
I ended up doing this:
import decimal
def dropzeros(number):
mynum = decimal.Decimal(number).normalize()
# e.g 22000 --> Decimal('2.2E+4')
return mynum.__trunc__() if not mynum % 1 else float(mynum)
print dropzeros(22000.000)
22000
print dropzeros(2567.8000)
2567.8
note: casting the return value as a string will limit you to 12 significant digits
Slightly modified version of A-IV's answer
NOTE that Decimal('0.99999999999999999999999999995').normalize() will round to Decimal('1')
def trailing(s: str, char="0"):
return len(s) - len(s.rstrip(char))
def decimal_to_str(value: decimal.Decimal):
"""Convert decimal to str
* Uses exponential notation when there are more than 4 trailing zeros
* Handles decimal.InvalidOperation
"""
# to_integral_value() removes decimals
if value == value.to_integral_value():
try:
value = value.quantize(decimal.Decimal(1))
except decimal.InvalidOperation:
pass
uncast = str(value)
# use exponential notation if there are more that 4 zeros
return str(value.normalize()) if trailing(uncast) > 4 else uncast
else:
# normalize values with decimal places
return str(value.normalize())
# or str(value).rstrip('0') if rounding edgecases are a concern
You could use :g to achieve this:
'{:g}'.format(3.140)
gives
'3.14'
This should work:
'{:f}'.format(decimal.Decimal('2.5') * 10).rstrip('0').rstrip('.')
Just to show a different possibility, I used to_tuple() to achieve the same result.
def my_normalize(dec):
"""
>>> my_normalize(Decimal("12.500"))
Decimal('12.5')
>>> my_normalize(Decimal("-0.12500"))
Decimal('-0.125')
>>> my_normalize(Decimal("0.125"))
Decimal('0.125')
>>> my_normalize(Decimal("0.00125"))
Decimal('0.00125')
>>> my_normalize(Decimal("125.00"))
Decimal('125')
>>> my_normalize(Decimal("12500"))
Decimal('12500')
>>> my_normalize(Decimal("0.000"))
Decimal('0')
"""
if dec is None:
return None
sign, digs, exp = dec.as_tuple()
for i in list(reversed(digs)):
if exp >= 0 or i != 0:
break
exp += 1
digs = digs[:-1]
if not digs and exp < 0:
exp = 0
return Decimal((sign, digs, exp))
Why not use modules 10 from a multiple of 10 to check if there is remainder? No remainder means you can force int()
if (x * 10) % 10 == 0:
x = int(x)
x = 2/1
Output: 2
x = 3/2
Output: 1.5

How do I prevent spaces when using Python?

How would I remove the spaces after the R in the following line?
>>>print "4/3 =", 4 / 3, "R", 4 % 3
I want the result to look exactly like this:
4/3 = 1 R1
I appreciate any time anyone takes to answer this question.
Use str.format:
>>> a=4
>>> b=3
>>> print "{}/{} = {} R{}".format(a, b, a//b, a%b)
4/3 = 1 R1
If you are using an older version of Python which doesn't support str.format then you can use the % operator:
>>> print "%d/%d = %d R%d"%(a, b, a//b, a%b)
4/3 = 1 R1
Note also that since Python 2.2 you should use // for integer division, and from Python 3 onwards, you must use //.
You should use formatting.
print "4/3 = %d R%d" % (4 / 3, 4 % 3)
or even better, with string.format:
print "4/3 = {} R{}".format(4 / 3, 4 % 3)
You should use string format
print "4/3 =%d R%d" % (4 / 3, 4 % 3)

Categories