usingMaths.com
From Theory to Practice - Math You Can Use.







<< PreviousNext >>

Python Program to Calculate HCF (GCD) with User Input - Kids Fun Project



Understanding the HCF Algorithm in Python

This Python program calculates the HCF (Highest Common Factor) using user input and the Fast HCF Python Code from the previous lesson.
Let's add some input mechanism so our user enters the set of numbers whose H.C.F. we are to find.


Combining the H.C.F. (G.C.D.) Python Code and Collecting User Input

All we need is a main code that asks the user for input.
For this purpose, we'll use the input() function.

How to use the HCF Code in Python

The user gets to enter his/her choice of numbers for the HCF Python algorithm.
After entering each number, the user presses <Enter>.
After the user has entered every of his/her numbers, the user enters the word done to see the result.


Note: You can comment out the Python code for the main class from the previous lesson if you have been following.


So! Python Fun Practice Exercise - Find HCF with User Input

As a fun practice exercise, feel free to try out your own numbers, and see how the Python code finds the HCF of your input numbers.







Python Code for HCF with User Input - Main Class.

#!/usr/bin/python
from FastHCF import quickHCF
import re

# Collect input
print("\nWelcome to our Find HCF program.\
Enter your series of numbers whose HCF you wish to find.\
\nType 'done' when you are through with entering your numbers.")

group = []
collect_input_text = "Enter First Number:  ";
user_num = "start"

try:
    while user_num != "DONE":
        # get keyboard input
        user_num = input(collect_input_text)
        # Make sure input is a number
        if re.search("[0-9]+", user_num):
            user_num = int(user_num)
            if user_num != 0:
                group.append(user_num)
                collect_input_text = "Enter Next Number:  "

            else:
                print("\nYou cannot enter zero. Repeat that!\nType 'done' when you're finished.\n")

        else:
            # Convert 'user_num' to upper case.
            user_num = user_num.upper()
            if user_num != "DONE":
                print("\nWrong Input. Repeat that!\nType 'done' when you're finished.\n")

except:
    print("Sorry, but something must have gone wrong!")

# Use the fast HCF module/class
h_c_f = quickHCF(group)
answer = h_c_f.getHCF()
print ("The H.C.F. of ", group, "is", answer)


print("\n\n")




<< PreviousNext >>