Variable names can be made out of underscores (_), letters or numbers, but they have to start with an underscore or a letter.
Some example of valid variable names are:
mystring
_mystring
mystring1
To initialize (set a variable to hold some information) a variable, you'd type the variable name then equal sign then the value/data you'd like the variable to have, for example:
my_name = "John"
It'll set the variable named on the left of the equal sign to hold whatever data you have on right of the equal sign.
For fun and practical purposes I'll show you how to concatenate (combine) strings in Python.
You can concatenate strings by using the plus (+) signs between 2 or more strings. For example, if you want to combine "John" and "Smith", you'd type:
"John" + "Smith"
Now, that you know how declare variables and concatenate strings, let's have some fun. We'll declare a variable named
firstname
, another one named lastname
, and one last one named fullname
that uses concatenation to combine the 2 previous variables (with a space character between them for neatness) like below:firstname = "John"
lastname = "Smith"
fullname = firstname + " " + lastname
Now it's your turn to play around with what you've learned here (Click Run to run code).
Try playing around with different strings and different variable names.
Next lesson: Numbers in Python - Previous lesson: Strings in Python