Hanterar felaktiga indata samt testar detta

This commit is contained in:
Joakim Persson
2024-07-12 16:59:21 +02:00
parent 5e25aca23b
commit 1c29c35e4d
2 changed files with 57 additions and 52 deletions
+16 -12
View File
@@ -1,6 +1,7 @@
import io
def hanoi(n, source, auxiliary, target):
# Example usage:
# hanoi(3, 'A', 'B', 'C')
if n < 1:
print(f"No disks, nothing to do")
return
@@ -14,16 +15,19 @@ def hanoi(n, source, auxiliary, target):
# Move the n-1 disks that we left on auxiliary to target
hanoi(n - 1, auxiliary, source, target)
# Example usage:
# hanoi(3, 'A', 'B', 'C')
def get_hanoi_input():
# Returns a positive integer, otherwise throws an exception
while True:
user_input = input("Please enter an integer: ")
try:
user_integer = int(user_input)
return user_integer
except ValueError:
print("That's not a valid integer. Please try again.")
if __name__== "__main__":
user_input = input("Please enter an integer: ")
try:
user_integer = int(user_input)
print(f"You entered the integer: {user_integer}")
except ValueError:
print("That's not a valid integer. Please try again.")
hanoi(user_integer,'A','B','C')
# Call the new function to get the input
user_integer = get_hanoi_input()
# Now call hanoi with the obtained integer
hanoi(user_integer, 'A', 'B', 'C')