-3

I want the user to enter an integer as a server count when creating EC2 instances in AWS.

I wrote the following loop:

max_count = ''
while not max_count:
    max_count = input("Enter how many EC2 Servers: ")
    try:
        max_count = int(max_count)
    except:
        max_count = input("Enter how many EC2 Servers: ") 

If I enter a non integer (like a word) once, it works and prompts you again. But if you enter the wrong input twice you get an error:

Traceback (most recent call last):
  File ".\aws_create_ec2_simple.py", line 100, in <module>
    main()
  File ".\aws_create_ec2_simple.py", line 91, in main
    aws_account, region, max_count, image_id, instance_type, vpc_id, sg_list, subnet_ids, public_ip, private_ip, tenancy, monitoring_enabled, user_data = user_input()
  File "C:\Users\User\OneDrive - Company Technologies\Desktop\important_folders\Company\git\cloud_scripts\aws_scripts\python\aws_tools\user_input.py", line 30, in user_input
    for count in range(max_count):
TypeError: 'str' object cannot be interpreted as an integer

How can I get this to loop the input until the user inputs an integer?

bluethundr
  • 1,005
  • 17
  • 68
  • 141

1 Answers1

1
max_count = None
while max_count is None:
    try:
        max_count = int(input("Enter how many EC2 Servers: "))
    except Exception:
        continue
Quinn
  • 7,072
  • 7
  • 39
  • 61