Control Structures (Absolute Value)

Back To The Index absolute_value

Prompt user for a number, and print out the absolute value. Terminate when user enters any non numeric value to the prompt.

In [1]:
###################################################
#  Filename : absolute_value                      #
#  Purpose : To demonstrate console input and     #
#   usage of the following control structures     #
#            1. if elif else                      # 
#            2. while loop                        #
#  Author : Niel S.                               #
#  The English Tea Company LLC                    #
###################################################

#The main function
def main():
    #Read data for first iteration
    X = input("Enter any +/- number: ")
    #Shave '-' from negative numbers before using 'isnumeric'
    while (X.replace('-','').isnumeric()): 
        X = float (X)
        #Initialize abs_val, assign value using if-else structure
        abs_val = None
        if X < 0:
            abs_val = -1 * X
        else :
            abs_val = X
        #Print the information
        print ("The absolute value of ",X," is ",abs_val)
        
        X = input("Enter another +/- number to continue or anything else to exit: ")
        
    print ('Good Bye !!')
    
if __name__ == '__main__':
    main()
Enter any +/- number: -23
The absolute value of  -23.0  is  23.0
Enter another +/- number to continue or anything else to exit: 23
The absolute value of  23.0  is  23.0
Enter another +/- number to continue or anything else to exit: -98
The absolute value of  -98.0  is  98.0
Enter another +/- number to continue or anything else to exit: done
Good Bye !!

Question: Why did we use following snippet of code ?

while (X.replace('-','').isnumeric()): X = float (X) ...

Back To The Index