python、unix、NameError:名称未定义。无法识别字符串变量

我最近开始学习在 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 的东西是超级新的。这实际上是第 1 天。我已经能够创建和保存文件并更改目录。这是我在 shell 中编写 python 的第一次测试,我立即遇到了障碍。对不起,这个可能超级简单的问题。谢谢你的帮助。


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


慕娘9325324
浏览 197回答 1
1回答

跃然一笑

在 Python 2 中,raw_input()返回一个字符串,并input()尝试将输入作为 Python 表达式运行。尝试这个:#! /usr/bin/env pythondef hello():&nbsp; &nbsp; name = raw_input('\n\nHello, what is your name? \n')&nbsp; &nbsp; print('\nHello World')&nbsp; &nbsp; print('But more importantly... \nHello ' + name)&nbsp; &nbsp; returnhello()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python