Python cs50, what happened with this simple code

Asked

Viewed 62 times

-2

Good morning,

I’m starting a Python course by Cs50, but I don’t understand what happened to the code I wrote.

name = input("Name: ")

print("Hello, " + name)

You can see that it is simple and yet this error is shown in the terminal:

Name: alberty
Traceback (most recent call last):
  File "name.py", line 1, in <module>
    name = input("Name: ")
  File "<string>", line 1, in <module>
NameError: name 'alberty' is not defined

What I must do, is some configuration or error?

PS: I also did otherwise:

print(f"Hello, {name}")

And the result was this:

File "name.py", line 2
    print(f"Hello, {name}")
                         ^
SyntaxError: invalid syntax
  • 2

    You’re running the code with Python 2 and this code is Python 3. To use Python 2, modify input for raw_input in the first part. Note: f-strings can only be used in Python 3

  • 2

    @Paulomarques Just to be exact, f-strings is from Python 3.6 :-)

1 answer

1


Expensive,

The problem is the version of Python you are using. Some commands have changed from Python 2 to Python 3

Python 2

name = raw_input("Name: ")

print("Hello, " + name)

Note The command print may or may not have parentheses in Python 2

Other forms

print "Hello, " + name
print "Hello, %s" % name

Python 3

name = input("Name: ")

print("Hello, " + name)

or

name = input("Name: ")

print(f"Hello, {name}")

Note f-strings starting from version 3.6.

So use the command below to run your code:

python3 name.py

If you don’t have Python 3 installed, two options:

  1. Install the Python 3
  2. Modify the code to Python 2

I hope I’ve helped

  • 1

    Thanks, I did not know that there were versions to run the same program, even more that you can use old mods to do the same thing. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.