In this tutorial, we’ll study variables. Python variables are related the closest to PHP and Perl, except they don’t start with any symbols. In Python, both concatenation and addition are done with +. All the others you would expect.
Python variables are generic; you don’t have to declare them with a type [int,string,char etc...] or with var, you just simply use them. A variable can hold a number at one point, and later in the program hold a string of characters.
varone = 5
vartwo = 6
After assigning the variables, you can add them together and store them in another variable:
varthree = varone + vartwo
This assigns varthree to 11. You can subtract, multiply, and divide in the same way. You can divide vartwo in half like this:
vartwo /= 2
This takes vartwo, divides it by two, then assigns it back to vartwo. So since we had vartwo set to 6, it would now be set to 3. You can multiply by two with *=, add two with +=, subtract two with -= etc...
Strings are slightly different.
stringone = "Hello"
stringtwo = "World"
greeting = stringone + " " + stringtwo
This gives the variable greeting the value "Hello World". Commas do virtually the same thing as + with strings, except commas insert spaces. The above greeting assignment does the same thing as the following:
greeting = stringone,stringtwo
+ | Addition / Concatenation |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Modulos |
** | Powers |
Python variables are generic; you don’t have to declare them with a type [int,string,char etc...] or with var, you just simply use them. A variable can hold a number at one point, and later in the program hold a string of characters.
varone = 5
vartwo = 6
After assigning the variables, you can add them together and store them in another variable:
varthree = varone + vartwo
This assigns varthree to 11. You can subtract, multiply, and divide in the same way. You can divide vartwo in half like this:
vartwo /= 2
This takes vartwo, divides it by two, then assigns it back to vartwo. So since we had vartwo set to 6, it would now be set to 3. You can multiply by two with *=, add two with +=, subtract two with -= etc...
Strings are slightly different.
stringone = "Hello"
stringtwo = "World"
greeting = stringone + " " + stringtwo
This gives the variable greeting the value "Hello World". Commas do virtually the same thing as + with strings, except commas insert spaces. The above greeting assignment does the same thing as the following:
greeting = stringone,stringtwo