【问题标题】:python, unix, NameError: name not defined. not recognizing string variable [duplicate]python,unix,NameError:名称未定义。不识别字符串变量[重复]
【发布时间】:2019-07-03 03:19:24
【问题描述】:

我最近开始学习在 bash/unix 中工作……我还是很新……不太确定它到底叫什么。

我对 python 很有经验。在过去的 4 年中一直使用该语言进行网络工程和数据分析。

现在我们正在做这个虚拟环境的事情,我很难理解它。

目前,我在当前工作目录中存储的名为 helloWorld.py 的文件中有以下代码。

#! /usr/bin/env python
def hello():
    name = str(input('\n\nHello, what is your name? \n'))
    print('\nHello World')
    print('But more importantly... \nHello ' + name)
    return

hello()

所以。我的问题是。当我在 shell 中运行代码时,我得到以下信息:

[currentDirectory]$ python helloWorld.py


    Hello, what is your name?
    randomname <-- typed by user.

Traceback (most recent call last):
  File "helloWorld.py", line 8, in <module>
    hello()
  File "helloWorld.py", line 3, in hello
    name = str(input('\n\nHello, what is your name? \n'))
  File "<string>", line 1, in <module>
NameError: name 'randomname' is not defined

似乎没有认识到该变量是一个字符串。 代码在 bash shell 之外的 IDE 中运行良好。非常基本的代码。 但是这个虚拟环境 linux/unix/shell/bash 的东西是超级新的。 就像这实际上是第一天。我已经能够创建和保存文件并更改目录。这是我在 shell 中编写 python 的第一次测试,我立即遇到了障碍。 抱歉这个可能超级简单的问题。 感谢您的帮助。

顺便说一句: 如果用户在他们键入的内容周围加上引号,这将起作用。但这违背了在函数的输入行周围使用 str() 转换器的目的。 我怎样才能让它让用户可以输入任何内容?

【问题讨论】:

  • 你不应该使用raw_input()吗?
  • 哇......是的......谢谢。哈哈。那非常容易。老实说,我不必对 cli 用户输入做太多事情。通常构建 GUI 等来处理它。我知道 raw_input() 存在。但是没用过。非常感谢!

标签: python string bash unix python-2.x


【解决方案1】:

在 Python 2 中,raw_input() 返回一个字符串,input() 尝试运行 输入为 Python 表达式。

试试这个:

#! /usr/bin/env python

def hello():
    name = raw_input('\n\nHello, what is your name? \n')
    print('\nHello World')
    print('But more importantly... \nHello ' + name)
    return

hello()

【讨论】:

  • 谢谢。我知道 raw_input()。但我不知道它的目的是什么。这成功了,现在我明白了其中的区别。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 2018-08-01
  • 2020-06-17
  • 2016-07-06
相关资源
最近更新 更多