TransWikia.com

Can I use text when using functions? Or only numbers?

Stack Overflow Asked by Osk6r on February 9, 2021

Let me just start off by saying that I’m very new to programming, I’m pretty sure this is like my fourth time sitting down and learning stuff, so well, I’m not even sure the question sounds right.

So I watch beginner tutorials for Python by CS Dojo on YouTube, I’m on the third video, it’s about functions. Watching tutorials I pause the video a lot and try to experiment a little bit to truly understand what I’m working with. So it went all good when I would play around with numbers. Like here:

def function(x):
    return x+5
a = function(10)
print(a)

(Not sure if I pasted the code well, sorry)

But then I tried to do something with words to see if it could work:

def function(name):
    return ("Hi ")
b = function(Oskar)
print(b)

And it doesn’t, I get an error like this:

NameError: name 'Oskar' is not defined

Do these kind of codes only work with numbers? Or did I do something wrong? I wanna understand this so I’d like someone to explain it to me, considering that I’m a beginner and don’t understand a lot of the words programmists use here.

4 Answers

Oskar without quote is treated as an identifier not a string. Use "Oskar" or 'Oskar'

String always have to be encapsulated in a double("") or a single('') quote

def function(name):
    return ("Hi " + name)
b = function("Oskar")
print(b)

Or use this one, in future it will come in real handy

def function(name):
    return (f"Hi {name}")
b = function("Oskar")
print(b)

Answered by Aayam Oza on February 9, 2021

name = "oskar"

def function(name):
   return ("Hi " + name)
b = function(name)
print(b)

Oskar is not a string, but undefined variable.

Answered by RawAvacado on February 9, 2021

Oskar is a variable. 'Oskar' and "Oskar" are strings (note the quotes).

In other words, any of the following will work:

b = function('Oskar')
b = function("Oskar")
my_name = 'Oskar'
b = function(my_name)
my_name = input('What is your name? ')
b = function(my_name)

(Along with an infinite number of other examples, of course.)

Answered by 0x5453 on February 9, 2021

When you type Osakar python interpreter expects a variable which is not defined in your case.

Please note that Oskar is different from 'Oscar'. The first is a variable (that must be defined first). While the latter is a string.

Even if you use sting 'Oscar' you cannot use it with your function. Because the + does not work between a string and an integer.

Answered by Amir Afianian on February 9, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP