Home > Software engineering >  Code to distinguish non-integers, negative numbers, zeros not behaving correctly
Code to distinguish non-integers, negative numbers, zeros not behaving correctly

Time:06-25

im trying to code a script that calculates how many minutes there are in x days and prints out a anwser, if the user input is a negative number, a string or a 0 it should print a error messege. Here is how far i have come

# global var

user_input = input('Click here and type how many days you want to know the minutes of\nthen press enter...\n')


# def for calculating minutes in x days

def calc_minutes(user_input):

    if user_input.isdigit() > 0:
        user_input_int = int(user_input)
        minutes_a_day = 1440
        calc_anwser = minutes_a_day * user_input_int
        return f'there are {calc_anwser} minutes in {user_input} days'

    else:

        if user_input == int():
            return 'ERROR: type something else then a string'

        if user_input == 0:
            return 'type a number above 0'

        if user_input < 0:
            return ' type a positive number'

print(calc_minutes(user_input))

i cant figure it out, if i type a positive number it works, it calculates how many minutes there are in the days u typed and prints it out.

but if you type 0 as input it still runs the calculation instead of giving the error messege.

and if you type a string or negative number it says the code isnt right and displays the red error crash messege(not the error messege i typed to be displayed)

could anyone explain why it cant use the code ive written for the negative numbers, strings and 0?

CodePudding user response:

user_input.isdigit() just tells you if the input only contains digits. It returns a boolean, not the value of the number. So you can't compare it to tell if the number is more than 0.

What's actually happening is that the boolean value True or False is converted to a number: True == 1 and False == 0. That's being compared with 0.

The best way to do this is to call int() to try to convert the input to an integer, and use try/except to detect the error if it can't be converted. If it converts successfully, check there to see if it's positive.

def calc_minutes(user_input):
    try:
        user_input_int = int(user_input)
        if user_input_int <= 0:
            return 'ERROR: type a positive number'
        minutes_a_day = 1440
        calc_anwser = minutes_a_day * user_input_int
        return f'there are {calc_anwser} minutes in {user_input} days'
    except ValueError:
        return 'ERROR: type an integer'

CodePudding user response:

In the first if operator you don't check whether the number is positive, but whether the string you got is a number.

Possible solution: First, convert the input string to integer type

user_input = int(input('...'))

Then, check if it's non-negative:

if user_input > 0:
  • Related