Python Forum

Full Version: Fraction Calculation with Limitations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
I am a beginning Python coder and I am trying to write code to convert a FIF dimension (One Sixteen of an Inch Precision) - Feet, Inches, Fraction of Inch to Decimal Inches.

I can convert the Feet to inches with no problem. The Fraction is giving me problems.

The fraction of an inch numerator must be limited to a integer (Whole Number) between 0 and 15. I am not sure how to limit my selection to these sixteen numbers. Can you point me in the right direction.

The fraction of an inch denominator must be a integer (Whole Number) one of four numbers 16,8,4, or 2.

The third criteria I have is the denominator must be greater than the numerator.

Do you know if any code exists that my help me out with this task.

This is only by second try at trying to write Python code.

Any help you can provide would be greatly appreciated.
Please show code attempt so far.
I read the problem description you provided and didn't understand. Maybe you should spend some time to describe you objective more precisely and concisely? And of course provide your efforts to achieve the objective and problem encountered.
(Dec-05-2020, 03:40 AM)Larz60+ Wrote: [ -> ]Please show code attempt so far.
This is the code attempt I have used so far. I don't know how to have the user select the numerator from the list of 0 to 15 I have created. Also I don't know how to generate a list of numbers starting from 2 where the next number is 2 times the previous number - 2,4,8, ending in 16. I then need to select from this list for the denominator.

In addition I want some way to check that the denominator is larger than the selection for the numerator so I don't end up with a fraction greater than one.

Please keep in mind this is my first attempt at coding for this Senior Citizen!!

#Python program to convert Feet, Inches, Fraction Dimension to Decimal Inches
print ("     ")
print ("     ")
print ("Python program to convert Feet, Inches, Fraction Dimension to Decimal Inches")
print ("     ")
feet = int(input('Feet: '))
print ("     ")
feetinchesconv = feet * 12
print("Feet is: ", feet)
print("Feet Inches Conversion is: ", feetinchesconv)
print ("     ")
print ("     ")
inches = int(input('Inches: '))
print("Inches is: ", inches)
nums = range(0,16)
print ("     ")
print ("     ")
print ("Numerator must be betweeen 0 and 15 as shown below:  ")
print ("     ")
print(list(nums))
print(list(map(str, nums)))
PROGRAM OUTPUT

Python program to convert Feet, Inches, Fraction Dimension to Decimal Inches
Output:
Feet: 10 Feet is: 10 Feet Inches Conversion is: 120 Inches: 11 Inches is: 11

Numerator must be betweeen 0 and 15 as shown below:
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15']
Getting input from a user is something you will use a lot. This is a modified version of a function I wrote so I don't have to keep re-writing user input code over and over. It has been modified to let you specify a list of allowable values.
def input_number(prompt='', values=None, conv=int):
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
    while True:
        try:
            result = conv(input(prompt))
            if values and not result in values:
                raise ValueError
            return result
        except ValueError:
            print("Input is invalid")
This is the start of a function named "input_number". It takes multiple arguments. Default values are provided for all the arguments making them all optional.
def input_number(prompt='', values=None, conv=int)
This is a docstring. It is a description of the function.
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
Docstrings aren't required, but I find them useful. If I am using this function later and don't remember the arguments I can just type "help(input_number)" at the Python prompt.
Output:
>>> help(input_number) Help on function input_number in module __main__: input_number(prompt='', values=None, conv=<class 'int'>) Input a number. values : An optional list of allowable values conv : The value converter, int() is the default value returns the input number
I know users will make mistakes typing input, so I give them multiple chances to enter a value and catch when they make an error.
while True:
    try:
        ...
    except ValueError:
        ...
try and except will "catch" errors that occur in the code between the try and except statements. This exception handler catches errors of type "ValueError". Python will raise a ValueError if you call int() and pass it a string that does not represent an integer. For example typing 'a' or '3.14'. The line(s) after "except" is executed when an exception occurs.

This line gets the input and converts it to a number. Instead of using int() to do the conversion I let the caller specify a converter function and provide int() as the default converter.
result = conv(input(prompt))
This code verifies the input value against a list of allowable values. The caller may want to allow all numbers, so this test is only performed if "values" is specified in the function call.
if values and not result in values:
    raise ValueError
If the result is not in the values list the code raises a ValueError. Our exception handler will catch this error.

This is some code I wrote to test the function.
odd_values = [1, 3, 5, 7, 9]
print(input_number(f'Enter number {odd_values}: ', odd_values))
Output:
Enter number [1, 3, 5, 7, 9]: 2 Input is invalid Enter number [1, 3, 5, 7, 9]: a Input is invalid Enter number [1, 3, 5, 7, 9]: 3 3
I think this function, or one like it, could be useful for code that takes user input but has special input limitations.
Thank you very much for your response I am going to try and incorporate your suggestions into my code. I am trying to learn Python. I am finding these modern programming languages very difficult to learn. I took Fortran in college 56 years ago and did not use it during my working career.

I did some investigation on the internet and came up with the following code for a list of values I will accept for the denominator for fractions limited to 1/16 of an inch precision. I will add this to my existing code.

I would like to be able to make my response look as professional looking as your response.

I am going to try and use the BBCode in my response hopefully I am successful. It is like trying to learn Python.

[/print ("Denominator must be one of four numbers as shown below:  ")
print ("     ")
pow2=[2**x for x in range (5) if x>0]
print (pow2)python]
[python]
Output:
Denominator must be one of four numbers as shown below: [2, 4, 8, 16]
Again thanks for your response.
(Dec-05-2020, 03:31 PM)deanhystad Wrote: [ -> ]Getting input from a user is something you will use a lot. This is a modified version of a function I wrote so I don't have to keep re-writing user input code over and over. It has been modified to let you specify a list of allowable values.
def input_number(prompt='', values=None, conv=int):
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
    while True:
        try:
            result = conv(input(prompt))
            if values and not result in values:
                raise ValueError
            return result
        except ValueError:
            print("Input is invalid")
This is the start of a function named "input_number". It takes multiple arguments. Default values are provided for all the arguments making them all optional.
def input_number(prompt='', values=None, conv=int)
This is a docstring. It is a description of the function.
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
Docstrings aren't required, but I find them useful. If I am using this function later and don't remember the arguments I can just type "help(input_number)" at the Python prompt.
Output:
>>> help(input_number) Help on function input_number in module __main__: input_number(prompt='', values=None, conv=<class 'int'>) Input a number. values : An optional list of allowable values conv : The value converter, int() is the default value returns the input number
I know users will make mistakes typing input, so I give them multiple chances to enter a value and catch when they make an error.
while True:
    try:
        ...
    except ValueError:
        ...
try and except will "catch" errors that occur in the code between the try and except statements. This exception handler catches errors of type "ValueError". Python will raise a ValueError if you call int() and pass it a string that does not represent an integer. For example typing 'a' or '3.14'. The line(s) after "except" is executed when an exception occurs.

This line gets the input and converts it to a number. Instead of using int() to do the conversion I let the caller specify a converter function and provide int() as the default converter.
result = conv(input(prompt))
This code verifies the input value against a list of allowable values. The caller may want to allow all numbers, so this test is only performed if "values" is specified in the function call.
if values and not result in values:
    raise ValueError
If the result is not in the values list the code raises a ValueError. Our exception handler will catch this error.

This is some code I wrote to test the function.
odd_values = [1, 3, 5, 7, 9]
print(input_number(f'Enter number {odd_values}: ', odd_values))
Output:
Enter number [1, 3, 5, 7, 9]: 2 Input is invalid Enter number [1, 3, 5, 7, 9]: a Input is invalid Enter number [1, 3, 5, 7, 9]: 3 3
I think this function, or one like it, could be useful for code that takes user input but has special input limitations.
(Dec-22-2020, 01:27 AM)TINMAN01 Wrote: [ -> ]
(Dec-05-2020, 03:31 PM)deanhystad Wrote: [ -> ]Getting input from a user is something you will use a lot. This is a modified version of a function I wrote so I don't have to keep re-writing user input code over and over. It has been modified to let you specify a list of allowable values.
def input_number(prompt='', values=None, conv=int):
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
    while True:
        try:
            result = conv(input(prompt))
            if values and not result in values:
                raise ValueError
            return result
        except ValueError:
            print("Input is invalid")
This is the start of a function named "input_number". It takes multiple arguments. Default values are provided for all the arguments making them all optional.
def input_number(prompt='', values=None, conv=int)
This is a docstring. It is a description of the function.
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
Docstrings aren't required, but I find them useful. If I am using this function later and don't remember the arguments I can just type "help(input_number)" at the Python prompt.
Output:
>>> help(input_number) Help on function input_number in module __main__: input_number(prompt='', values=None, conv=<class 'int'>) Input a number. values : An optional list of allowable values conv : The value converter, int() is the default value returns the input number
I know users will make mistakes typing input, so I give them multiple chances to enter a value and catch when they make an error.
while True:
    try:
        ...
    except ValueError:
        ...
try and except will "catch" errors that occur in the code between the try and except statements. This exception handler catches errors of type "ValueError". Python will raise a ValueError if you call int() and pass it a string that does not represent an integer. For example typing 'a' or '3.14'. The line(s) after "except" is executed when an exception occurs.

This line gets the input and converts it to a number. Instead of using int() to do the conversion I let the caller specify a converter function and provide int() as the default converter.
result = conv(input(prompt))
This code verifies the input value against a list of allowable values. The caller may want to allow all numbers, so this test is only performed if "values" is specified in the function call.
if values and not result in values:
    raise ValueError
If the result is not in the values list the code raises a ValueError. Our exception handler will catch this error.

This is some code I wrote to test the function.
odd_values = [1, 3, 5, 7, 9]
print(input_number(f'Enter number {odd_values}: ', odd_values))
Output:
Enter number [1, 3, 5, 7, 9]: 2 Input is invalid Enter number [1, 3, 5, 7, 9]: a Input is invalid Enter number [1, 3, 5, 7, 9]: 3 3
I think this function, or one like it, could be useful for code that takes user input but has special input limitations.
I created the code shown below per your recommendations. It works fine, thank you, however I would like to take the input an assign it to a variable. I must be doing something wrong. I know this must be something simple.

def input_number(prompt='', values=None, conv=int):
    """Input a number.
    values : An optional list of allowable values
    conv   : The value converter, int() is the default value
    returns the input number
    """
    while True:
        try:
            result = conv(input(prompt))
            if values and not result in values:
                raise ValueError
            return result
        except ValueError:
            print("Input is invalid")
numerator_values = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]
print ("Enter numerator integer number from list shown. ")
print (" ")
print(input_number(f'Enter number {numerator_values}: ', numerator_values))
print (" ")
numerator = numerator_values
print ('numerator')
This is the output I get.

Output:
Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> = RESTART: C:\Users\Fred\OneDrive\Documents\Python Programs\Fred First Program Modules\Training-002 Numerator Values.py Enter numerator integer number from list shown. Enter number [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]: 14 14 numerator >>>
I am not getting anything for the variable numerator, I was expecting to get 14.
print ('numerator') is not printing the variable numerator, it's printing the string "numerator". You would need to remove the quotes to reference the variable.
Pages: 1 2