【问题标题】:Python "Invalid Syntax" error while calling a function in IDLE [duplicate]在IDLE中调用函数时出现Python“无效语法”错误[重复]
【发布时间】:2018-01-07 17:35:14
【问题描述】:

我正在尝试编写一个生成随机数字字符串的程序,其长度基于用户输入。我在 Sublime Text 中编写它,它与 SublimeREPL 完美配合,但我随后将它放入 IDLE 并尝试运行它,它抛出了一个无效的语法错误。

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)

当我调用函数时,它总是给我无效的语法错误,特别是“digit_password”名称。它在崇高的文本中工作,但在 IDLE 中它不会工作。有谁知道为什么会这样?

如果相关,我正在使用 python 3.6.4 shell。

【问题讨论】:

  • 有什么理由在函数之外有return
  • 您正在使用 print 语句,在 python 3 中它被更改为一个函数,因此需要括号才能在 python 3 中正常工作。我假设它在 sublime 文本中工作,因为它正在使用 python2
  • 以上 cmets 应该可以解决您的问题。仅供参考:您应该始终在问题正文中发布确切的错误消息

标签: python python-3.x sublimetext sublimerepl


【解决方案1】:
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.

【讨论】:

    【解决方案2】:

    打印调用周围没有括号。 Python 3 需要将 print 构造为print(item)

    将最后一行更改为:

    print(digit_password(length))
    

    附言。您可能需要缩进您的回电。

    【讨论】:

      【解决方案3】:

      首先,您的 while 循环将无限运行,因为您没有更改循环内的长度,您实际遇到问题的第二个原因是在 py3 print 被修改为 print() 之后,它会给您一个无效的语法错误.

      【讨论】:

        猜你喜欢
        • 2021-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多