简体   繁体   中英

For loop - I can only enter 1 integer

I am unable to enter more than one integer. I should be able to specify how many and then input like so...

How many integers? 3
Please enter an integer 1: 5
Please enter an integer 2: 2
Please enter an integer 3: 6
Using a for loop
5
2
6

However I am only being asked for integer 1 (in a continuous loop)

Below is the code:-

#!/usr/bin/env python2

import sys

target_int = raw_input("How many integers?")

try:
  target_int = int(target_int)
except ValueError:
  sys.exit("You must enter an integer")

ints = list()

count = 0

while count < target_int:
 new_int = raw_input("Please enter integer {0}:".format(count + 1))
 isint = False
 try:
   new_int = int(new_int)

 except:
   print("You must enter an integer")

 if isint == True:
     ints.append(new_int)
     count += 1

print("Using a for loop")
for value in ints:
  print(str(value))
~                   

Your main issue is as noted, that you aren't setting isint . But you shouldn't anyway, as you already cast in the try block. So if you reach this code, it is necessarily an int . 2 other small things are, I'm running in Python 3, since it was released 14 years ago, so raw_input is input , and it is good to get into the habit of initializing lists with [] instead of list() . It is faster sometimes, and never slower.

Here is working code:

import sys

target_int = input("How many integers?")

try:
    target_int = int(target_int)
except ValueError:
    sys.exit("You must enter an integer")

ints = []

count = 0

while count < target_int:
    new_int = input("Please enter integer {0}:".format(count + 1))
    try:
        new_int = int(new_int)
    except ValueError:
        print("You must enter an integer")
        continue # so it doesn't try to append

    # No need to check isint. It is.
    ints.append(new_int)
    count += 1

print("Using a for loop")
for value in ints:
    print(str(value))

Another small improvement is to avoid count altogether, since it is always the length of ints already.

import sys

target_int = input("How many integers?")

try:
    target_int = int(target_int)
except ValueError:
    sys.exit("You must enter an integer")

ints = []

while len(ints) < target_int:
    new_int = input("Please enter integer {0}:".format(len(ints) + 1))
    try:
        ints.append(int(new_int))
    except ValueError:
        print("You must enter an integer")


print("Using a for loop")
for value in ints:
    print(str(value))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM