我最近開始學習在 bash/unix 中工作……我還是個新手……不太確定它叫什么。我對python有經驗。在過去 4 年中使用該語言進行網絡工程和數據分析?,F在我們正在做這個虛擬環境的事情,但我很難理解它。目前,我在當前工作目錄中存儲的名為 helloWorld.py 的文件中有以下代碼。#! /usr/bin/env pythondef hello(): name = str(input('\n\nHello, what is your name? \n')) print('\nHello World') print('But more importantly... \nHello ' + name) returnhello()所以。我的問題是。當我在 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() 轉換器的目的。我怎樣才能讓它讓用戶可以輸入任何內容?
1 回答

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
在 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()
添加回答
舉報
0/150
提交
取消