简体   繁体   中英

Issue while checking user input

I have to read the input and check if the number is actually a float or the string STOP . When I execute my program without the two commented out lines, the result is like this:

1.1
g=nan   r=nan%  s=nan
2.2
g=nan   r=nan%  s=nan

The code:

def CheckFloat(number):
    try:
        float(number)
        return True
    except ValueError:
        return False

def read_input(period):
    i = 0
    info = []
    nbr = []
    diff = []

    while True:
        try:
            # if not CheckFloat(input()) and input() != "STOP":
            #     exit(84)
            info.append(input())
            if info[i] == "STOP":
                fnc_tendency(period, nbr)
            else:
                nbr.append(float(info[i]))
                if i >= 0:
                    diff.append(nbr[i] - nbr[i - 1])
                    print_res(nbr, period, diff, i)
                i += 1
        except(EOFError, StopIteration):
            exit(84)

But when I uncomment the two lines

# if not CheckFloat(input()) and input() != "STOP":
#     exit(84)

the result looks like this:

1.1
2.2
g=nan   r=nan%  s=nan

I lose one line of printing, and I don't know why. Could someone help me through this please?

Your float function can be simplified quite a bit

def CheckFloat(n):
    return type(n) == float

Otherwise, it looks like you're checking for input twice?

if not CheckFloat(input()) and input() != "STOP":
    exit(84)
info.append(input())


# I think you intended to do something more like this:

val = input()
if CheckFloat(val) and val != "STOP":
    # do something
else:
    # do something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM