Basic Variables in Python

Today, we have been playing with basic variables in Python. The plan is to output something similar to the following:

Hello World
1 + 1 = 2
2 + 2 = 4
4 + 4 = 8

This output is to be generated entirely from calling variables.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
#OUTPUT
print(firstWord + space + secondWord)

Now, as you can see, the first line of the output is somewhat easy to code. We declared the variables firstWord, secondWord, and space and then called them to print concatenated together.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
firstAddend = 1
firstProblemSum = firstAddend + firstAddend
secondAddend = firstProblemSum
secondProblemSum = secondAddend + secondAddend
thirdAddend = secondProblemSum
thirdProblemSum = thirdAddend + thirdAddend
#OUTPUT
print(firstWord + space + secondWord)
print(firstAddend + " + " + firstAddend + " = " + firstProblemSum)
print(secondAddend + " + " + secondAddend + " = " + secondProblemSum)
print(thirdAddend + " + " + thirdAddend + " = " + thirdProblemSum)

Things start to act problematically when we try to produce the last 3 lines of output. When we run the application, we receive an error because we are attempting to mix string and integer variables on a combined output line.

To resolve this issue, we must typecast the integers as strings.

#Programmer Name: Eric Evans, M.Ed.
#Program Name: 02 - Hello Variable
#Program Description: Outputs assigned information using only variables.
#
#DECLARATION OF VARIABLES
firstWord = "Hello"
secondWord = "World"
space = ' '
firstAddend = 1
firstProblemSum = firstAddend + firstAddend
secondAddend = firstProblemSum
secondProblemSum = secondAddend + secondAddend
thirdAddend = secondProblemSum
thirdProblemSum = thirdAddend + thirdAddend
#CASTING OF VARIABLES
firstProblemSum = str(firstProblemSum)
firstAddend = str(firstAddend)
secondProblemSum = str(secondProblemSum)
secondAddend = str(secondAddend)
thirdProblemSum = str(thirdProblemSum)
thirdAddend = str(thirdAddend)
#OUTPUT
print(firstWord + space + secondWord)
print(firstAddend + " + " + firstAddend + " = " + firstProblemSum)
print(secondAddend + " + " + secondAddend + " = " + secondProblemSum)
print(thirdAddend + " + " + thirdAddend + " = " + thirdProblemSum)

As you can see, on lines 15 – 21 we cast each of the integer variables as a string variable. At this point, lines 24 – 26 will execute as expected.

The compilable code can be viewed at https://repl.it/HesM/3

Leave a Reply

Your email address will not be published. Required fields are marked *