Can str be used as a variable?

All other Source.Python topics and issues.
User avatar
FlyingDoggyJake
Junior Member
Posts: 4
Joined: Tue Feb 01, 2022 3:11 am

Can str be used as a variable?

Postby FlyingDoggyJake » Wed Feb 02, 2022 2:37 am

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?
User avatar
Ayuto
Project Leader
Posts: 2193
Joined: Sat Jul 07, 2012 8:17 am
Location: Germany

Re: Can str be used as a variable?

Postby Ayuto » Wed Feb 02, 2022 6:32 am

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.
User avatar
FlyingDoggyJake
Junior Member
Posts: 4
Joined: Tue Feb 01, 2022 3:11 am

Re: Can str be used as a variable?

Postby FlyingDoggyJake » Thu Feb 03, 2022 11:43 pm

Ok, thanks for the clarification Ayuto. That's kind of what I figured.

Return to “General Discussion”

Who is online

Users browsing this forum: No registered users and 21 guests