蟒蛇,UNIX,NameError:名字没有定义。不承认字符串变量[重复]

问题描述 投票:1回答:1

这个问题已经在这里有一个答案:

我最近开始学习在bash工作/ UNIX ...我还是很新..真的不知道它是什么甚至称其。

我与蟒蛇的经验。经过与语言在过去的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

这似乎不承认这个变量是一个字符串。代码IDE工作正常的bash shell之外。非常基本的代码。但这种虚拟环境的Linux / Unix /壳/ bash的东西,是超新。像这样的字面1日我已经能够创建和保存文件,并更改目录。这是我在shell编写Python的第一次测试,我马上打了一个路障。对不起,我大概超级简单的问题。谢谢你的帮助。

BTW:这是否工作,如果用户将围绕他们键入的内容引号。但是,这违背了使用围绕在该函数的输入线的STR()转换器的目的。我怎样才能使它所以用户只需键入什么?

python string bash unix python-2.x
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.