Python Forum
While loop within a Function (2.7)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
While loop within a Function (2.7)
#1
Good Morning. I have some beginner/intermediate coding experience and decided to learn a new language. I am working through a book that teaches Python 2.7. This question seems pretty simple, I made a While loop that worked. Then I was asked to put it in a function and I am getting a syntax error on Line 9 - While i < stop:. Is the indention wrong? Thanks in advance for any help on this.

stop = raw_input("How high should we count? ")
increment = raw_input("What should we count by? ")


def list_numbers(stop, increment):
i = 0
numbers = []

While i < stop:
print "At the top i is %d" % i
numbers.append(i)

i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i

print "The numbers: "

for num in numbers:
print num



list_numbers(stop, increment)
Reply
#2
Since you are in the learning stage, It would be a good idea to buy another book that uses python 3
As far as your code is concerned, your statement
stop = raw_input("How high should we count? ")
inputs a string, not an integer, so when you use the statement
While i < stop:
you are trying to compare an int to a string.

there are other issues, not checking validity of input value, etc. but another issue.
change your input statement to read:
stop = int(raw_input("How high should we count? "))
Again, you will need assert that the input is capable of integer conversion.
Sooner or later someone will enter non valid input and blow the program up
Reply
#3
I knew it was something simple. Thanks so much for the quick reply and the advice. Any recommendations on Python 3 books would be great.
Reply
#4
Please refer to our list of Free Python Resources
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How can I run a function inside a loop every 24 values of the loop iteration range? mcva 1 2,137 Sep-18-2019, 04:50 PM
Last Post: buran

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020