okay, so i was doing an exercise for this beginning python course i got my hands on, and i just completed the exercise (took longer than it should have though) and for some reason, when i run it, it returns data i didn't expect, and when i run it again it return correctly. i just dont understand?! here is the exercise information;
exercise 7.3
Improve the program you wrote for exercise 7.2:
> Make it loop until exit is requested by the user hitting <return> only.
> Allow the stop and increment parameters to be optional; supply defaults for when they are not entered.
A session might now look like this:
Enter <return> only to exit
Enter Start, [Stop], [Increment]: 2,6,2
Number Square Cube
2 4 8
4 16 64
6 36 216
Enter Start, [Stop], [Increment]:1,3
Number Square Cube
1 1 1
2 4 8
3 9 27
Enter Start, [Stop], [Increment]:2
Number Square Cube
2 4 8
Enter Start, [Stop], [Increment]:
Exit requested
and below is the code i wrote for this exercise;
'Exercise 7.3'
# modified program from exercise 7.2
print "press <Enter> to Exit!"
while True:
x_str = raw_input('Enter Start, [Stop], [Increment]: ')
if not x_str:
print "Exit Requested"
break
else:
x_str_array = x_str.split(',') # splits the string where a comma pops up
x = range(len(x_str_array)) # Preallocation step- makes x= the same length as x_str_array
for i in range(len(x_str_array)):
x[i] = int(x_str_array[i])
if len(x)==3:
a=x[0]
b=x[1]+c
c=x[2]
if len(x)== 2:
a=x[0]
b=x[1]+c
c=1
if len(x)== 1:
a=x[0]
b=a+1
c=1
for number in range(a,b,c):
print "number:", number, " square:", number**2, " cube:", number**3
:X
i just dont get it. it seems to occur after i first input start,stop,increment then run a test with just start and stop. it goes too far before stopping. i dont get it?!
could someone test this code and see if the same happens for them, and let me know if they know why?
thank you very much for any help! :)