0

I'm attempting to write a program that generates a random string of numbers, with its length based on user input. I wrote it in Sublime Text, and it worked perfectly with SublimeREPL, but I then took it into IDLE and attempted to run it and it threw an invalid syntax error.

import string
import random

# Random Number Password Generator


def digit_password(length):
    final = []
    while length > 0:
        final.append(random.choice(string.digits))
    length -= 1
    result = ''.join(final)
    return result


length = int(raw_input("How long will this password be? "))
print digit_password(length)

It always give me the invalid syntax error when I call the function, specifically the "digit_password" name. It worked in sublime text, but it wont work here in IDLE. Does anyone know why this is happening?

Im using the python 3.6.4 shell if that is relevant.

Tim Anderson
  • 25
  • 2
  • 6
  • 3
    Any reason why you have a `return` outside the function? – cs95 Jan 07 '18 at 17:35
  • 1
    You are using a print statement, in python 3 it is changed to a function and therefore needs parentheses to work properly in python 3. I'd assume it works in sublime text because that is using python2 – Tadhg McDonald-Jensen Jan 07 '18 at 17:39
  • Above comments should solve your problem. FYI: you should always post the *exact error message* in the body of your questions. – SherylHohman Jan 07 '18 at 17:44

3 Answers3

2
import string
import random

# Random Number Password Generator


def digit_password(length):
    final = []
    while length > 0:
        final.append(random.choice(string.digits))
        length = length - 1  ###should be indented inside while loop
    result = ''.join(final)
    return result


length = int(input("How long will this password be? "))
print(digit_password(length))


try this because i feel like there's an indentation error length is decremented outside the while loop so the loop keeps running indefinitely.
1

You have no brackets around the print call. Python 3 needs print to be constructed as print(item).

Change your last line to:

print(digit_password(length))

Ps. You might need to indent your return call.

13smith_oliver
  • 414
  • 6
  • 13
1

First your while loop will run infinitely as you haven't changed the length inside the loop second reason where you are actually facing trouble is that after py3 print has been modified to print() so it will give you a invalid syntax error.

sayantan ghosh
  • 426
  • 1
  • 6
  • 8