user3100804
user3100804

Reputation: 9

How to use "def" with strings

I'm relatively new to programming so I just recently got started with experimenting with "def" in python. This is my code and its keeps on telling me the first name hasn't been defined.

def name(first, last):
    first = str(first)
    last = str(last)
    first = first.upper
    last = last,upper
    print("HELLO", first, last)

I then run the program and i write a name like

name(bob, robert) and then it would tell me that "bob" hasn't been defined

Upvotes: 0

Views: 3094

Answers (4)

kostyll
kostyll

Reputation: 41

    def name(first, last):
        first = str(first)
        last = str(last)
        first = first.upper()
        last = last.upper()
        print("HELLO", first, last)
    name("bob","robert")

1.str-objects has upper-method, but to call it and get result u have to add "()" after the name of method - because you get link to object-method - not to string in upper case... 2.in calling name(bob,robert) - you put the arguments, which are undefined variables.. to do this u have to define these variables before calling, f.g:

    bob = "bob"
    robert="robert"
    name(bob,robert)

Upvotes: 1

Maxime Lorant
Maxime Lorant

Reputation: 36161

There's a difference between a variable and a string. A variable is a slot in memory already allocated with a data (string, number, structure...) When you write robert without quotes, Python will search this variable already instancied with this name.

Here it doesn't exists, since you don't write robert = 'something'. If you want to pass a string directly, you just have to write it, surronding by quotes (or triple quotes if it's on multiple lines).

What you want to achieve is calling your name function like this:

def name(first, last):
    first = str(first)
    last = str(last)
    first = first.upper
    last = last,upper
    print("HELLO %s %s" % (first, last))

name('bob', 'robert') # Will print "HELLO bob robert"

Upvotes: 1

Hamatti
Hamatti

Reputation: 1220

You need to put the strings to quotes (either "bob" or 'bob').

So your call would be

name('bob', 'robert')

instead of

name(bob, robert)

.

If you use it without the quotes, python tries to find a variable with a name bob.

Also, you do not need to use the str(first) or str(last) since both are already strings.

Upvotes: 0

falsetru
falsetru

Reputation: 369094

You should quote them (using ' or ") if you mean string literals:

name('bob', 'robert') 

Beside that, the code need a fix.

def name(first, last):
    first = str(first)
    last = str(last)
    first = first.upper() # Append `()` to call `upper` method.
    last = last.upper()   # Replaced `,` with `.`.
    print("HELLO", first, last)

Upvotes: 4

Related Questions