I'm new at Python coding and in DaniWeb. Really nice forum :icon_cheesygrin: Need some help w/ the following code:

the content of saldo.txt is the following

1000

The code I was talkin' about:

# [...]

        f = open('C:/saldo.txt')
        print f
        saldo = f.readline()
        f.close()
        if saldo <= 100:
            a = 5
            b = 70
        if 1000 >= saldo > 100:
            a = 50
            b = 700
        if 1000 < saldo < 2500:
            a = 100
            b = 1000
        if 2500 <= saldo < 5000:
            a = 250
            b = 2000
        if 5000 <= saldo < 10000:
            a = 500
            b = 5000
        if 10000 <= saldo < 25000:
            a = 1000
            b = 7500
        if 25000 <= saldo < 50000:
            a = 2500
            b = 10000
        if 50000 <= saldo < 100000:
            a = 5000
            b = 10000
        if saldo >= 100000:
            a = 1
            b = 1000000000
        print (a, b)

# [...]

My problem is:

"a" is being printed as 1 instead of 50
"b" is being printed as 1000000000 instead of 700

:confused:

Dani AI

Generated

Quick diagnosis and what caused the surprising output: the file read returns text, not a number. and were right about the type issue, and 's fix (convert the text to a numeric type) is the right immediate step. Also note: Python 2 quietly allows cross-type comparisons (giving misleading results); Python 3 raises a TypeError for comparisons between strings and numbers, so converting the file text to a numeric type is required in both versions.

A robust way to read and parse the file, handling whitespace, commas or a leading currency sign, and malformed content:

with open('C:/saldo.txt', 'r') as fh:
    raw = fh.read().strip()

clean = raw.replace(',', '').lstrip('$').strip()

try:
    value = int(clean)
except ValueError:
    try:
        value = float(clean)
    except ValueError:
        raise ValueError("saldo.txt does not contain a valid number: %r" % raw)

After you have a numeric value, avoid using several independent if statements. Use elif (or a lookup) so only one branch runs and earlier results aren’t overwritten:

if value <= 100:
    a, b = 5, 70
elif value <= 1000:
    a, b = 50, 700
elif value < 2500:
    a, b = 100, 1000
# continue the chain...

For many thresholds, ’s bisect idea is cleaner: build a sorted list of breakpoints and a parallel list of (a,b) pairs, then locate the bucket with bisect/bisect_right. Convert the file text to a number before using bisect. Final debugging tips: print repr(raw) and type(value) while developing, handle empty files, and prefer the with context manager so the file is always closed.

Recommended Answers

All 5 Replies

A string is always larger than a number (any number). Better re-read your other thread and if you are not sure, print type() for both variables.

Also, all this should be written using module bisect:

from bisect import bisect
limits = [100, 1000, 2500, 5000, 10000, 25000, 50000, 100000]
pairs = [
    (5, 70), (50, 700), (100, 1000), (250, 2000),
    (500, 5000), (1000, 7500), (2500, 10000), (5000, 10000),
    (1, 1000000000)
]

a, b = pairs[bisect(limits, saldo)]

In the mean time changing
saldo = f.readline()
to
saldo = int(f.readline())
will work

In the mean time changing
saldo = f.readline()
to
saldo = int(f.readline())
will work

Got it. I'm not used to Python. In some other languages the content of the file (1000) would be a numeric value, not a string. Thanks

In some other languages the content of the file (1000) would be a numeric value, not a string. Thanks

In many other lanuages you need to declare vaiables.
In python there is no need for this,but off course datatypes is always there.

C++
int age;
age = 30

Python
age = 30

Test in IDLE.

>>> age = 30
>>> type(age)
<type 'int'>
>>>

So do this if you not sure of datatype.

>>> f = open('C:/saldo.txt')
>>> saldo = f.readline()
>>> saldo
'100'
>>> print saldo
100
>>> type(saldo)
<type 'str'>

>>> if saldo > 1000:
        print True
    else:    
        print False   
True
#As you see this is worng
#Because saldo is a string

>>> if int(saldo) > 1000:
        print True
    else:  
        print False
False
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.