division not working where multiplication does?

This is the place for queries that don't fit in any of the other categories.

division not working where multiplication does?

I cant understand what i am doing wrong with this code:

Code: Select all
`         user_numberofselections = re.findall(pattern4, user_delimiter)[0]        user_numberofwinners = re.findall(pattern5, user_delimiter)[0]        strikeratecalc = user_numberofselections/user_numberofwinners        print "Strike rate = ",strikeratecalc`

Both user_numberofselections and user_numberofwinners return numbers.
I tested that they were indeed recognised as numbers by replacing strikeratecalc = user_numberofselections/user_numberofwinners with strikeratecalc = user_numberofselections*7and likewise foruser_numberofwinners. Both of which work.

Any ideas why i cant get this (what should be simple) division to work???

Kind regards

AEA
AEA

Posts: 32
Joined: Thu Apr 18, 2013 11:37 am

Re: division not working where multiplication does?

re.findall returns a list of strings, not numbers. You need to ether int() or float() (depending on what the numbers actuallya are) the result before you can do arithmetic on them. Multiplication works because you can multiply a string by an int (but it does not do what you might expect):
Code: Select all
`>>> '1' * 3'111'`
setrofim

Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: division not working where multiplication does?

Hi thanks that was very useful, i ammended the code to:

Code: Select all
`          user_numberofselections = int(re.findall(pattern4, user_delimiter)[0])        user_numberofwinners = int(re.findall(pattern5, user_delimiter)[0])        strikeratecalc = user_numberofwinners/user_numberofselections        print "Strike rate = ",strikeratecalc,"%"        print ""  `

However the python returns 0 i assume it is displaying results to 0 decimal places? Any idea how to make it return to more decimal places? Please note I am very new to python and programming in gerneral, i dont know what a float is yet.

kind regards

AEA
AEA

Posts: 32
Joined: Thu Apr 18, 2013 11:37 am

Re: division not working where multiplication does?

By default, when you devide two ints in Python 2, it will perform integer division, i.e. it will always return an int, so if the divisor is greater than the dividend, you will get zero:
Code: Select all
`>>> 1 / 30`

To get around this, either user float() instead of int(), or add the following to the top of your script:
Code: Select all
`from __future__ import division`
setrofim

Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: division not working where multiplication does?

Many thanks Setrofim all working
AEA

Posts: 32
Joined: Thu Apr 18, 2013 11:37 am