user2780390
user2780390

Reputation: 11

What is the cause of this Syntax error

I'm wondering why my code doesn't work. Is it not a string? Are my periods affecting my code? Quotes somewhere?

def intro(name,school):
    return "Hello. My name is" + str(name). + "I go to" + str(school).

Upvotes: 1

Views: 1013

Answers (2)

Deelaka
Deelaka

Reputation: 13693

You script returns a syntax error because you cannot add a full-stop to a string by str(name). but it too has to be added as a string str(name) + "."

def intro(name,school):
    return "Hello. My name is " + str(name) + "." + " I go to " + str(school) + "."

print intro('kevin','university of wisconsin')

This would print (Notice the extra spaces I have added, "I go to" replaced with " I go to " so that the output is more readable):

Hello. My name is kevin. I goto university of wisconsin.

But you can use the format() method to overcome the complexity of string additions:

def intro(name,school):
    return "Hello. My name is {0}. I goto {1}.".format(name,school)

print intro('kevin','university of wisconsin')

Output:

Hello. My name is kevin. I goto university of wisconsin.

Please Note : as mentioned in a comment here you cannot use:

print intro(kevin,university of wisconsin) as it would bring a Syntax Error, why?, because variables cannot have spaces and strings must have quotes or python thinks kevin as a variable but your always welcome to do it like:

name = 'kevin'
school = 'university of wisconsin'

def intro(name,school):
    return "Hello. My name is " + str(name) + "." + " I go to " + str(school) + "."
    #return "Hello. My name is {0}. I goto {1}.".format(name,school)

print intro(name,school)

Upvotes: 5

NG.
NG.

Reputation: 22904

Try the interpreter..

Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def intro(name,school): return "Hello. My name is" + str(name). + "I go to" + str(school).
  File "<stdin>", line 1
    def intro(name,school): return "Hello. My name is" + str(name). + "I go to" + str(school).
                                                                    ^
SyntaxError: invalid syntax
>>>

It gives you a good clue that the syntax is wrong right around str(name).. Sure enough, it is. Same issue @ str(school). Change it to:

def intro(name,school): 
    return "Hello. My name is" + str(name) + ". I go to" + str(school) + "."

Upvotes: 1

Related Questions