简体   繁体   中英

I am not getting expected output of for while and while loop in Python

import sys

target_int = input("How many integers?")
try:
target_int = int(target_int)

except ValueError:
sys.exit("You must input an integer")
ints = list()
count = 0

while count < target_int:

new_int = input("Please enter {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))

print("Using a while loop")
total = len(ints)
count = 0

while count < total:
    print(str(ints[count]))
    count += 1

OUTPUT is:

How many integers?4
Please enter 1:12
Please enter 1:2 
Please enter 1:21
Please enter 1:34
Please enter 1:23
Please enter 1:23

Expected OUTPUT should be

How many integers? 4
Please enter integer 1: t
You must enter an integer
Please enter integer 1: 5
Please enter integer 2: 2
Please enter integer 3: 6
Please enter integer 3: 6

Using a for loop

5
2
6
9

Using a while loop

5
2
6
9

The problem is that you don't increment count when you're building ints , and you've written the loop such that it won't finish until count reaches the target. You don't really need the loop to be written that way in the first place, though; just check len(ints) to see how many ints have been entered instead of keeping your own counter that mirrors the length.

try:
    num_ints = int(input("How many integers? "))
except ValueError:
    exit("You must input an integer.")

ints = []
while len(ints) < num_ints:
    try:
        ints.append(int(input(f"Please enter {len(ints)+1}: ")))
    except ValueError:
        print("You must enter an integer")

print("Using a for loop")
for v in ints:
    print(v)

print("Using a while loop")
while ints:
    print(ints.pop(0))

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