[Tutor] Python problem

Alan Gauld alan.gauld at yahoo.co.uk
Sat Feb 27 06:19:54 EST 2021


On 27/02/2021 07:23, Vakhtang Kvaratskhelia wrote:

> What i mean is that if i write the code (for simplicity i have
> precalculated variables mentioned in the previous emails and narrowed the
> code down to the following ) :

I'm confused. I'd expect both versions to give an infinite loop since
you never change portion_saved and it is equal to zero. So the while
loop will always evaluate to the same result.

Also you have commas in your numbers which changes the meaning in
Python. For example the while test parens looks like this to python:

(250, (000 - portion_saved * 566), 774)
Which works out at

(250, 0, 774)

But that should result in an error when you apply abs()

Now the other possibility is that your locale settings allow commas
in a number as a decimal point. In which case I'm not sure how Python
distinguishes numbers in a tuple?

But either way the fact that you multiply by zero and never change
portion_saved should result in an infinite loop.

The other thing I see different is that in the integer division
version you have a comma in the if test but not in the float
division version.

> 
> low=0
> high=10000
> epsilon=100
> portion_saved=0
> while abs(250,000 - portion_saved * 566,774) >= epsilon:
>     if portion_saved * 566774 < 250,000 :
>         low=portion_saved
>     else:
>         high=portion_saved
>     portion_saved=(high+low) / 2
> print(portion_saved)
> 
> The result is the same as the answer in the book that had the problem.
> 
> but if i run the code:
> 
> low=0
> high=10000
> epsilon=100
> portion_saved=0
> while abs(250,000 - portion_saved * 566,774) >= epsilon:
>     if portion_saved * 566,774 < 250,000 :
>         low=portion_saved
>     else:
>         high=portion_saved
>     portion_saved=(high+low) // 2
> print(portion_saved)


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list