Syntax error (The Python Book) Linux User and Developer Bookazine
Geoff Munn
geoff.munn at gmail.com
Sun Feb 14 08:39:20 EST 2016
Hi,
Noob at the Python thing so here goes,
I have copied a program to demonstrate control structures in Python but get a syntax error at line 31, isint = False. I'm using Python 2.7.6 and Linux Mint based around ubuntu14.04.1. I have pasted all the code below,
#!/usr/bin/env python2
'''
We are going to write a program that will ask for the user to input an arbitary
number of integers, store them in a collection, and then demonstrate how
the collection would be used with various control structures
'''
import sys # Used for the sys.exit function
target_int=raw_input("How many integers?")
'''
By now the variable target_int contains a string representation of
whatever the user typed. We nee to try and convert that to an integer but
be ready to deal with the error if it's not. Otherwise the program will crash
'''
try:
target_int=int(target_int)
except ValueError:
sys.exit("You must enter an integer")
ints=list() # list to store the integers
count = 0 # Track how many integers have been inputted
# Keep asking for a number until we have reached the required number
while count < target_int:
new_int=raw_input("Please enter integer {0}:".format(count +1)
isint = False
try:
new_int=int(new_int) # If the above succeeds then isint will
#be set to true: isint = True
except:
print("You must enter an integer")
'''
Only carry on if we have an integer. If not we will loop again.
The == below is a comparision operator, a single = is an asignment operator
'''
if isnit==True:
ints.append(new_int) # Adds the integer to the collection
count += 1 # Count is incremented by 1
# The for loop
print ("Using a for loop")
for values in ints:
print (str(value))
# The while loop
print ("Using a while loop")
total=len(ints) # We already have the total from above but using len we can determine from the ints list.
count = 0
while count < total:
print (str(ints[count]))
count += 1
More information about the Python-list
mailing list