Python Forum
SyntaxError: Invalid syntax in a while loop
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
SyntaxError: Invalid syntax in a while loop
#1
Hello everyone,
I would like to create a list of 12 numbers which each term is equal to the previous triple using a while loop.
Here is my code:
i, n=int(input("Enter a number:"), 1
while n<=12:
    print(i, end=",")
    i*=3
    n+=1
Error:
File "learning.py", line 2 while n<=1: ^ SyntaxError: invalid syntax
I don't understand why it doesn't work, what should I do differently ?
Reply
#2
i, n=int(input("Enter a number:"), 1
is invalid python syntax, the error is showing up on line 2 because of line 1 error

use something like:
try:
    n = int(input('Enter starting number: '))
    for i in range(12):
        print('{}, '.format(n), end = '')
        n = n * 3
except ValueError:
    print("Numbers only, please")
Reply
#3
Thank you very much for the quick awnser and for your code. I'll check it!
Meanwhile I've found the error, it was a parenthesis missing in line 1.
Here is the script
n, i= 1, int(input("Enter a number:"))
while n<=12:
    if n!=12:
        print(i, end=", ")
    else:
        print(i)
    i*=3
    n+=1
It works !
Output:
Enter a number:1 1, 3, 9, 27, 81, 243, 729, 2187, 6561, 19683, 59049, 177147
Reply
#4
Great!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Please check whether the code about the for loop question is correct. (SyntaxError) lilliancsk01 10 2,560 Nov-08-2022, 01:25 PM
Last Post: deanhystad
  Invalid syntax Slome 2 1,949 May-13-2022, 08:31 PM
Last Post: Slome
  print(f"{person}:") SyntaxError: invalid syntax when running it AryaIC 11 16,295 Nov-07-2020, 10:17 AM
Last Post: snippsat
  Invalid syntax error, where? tucktuck9 2 3,415 May-03-2020, 09:40 AM
Last Post: pyzyx3qwerty
  Invalid syntax defining a dictionary? ep595 6 5,078 Nov-19-2019, 08:06 PM
Last Post: ThomasL
  Syntax Error: Invalid Syntax in a while loop sydney 1 4,068 Oct-19-2019, 01:40 AM
Last Post: jefsummers
  Syntax "for" loop, "and", ".isupper()", ".islower", ".isnum()" dcardonaa 4 3,476 Sep-06-2019, 01:33 PM
Last Post: ichabod801
  [split] Please help with SyntaxError: invalid syntax Mason 1 2,187 Apr-28-2019, 06:58 PM
Last Post: Yoriz
  SyntaxError: invalid syntax at run .py tuxo9999 10 7,232 Aug-23-2018, 03:58 PM
Last Post: Axel_Erfurt
  Homework: Invalid syntax using if statements chehortop 3 3,640 Mar-01-2018, 04:38 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

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