MCPcopy Index your code
hub / github.com/geekcomputers/Python / main

Function main

Collatz-Conjecture.py:40–86  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

38
39
40def main():
41 # Get the input
42 number = input("Enter a number to calculate: ")
43 try:
44 number = float(number)
45 except ValueError:
46 print("Error: Could not convert to integer.")
47 print("Only numbers (e.g. 42) can be entered as input.")
48 main()
49
50 # Prevent any invalid inputs
51 if number <= 0:
52 print("Error: Numbers zero and below are not calculable.")
53 main()
54 if number == math.inf:
55 print("Error: Infinity is not calculable.")
56 main()
57
58 # Confirmation before beginning
59 print("Number is:", number)
60 input("Press ENTER to begin.")
61 print("\nBEGIN COLLATZ SEQUENCE")
62
63 def sequence(number: float) -> float:
64 """
65 The core part of this program,
66 it performs the operations of
67 the Collatz sequence to the given
68 number (parameter number).
69 """
70 modulo = number % 2 # The number modulo'd by 2
71 if modulo == 0: # If the result is 0,
72 number = number / 2 # divide it by 2
73 else: # Otherwise,
74 number = 3 * number + 1 # multiply by 3 and add 1 (3x + 1)
75 return number
76
77 # Execute the sequence
78 while True:
79 number = sequence(number)
80 print(round(number))
81 if number == 1.0:
82 break
83
84 print("END COLLATZ SEQUENCE")
85 print("Sequence has reached a 4-2-1 loop.")
86 exit(input("\nPress ENTER to exit."))
87
88
89# Entry point of the program

Callers 1

Calls 2

sequenceFunction · 0.85
exitFunction · 0.85

Tested by

no test coverage detected