1

I have recently started learning to work in bash/unix... I'm still very new.. not really sure what its even called.

I am experienced with python. Having worked with the language the past 4 years for network engineering and data analysis.

Now we are doing this virtual environment thing, and I'm having some trouble wrapping my head around it.

Currently I have the following code in a file called helloWorld.py stored in the current working directory.

#! /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()

So. my issue is. when I run the code in the shell, I get the following:

[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

It seems to not be recognizing that the variable is a string. Code works fine in IDE outside of bash shell. Pretty basic code. But this virtual enviroment linux/unix/shell/bash stuff is super new. Like this is literally day 1. I have been able to create and save a file and change directories. This was my first test of writing python in the shell and I immediately hit a roadblock. Sorry for the probably super easy question. Thanks for any help.

BTW: this DOES WORK IF the user puts quotes around what they type. But that defeats the purpose of using the str() converter around the input line in the function. How can I make it so user can just type whatever?

Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
SydDevious
  • 103
  • 1
  • 10
  • 1
    Shouldn't you be using `raw_input()`? – Alan Kavanagh Feb 08 '19 at 20:46
  • wow..... yea... thank you. lol. That was super easy. Honestly I haven't had to do much with cli user input. Usually built GUIs and such to handle that. I was aware that raw_input() existed. But haven't had to use it. Thank you much! – SydDevious Feb 08 '19 at 20:51

1 Answers1

1

In Python 2, raw_input() returns a string, and input() tries to run the input as a Python expression.

Try this:

#! /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()
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65
  • Thank you. I was aware of raw_input(). But I had no idea what its purpose was. This did the trick, AND now I understand the difference. Thanks for the help. – SydDevious Feb 08 '19 at 20:54