Chapter: Variables
The Tale of Variables
In our previous quest, we learned about Numbers and Strings. Now, it's time to discover
🎁
the secret language of Variables and Data Types. In Python, variables are like magic
boxes .
They can hold strings, numbers, or even a spell (or what we humans call "functions")!
Imagine you have a treasure chest, and instead of gold, it is filled with phrases or
numbers you need to use over and over again. Instead of carrying this bulky chest
around, you could just use a magical word that could summon whatever is inside it.
That's precisely what variables do!
Creating a Variable: A set of rules
1. When naming your variable, it must start with a letter or an underscore, but never
with a number.
2. Variable names can only contain alpha-numeric characters and underscores (A-z,
0-9, and _). Beware of special characters; they will anger the Python gods!
3. Variable names are case-sensitive, just like passwords. (Remember, "password",
"Password", and "PASSWORD" are different!)
4. Choose names that are easy to remember and clearly describe the treasure they
hold. It's like naming a pet; you want it to be fun, unique, and meaningful.
Valid Variable Names:
firstname,
age,
num1,
first_name,
last_name,
year2021,
year_2021,
num2
Invalid Variables Names:
first-name,
first@name,
first$name,
num-1,
1num,
#sum,
*first
Python variable naming style
1. Python developers use snake case(snake_case) variable naming convention.
2. We use underscore character after each word for a variable containing more than
one word (eg. first_name, last_name).
Declaring a Variable: The Magic Spell ✨
In Python, you cast a spell on a variable by assigning a value to it. You can think of the
equal sign (=) as a magic wand that puts whatever value you want into the variable. The
"spell" to store "Anand" into a variable named "first_name" would look like this:
first_name = "Anand"
Now, every time you call upon first_name, Python will replace it with "Anand". So, the
next time you want to print your first name, you can just say:
print(first_name)
1. When we assign a certain data to a variable, it is called variable declaration. For
instance in the example above, my first name is assigned to a variable
first_name.
2. The equal sign is an assignment operator. Assigning means storing data in the
variable.
3. The equal sign in Python is not equality as in Mathematics.
4. Python variables can be a single character, a word or multiple words.
Remember, the kind of value you put in a variable determines its type. So, if you put a
string value into a variable, it becomes a string variable. If you put a number value into a
variable, it becomes a number variable. Pretty neat, right?
Examples: fruit = "apple", age = 12
Here, fruit is a string variable and age is a number variable.
The Power of Multiple Declarations:
You can also put different treasures into multiple boxes at the same time!
first_name, last_name, country, age, is_married = 'Siddhar', 'Sinha',
'India',39,True
Now print these variables and check values they have stored.
print(first_name)
print(age)
print('First name:', first_name)
print('Age: ', age)
print('Married: ', is_married)
#Note!! Use False not FALSE. Same with True, Don't use TRUE. We will learn about these data
types later.
Getting user input using the input() spell
You can even ask a fellow wizard (or user) for a value to put in your variable!
Using input() functions, we get an input from the user and store it in a variable.
first_name = input('What is your name, great wizard?: ')
age = input('How many seasons have you seen?: ')
Variable Operations:
Just like numbers, variables can also be added, subtracted, multiplied... But beware! You
can only do with variables what you can do with their values. If a variable holds a string,
you cannot subtract it. If a variable holds a number, you cannot multiply it by a word.
Only the operators corresponding to a variable's type are allowed for that variable.A
string variable only allows using the + and * operators, while a number variable can
use +, -, *, / etc.
Incorrect Operation:
fruit = "apple" print(fruit-1) #This will lead to an error!
Correct Operation:
age = 25
age = age + 5
print(age) #This will print 30.
Beware of the Unassigned Variable!
Never use a variable before you have assigned a value to it. That would be like trying to
open an empty treasure chest!
Below code will fail because the variable called "name" is not defined yet. So Python
does not know what value to put in for the variable called name.
print(“Hellp” + name) #This will lead to an error.
Borrowing Values:
Sometimes, a variable might want to borrow the value of another variable.
name = "Anand"
greeting = "Hello, " + name
print(greeting)
# This will print "Hello, Anand"
Assignment
Homework:
1. Practice the art of declaring multiple variables in 1 line.
2. Declare a year variable and assign a value to it.
3. Declare an age variable and assign a value to it.
4. Declare a is_married variable and assign a value to it.
5. Swap the values of 2 variables, like a magic trick!
6. Classroom Seats: A classroom has 5 rows of seats. Each row can seat 8
students. Write a program that asks the user how many students are in the class,
then calculates and prints the number of empty seats.
7. Temperature Conversion: Write a program that asks the user to input a
temperature in Fahrenheit and convert it to Celsius. The formula to convert
Fahrenheit to Celsius is (Fahrenheit - 32) * 5/9
8. Favorite Color: Ask the user to input their favorite color. Then print a sentence
saying "Your favorite color is _____." Replace the blank with the color the user
inputted.
9. Declare 5 as num_one and 4 as num_two. Perform these spells:
● Add num_one and num_two and assign the value to a variable total.
● Subtract num_two from num_one and assign the value to a variable diff.
● Multiply num_two and num_one and assign the value to a variable product.
● Divide num_one by num_two and assign the value to a variable division.
● Use modulus division to find num_two divided by num_one and assign the value to
a variable remainder.
Some Multiple choice questions:
1. What symbol is used for variable assignment in Python?
a) -
b) *
c) =
d) +
2. Which of the following is an invalid Python variable name?
a) first_name
b) _last_name
c) 1st_name
d) Lastname
3. Which of the following commands will print the variable name that contains the
string "John"?
a) print(name("John"))
b) [Link]
c) print("name")
d) print(name)
4. Is myVar the same as myvar in Python?
a) Yes
b) No
5. What is the output of the following code: x = 5; x = x + 5; print(x)
a) 10
b) 5
c) 25
d) Error
6. How can we assign the value 10 to a variable x in Python?
a) x == 10
b) 10 -> x
c) x <- 10
d) x = 10
7. What will be the output of print(num) after executing the following lines of code:
num = 10
num = 'ten'
a) 10
b) 'ten'
c) Error
d) None of the above
8. What is the output of the following code: a, b, c = 1, 2, 3; print(b)
a) 1
b) 2
c) 3
d) Error
9. Which function is used to get the user's input in Python?
a) user_input()
b) get_input()
c) input()
d) read_input()
10. Can we assign the value of a variable using the value of another variable in
Python?
a) Yes
b) No
11. Consider the following Python code:
var1 = 2
var2 = var1
var1 = 4
print(var2)
What will be printed?
a) 2
b) 4
c) var1
d) var2