Exercise 33 Study Drill

I tried different code for study drill in Exercise 33 but keep getting this error:

SyntaxError: invalid syntax
PS C:\Users\mr_lo\mypython> python ex33.py
  File "ex33.py", line 26
    for i < max:
          ^
SyntaxError: invalid syntax

My code as below:

i = 0
numbers = []

print("Specify a maximum number")
max_number = input(">   ")
function(max_number)

def function(max):
    for i < max:
        numbers.append(i)
        i = i + 1

for num in numbers:
    print(num)

Can someone give me some guidance whayt I did wrong in my code?

Appreciate your help on my question.

Hello @pcho028

It looks like you need to read a little bit more about for loops.
Try w3schools, python for loop

first do it simple:

for i in range(5):
    print(i)

Add a function to it:

def my_for_loop(a):
    for i in range(a):
        print(i)
my_for_loop(5)

Then add a list to it and append i to it.

Add another parameter to the function

my_for_loop(a, b):
    for b in range(a, b)
        print(b) 

Then i can be replaced by b and you choose which value to start with

Build it up in small steps. Make it work before you add more.
And try to really understand what happening.

Thank you for your suggestion. I will have another try :slight_smile:

Easy. You’re using the word for the way you use the word while. Just use while there and you’re done.

I Tried to do looping without using loop for number less than 6.but i am failing to do so can please someone help me
why this is’nt iterating again and again whenever the if condition if good.
it isn’t calling the function whenver if is true.

here is my code

i = 0

numbers = []

def injecting(i):

    print(f"The top number is {i}.")

    i += 1

    numbers.append(i)

    print(f"The bottom number is {i}.")

    print(f"Now the list is {numbers}")

injecting(i)

print(i)

if i < 6:

    i = i + 1 

    injecting(i)

else:

    print("The program is terminated.")

Close! I think your indenting is off on this code, so the call where do this:

injecting(i)

Should be indented to be at the same as the line:

print(f"Now the list is {numbers}")

now this get’s to looping infinite i don’t know why …
or iterating i don’t know but i put a if statement …
need help …

If you want to do the loop recursively, you need an exit condition inside the function.
Something like this:

def incecting(i):
    if i > 6:
        print("terminated")
        return
    else:
        numbers.append(i)
        print("numbers now:", numbers)
        injecting(i + 1)

Yes, what florian here is explaining is that you will loop forever if you don’t have some kind of break, which is usually done with an if-statement.

wow! that’s working thank you.
the exit condition under if and else for the continuing the i was doing the opposite.
thanks

A free service run by Zed A. Shaw for learncodethehardway.org.