Page 1 of 1

Can str be used as a variable?

Posted: Wed Feb 02, 2022 2:37 am
by FlyingDoggyJake
I'm just learning python and I decided to take a beginners online quiz to test myself. One of the questions was this:

8. What is the output of the following code?

Code: Select all

str = "pynative"
print (str[1:3])

A. py
B. yn
C. pyn
D. yna

Because of the slice() function the anwer is B. But that's not my question. I thought it was odd that they used "str" as a variable. I wasn't even aware that you could use a built-in function as a variable. I would have thought that at a minimum this is poor coding practice. Am I missing something here?

Re: Can str be used as a variable?

Posted: Wed Feb 02, 2022 6:32 am
by Ayuto
Yes, you could use it as a variable name, but you should avoid it as it's not good practice. Since you overwrote it you will have problems actually calling the original str built-in, which will result into errors. There are possibilities to restore it, but it's better to not call your variable like that in the first place.

Re: Can str be used as a variable?

Posted: Thu Feb 03, 2022 11:43 pm
by FlyingDoggyJake
Ok, thanks for the clarification Ayuto. That's kind of what I figured.