Learn Python - Bit by bit #2

in python •  7 years ago  (edited)

python-logo-master-v3-TM.png
<< Learn Python - Bit by bit #1 - print()

Today's topic? Variable

If you read Learn Python - Bit by bit #1, you know how to print text in python. But what if you want to store some text and print it later. That's where the variable comes into play.

Go to repl.it and choose Python3 as the language. Inside main.py type:

text = "Hello World"
print(text)

Now click run.

Same result as our first lesson but this time we used a variable named text to store our text before printing it. Now the variable name can be anything. Instead of using text you can use spiderman as your variable name.

spiderman = "Hello World"
print(spiderman)

It just needs to be something that makes sense. Why must it make some sense? Suppose you have 10 variables, it's too hard to remember what is stored in spiderman or batman because we are storing some random text in it which have no relation with spiderman or batman. So text or hellotext seems more makes-sense type variable names.

A word of caution:
Redefining a variable name again will replace its content with a new one.

text = "Hi"
text = "Bye"
print(text)

Prints Bye

Now even though you are free to use any name you like, you gotta follow some rules. Yep! Rules! You gotta obey it otherwise the python interpreter will yell at you.

  1. Variable name must start with a letter or underscore _
    _text = "Valid Variable"
    text = "Valid Variable"
    123 = "Not Valid! SyntaxError: can't assign to literal"
    1text = "Not Valid! SyntaxError: invalid syntax"

  2. The rest of the variable name can consist of numbers, letters or underscores
    _text_ = "Valid Variable"
    text123 = "Valid Variable"
    text$ = "Not Valid! SyntaxError: invalid syntax"

  3. Variable names are case sensitive. text and Text are different.

text = "Hello"
Text = "World"

print(text) will print Hello
print(Text) will print World

So that's it for today. Have a nice day :)
Learn Python - Bit by bit #3 - input() >>

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Hey, just wanted to let you know I gave you an upvote because I appreciate your content! =D See you around