I'm using the bookazine  "The Python Book" First Edition on pages 13-14 it
gives the code (listed further below).

It asks for user to state a given number of integers (for example 4)...then
user enters integers.  It doesn't stop seeking input after the number
requested thereby creating an infinite loop.

-----------------------------
CODE
-----------------------------

# Python Book Page_13.py
# Joe G.

# several comment lines explain the code below it.
# Re-typing is good practice

# We're going to write a program that will ask the user to input an
arbitrary
# number of intergers, store them in a collection, and then demonstrate how
the
# collection would be used in various control structures.

# Used for the sys.exit function
import sys
# Requests number of intergers
target_int=raw_input("How many intergers?")
# By now, the variable target_int contains a string representtion of
# whatever the user typed.  We need to try and convert that to an interger
but
# be ready to # deal with the error if it's not.  Otherwise the program will
# crash
# Begin the error check
try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an interger")
# creates a collection (list) called ints
ints=list()
# keeps track of number of intergers
count=0
# Keep asking for an interger until we have the required number
while count<target_int:
new_int=raw_input("Please enter interger{0}:".format(count+1))
isint=False
try:
new_int=int(new_int)
except:
print("You must enter an interger")
# Only carry on if we have an interger.  If not, we'll loop again
# Notice below I use == which is different from =.  The single equals sign
is an
# assignment operator whereas the double equals sign is a comparison
operator. I would
# call it a married eguals sign....but whenever single is mentioned I have
to mention marriage.

if isint==True:
# Add the interger to the collection
ints.append(new_int)
# Increment the count by 1
count+=1
# print statement ("using a for loop")
print("Using a for loop")
for value in ints:
print(str(value))
# Or with a while loop:
print("Using a while loop")
# We already have the total above, but knowing the len function is very
# useful.
total = len(ints)
count = 0
while count < total:
   print(str(ints[count]))
   count +=1

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

-------------------------------
END OF CODE
-------------------------------
Sample output:

How many integers?3
Please enter integer1:1
Please enter integer1:2
Please enter integer1:3
Please enter integer1:a
You must enter an integer
Please enter integer1:4
Please enter integer1:5
Please enter integer1:6
Please enter integer1:b
You must enter an integer
Please enter integer1:
(Keeps Looping)

Thanks in advance
Joe
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to