Saturday 23 July 2016

Variables

All programming languages (that I know of) have variables. We assign values to variables, so that we can refer to that value by using the variable anywhere in the program. We define a variable using '=' sign. For example:

 a = 2
 

This means that the value 2 has been assigned to the variable. Anywhere from this point on, we use 'a', we are essentially using '2'. For example, the following code will output '2':

 print (a)
 

Output:

 2
 

In the Hello Python! post, instead of using "Hello Python" as a string, we could have used the following:

 greeting = "Hello"
 greetingTo = "Python"

 print (greeting + ", " + greetingTo +"!")
  

Output:

 Hello, Python!
  

In this way, we can change the greeting and the person we are greeting to by changing it in the variable name. For example:

 greeting = "Good morning"
 greetingTo = "Reader"


 print (greeting + ", " + greetingTo +"!")
 

Output:

 Good morning, Reader!

The comma and exclamation mark are hardcoded in the print statement as they don't really need to change.
More about variable names, types and use of the '+' operator in the future posts.

No comments:

Post a Comment