0

I am trying a simple Hello world, this is my code-

def hello(name=''):
    if len(name) == 0 :
        return "Hello, World!"
    else :
        return "Hello, %s!" %(name)
my_name = raw_input()
x = hello(my_name)
print (x)

This code works fine if I use raw_input, but if I use input, it gives an error. Doesn't the new python not support raw_input. I also want to know why I defined the parameter in my function as following-

def hello(name='')

Why did I need to use the '' after name

I am really confused, please help. If you have any advice to improve my program, it's appreciated

  • 1
    `raw_input` doesn't exist in "the new python" (Python 3), so you're using the "old" python (Python 2.x). – roganjosh Aug 29 '16 at 16:49
  • You've also lifted an example from somewhere, probably a tutorial that will go on to explain. `Why did I need to use the '' after name` is defining a default value for the function argument. `''` is simply an empty string, so if you called `hello()` and didn't pass an argument to the function, `if len(name) == 0` is `True`, so you'd get "Hello World!". – roganjosh Aug 29 '16 at 16:56

1 Answers1

0

If you are passing string with input, you have to also mention the double quotes ", for example "My Name"

Whereas in raw_input, all the entered values are treated as string by default

Explanation:

# Example of "input()"
>>> my_name = input("Enter Name: ")
Enter Name: "My Name"  
# Passing `"` with the input, else it will raise NameError Exception
>>> my_name
'My Name'   <--- value is string

# Example of "raw_input()"
>>> my_name = raw_input("Enter Name: ")
Enter Name: My Name
# Not passing any `"`
>>> my_name
'My name'    <--- still value is string
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126