Embark
About Lesson
XP
Bolt
Strike

Variables & Assignment Statements

Think of RAM (Random Access Memory) in your computer as a simple list or array of numbered slots, starting at 0 and going up to as much memory as you  in your computer.

Every one of these memory locations can be used as a variable. That is, you can store a piece of data in any free memory slot.

Practically different types of data (integer, float, string, and Boolean) take up different amounts of memory, rather than a single “slot”.

An assignment statement has this general form:

				
					<variable> = <expression>
				
			

Anything written like <variable> is a placeholder – it means that you should replace that whole thing (including the brackets) with something that you choose.

It works like this: everything on the right side of the equals sign, is evaluated, and a value is computed.

The resulting value is assigned to (put into) the variable on the left.

				
					age = 29
name = 'Fred'
alive = True
gpa = 3.9

				
			

We can assign a value to multiple variables using:

				
					a = b = c = 5 # All a, b and c have the value 5

				
			

We can also assign different values to multiple variables in a single statement:

				
					a, b, c, d = 1, 2, 3, 4 # a is 1, b is 2, c is 3 and d is 4


				
			

Therefore, when you entered age = 29 and pressed Return or Enter, Python first looked to see if it had ever seen the variable name age before.

Since it had not, it allocated a memory slot somewhere (again, we don’t care where) attached the age label to it, and then put the value 29 into that memory slot.

A similar sequence happened for the other variables.

After executing that line, enter the following line and press Return or Enter:

				
					age = 31
				
			

Python does the same sequence of steps, but now it finds that there already is a variable named age.

Rather than create a new variable, Python overwrites the current value of the variable age with the new value of 31.

The variable name age stays the same, but the contents change.

				
					print(<whatever you want to see>)
				
			

This whatever you want to see can be a text string or it can be the result of a calculated expression.

				
					print('Hello World')
				
			
				
					Hello World
				
			

Try Yourself

Print the following line using the print statement:

Hi, learning Python with PyStrike is fun. 

Solution

				
					print("Hi, learning Python with PyStrike is fun.")
				
			
				
					Hi, learning Python with PyStrike is fun.
				
			

Printing a Variable's Value

				
					eggsInOmlette = 3
print(eggsInOmlette)
				
			
				
					3
				
			
				
					knowsHowToCook = True
print(knowsHowToCook)
				
			
				
					True
				
			

Try Yourself

Store a value of 311 in a variable and print the same using print statement.

Solution

				
					a = 311
print(a)
				
			
				
					311
				
			

Printing multiple things on a single line

The print statement can also print multiple things on a single line.

You can do this by separating the items you want to print with commas.

When the print statement runs, each comma is replaced by a space.

				
					eggsInOmlette = 3
knowsHowToCook = True
print(eggsInOmlette, knowsHowToCook)
				
			
				
					3 True
				
			
				
					numberInADozen = 12
print('There are', numberInADozen, 'items in a dozen')
				
			
				
					There are 12 items in a dozen
				
			

Try Yourself

Store a value of 311 in a variable and use the variable to print the following line:

My House Number is 311.

Solution

				
					a = 311
print("My House Number is",a)
				
			
				
					My House Number is 311
				
			

Printing one or more blank lines

To make things a little clearer in your output, you may want to include one or more blank lines.

To create a blank line of output, you can use an empty print statement – just write the word print with a set of open and close parentheses.

				
					print()
				
			

Try Yourself

Print the following statements:
My House Number is 311.

I live in United States of America.

Solution

				
					print("My House Number is 311")
print ()
print("I live in United States of America")
				
			
				
					My House Number is 311

I live in United States of America
				
			

Let’s suppose we have two variables a and b.

We can swap their values with

				
					a, b = b, a
				
			

It means if the value of a is 5 and b is 10, then the value of a will become 10 and b will become 5 after swapping.

				
					a = 5
b = 10

a, b = b, a
print(a) # prints 10
print(b) # prints 5

				
			

Try Yourself

Store two values in x and y and swap them.

x = 10

y = 20

Solution

				
					x=10
y=20

x,y = y,x

print(x)
print(y)

				
			
				
					20
10
				
			

We can delete a variable using del in Python.

				
					a = 5

print(a) # prints a

del a # a is deleted

print(a) # Gives error


				
			
				
					NameError: name 'a' is not defined on line 7
				
			
				
					a = 5
b = 9
print(id(a))
print(id(b))

				
			
				
					1
2
				
			
  1. Must start with a letter (or an underscore)

  2. Cannot start with a digit

  3. Can have up to 256 total characters

  4. Can include letters, digits, underscores, dollar signs, and other characters

  5. Cannot contain spaces

  6. Cannot contain math symbols (+, -, /, *, %, parentheses)

Here are some examples of illegal names:

  • 49ers (starts with a digit)

  • table+chairs (contains a plus sign)

  • my age (contains a space)

  • (coins) (uses parentheses)

Naming Conventions

A convention is an agreed-upon way of doing things.

In programming, you can create any variable name you want as long as it follows the  rules.

However, when creating variable names, it is strongly suggested that you use a naming convention i.e. a consistent approach for creating names for variables.

A. For one word:

The convention is to use all lowercase letters.

B. For putting together two or more words:

1. camelcase convention

  • First word – all lowercase.

  • Every additional word – Make the first letter uppercase; All other letters lowercase.

Here are some examples of variable names that follow the camelcase naming convention:

  • someVariableName

  • anotherVariableName

  • countOfBadGuys

  • computerScore

  • humanScore

  • bonusPointsForCollectingMushrooms

The term camelcase describes the way variable names look when using this convention. When an uppercase letter starts a new word, it looks like the hump on a camel.

2. underscore convention

  • Separate words with underscores.

Here are some examples of variable names that follow the underscore naming convention:

  • this_is_a_variable_name

  • number_of_fish_in_aquarium

Avoid putting underscore (_) or double underscore (__) at the start and end of identifier names, because these have some special meaning in Python.

If you are coding on your own, obviously you can use whatever names you want, but it really is a good idea to be consistent when naming variables.

Remember, this is the general form of an assignment statement:

				
					<variable> = <expression>
				
			

The expression on the right-hand side can also contain variables.

				
					myAge = 31
yourAge = myAge
print(yourAge) # evaluates to 31 since the value of myAge has been assigned to yourAge
				
			
				
					31
				
			
				
					>>> myAge = 31
>>> yourAge = myAge
>>>
				
			

Whenever a variable appears in an expression (that is, on the right-hand side of an assignment statement), the expression is evaluated (computed) by using the value of each variable.

				
					numberOfMales = 5
numberOfFemales = 6
numberOfPeople = numberOfMales + numberOfFemales
print(numberOfPeople)
				
			
				
					11
				
			
				
					>>> numberOfMales = 5
>>> numberOfFemales = 6
>>> numberOfPeople = numberOfMales + numberOfFemales
>>>

				
			

The equals sign in an assignment statement is very different from the way an equals sign is used in math.

In math, the equals sign implies that the things on the left side and the right side have the same value.

In python it is used to assign the evaluated value on the right hand side to the variable written on the left hand side.

				
					myAge = 25
myAge = myAge + 1 # the value of myAge will now be 26
				
			
				
					>>> myAge = 25
>>> myAge = myAge + 1
>>>
				
			

The following is a list of the Python keywords.

and

as

assert

break

class

continue

def

del

elif

else

except

finally

for

from

global

if

import

in

is

lambda

nonlocal

not

or

pass

raise

return

try

while

with

yield

False

None

True

 

 

We know that computers only understand ones and zeros.

When you write code in Python, Python cannot run or execute your code directly.

Instead, it takes the code that you write and compiles it.

That is, Python converts your code into a language of ones and zeros that the computer can understand.

Every language has such a compiler.

When the Python compiler reads your code, it looks for special words called keywords to understand what your code is trying to say.

Python technically has an interpreter that turns your code into a machine independent byte code. 

But to make things simple, we’ll refer to this as the Python compiler.



            
0% Complete
Scroll to Top