In the first post, I learnt how to install Python, install the text editor and the first script using print function.
In this learning note, I will show you what I learned today.
Variable.
What is a Variable in Python? Variables are like containers for storing data values.
How to define a variable? It’s simple, Python has no command for declaring a variable like other languages, for example SQL. The variable is defined when you first assign a value to it. And I also learned that the variable name in Python is case sensitive. I will show you more in my examples.
Open your Spyder or PyCharm. Type or copy below codes. Copy and paste (or type) one line at a time. Run it. Then start with another line.
Variables are containers for storing data values.
print(“My name is XRKnows!”)
variable1= ‘My’
variable2=’name’
variable3 = ‘is’
Name = ‘XRKnows!’
print(variable1+’ ‘+variable2+’ ‘+variable3)
print(variable1+’ ‘+variable2+’ ‘+variable3+name)
print(variable1+’ ‘+variable2+’ ‘+variable3+Name)
print(variable1+’ ‘+variable2+’ ‘+variable3+’ ‘+ Name)
The green codes demonstrate how to define variables. We’re making four variables, each with a unique name. It’s worth noting that the last variable, Name, is capitalized.
Now we can start to use the variables. We can connect the variables with a plus (+) sign. It is used to concatenating strings. Since I would like to have a space between each of the variables, I added a ‘ ‘. Note there is space between the two single quote. This way the variables will be printed out with a space in between. Please try the first blue colored print statement.
Next, let’s test if the variables are case sensitive. Copy or type the 2nd blue print statement into your editor and executed it. Notice the letter “n” in Variable “name” in this statement was in lower case. However, we defined a variable named “Name” with N in upper case. What result do you get??
NameError: name ‘name’ is not defined
Yes, I got the same error. It won’t run because Python variable is case sensitive, so the variable name is not defined and Python can’t have it run successfully without knowing what strings “name” contained.
Next, let’s try the last print statement that in yellow color.
What result you see after executing it? I got below.
My name isXRKnows!
Yes, I know. We’d better put another space between the is and XRKnows. Let’s give the last red print statement a try.
My name is XRKnows!
Yeah! Now it’s perfect!
Did you notice this statement produced exactly same result was produced from the first print statement. print(“My name is XRKnows!”)
Note, how the string works and the variables work? Let me know if you have any questions. I will share more of what I learned in the future.
Happy learning!
Pingback: Learn all the basics of python – Python beginners, let’s learn together (3) – XRKnows