Corjava
Corjava

Reputation: 340

Arithmetic using decimals python

I save a number inside a variable and then I want to to multiply that number by 0.5. But, it seems to change the type of the variable, is my variable being changed into a double or something of the sort? (I'm just beginning to learn python)

CODE & ERROR:

  a = pickAFile()
  b = makePicture(a)
  c = getWidth(b)
  d = getHeight(b)
  e = (c * 0.5)
  f = (d * 0.5)
--> (problem line) newPicture = makeEmptyPicture(e,f)

error: An attempt was made to call a function with a parameter of an invalid type. This means that you did something such as trying to pass a string to a method that is expecting an integer.

Upvotes: 0

Views: 141

Answers (4)

Brian English
Brian English

Reputation: 466

Python variables do not have a set data type, so yes, Python can/will change the data type of your variable based on what you're assigning to it.

You can see the current type of the variable with:

type(var_name)

To be able to specifically answer your question, show us the definition of makeEmptyPicture().

Upvotes: 1

sabbahillel
sabbahillel

Reputation: 4425

The examples of makeEmptyPicture that I have been able to find seem to require an integer width and height. as a result, you should either use

makeEmptyPicture(int(e), int(f))

or round up using

makeEmptyPicture(int(math.ceil(e)), int(math.ceil(f)))

Note that math.ceil returns a float so you need to force it to an int in the call.

Upvotes: 2

awesomeshreyo
awesomeshreyo

Reputation: 15

you should use floats:

    e=float(whatever you want inside)

this way it will allow python to use decimals otherwise it rounds them. You should use floats instead of of integers for your other variables too, of you want to make them decimals.

Upvotes: 0

David Young
David Young

Reputation: 10791

This is because when you multiply an odd integer by 0.5, you will get a non-integer result. You probably want to either round up or round down using math.ceil or math.floor and then convert that result to an integer with the int function.

Upvotes: 0

Related Questions