0% found this document useful (0 votes)
38 views11 pages

03 Chapter Three - Variables

Machine Learning from Scratch with Python, Scikit-Learn & PyTorch by Bemnet Girma This book contains 3 chapters that cover machine learning concepts. Chapter 3 discusses variables in Python. It defines what variables are, how to create and use them, and what operations can be performed on variables such as assigning values, printing variables, taking user input, and more. The chapter also discusses variable data types, scopes, values, locations, lifetimes, and keywords.

Uploaded by

Bemnet Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views11 pages

03 Chapter Three - Variables

Machine Learning from Scratch with Python, Scikit-Learn & PyTorch by Bemnet Girma This book contains 3 chapters that cover machine learning concepts. Chapter 3 discusses variables in Python. It defines what variables are, how to create and use them, and what operations can be performed on variables such as assigning values, printing variables, taking user input, and more. The chapter also discusses variable data types, scopes, values, locations, lifetimes, and keywords.

Uploaded by

Bemnet Girma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Machine Learning from Scratch with Python, Scikit-Learn & PyTorch by Bemnet Girma

CHAPTER THREE

Variables

Objectives

What is a variable?
What are the properties of a variable?
How can we create and use variables in Python?
What is keyword?
What operations can be performed on variables?

keyboard_arrow_down Lesson One : Introduction to Variables


What is Variable?
Variable is the name which we give to the memory location which holds some data. With a variable we can
store the data, access the data and also manipulate the data.

PS. Variable is a container where you can store a value.

To summarize, a variable is a

Name
Refers to a value
Hold some data
Name of a memory location

💡 Let us consider librarians, how could they storeand access ton of books? They just make catalogue of
books based on their genre with their reference location. That is how variables also works.
Properties of a Variable
1. Type:

💡 What type of data you store in the variable?

Each data have a type whether it is number word or something and each variable should belong to one of the
data types. This is called the data type of the variable.

2. Scope:

💡 Who can access these data?

In any programming language, scope refers to the place or limit or boundaries or the part of the program
within which the variable is accessible.

3. Value:

💡 What do you store in the variable?

Each and every variable in a program holds value of some type which can be accessed or modified during the
due flow of the program.

4. Location:

💡 Where you store the variable?

As already stated, the data is stored in memory location. The variable is the name which we give to that
location. Each memory location has some address associated with it.

5. Lifetime:

💡 Till when the variable will be available?

The lifetime of a variable refers to the time period for which the memory location associated with the variable
stores the data.

How to create a variable in Python?


In python, to create a variable we just need to specify

Name of the variable


Assign value to the variable

Syntax to create variable:

name_of_the_variable = value

Ex. 3.1 ( Create a variable )

1 age = 21
How can I look for my variables?
To see your variable use print() function

Syntax to print a variable:

print(name_of_the_variable)

Ex. 3.2 ( Print a variable )

1 print(age)

21

What is print() function?


print() is a function that can print the specified message to your computer screen.

Syntax to print a message / text:

print("write your message here")

PS. Don’t worry we will discuss more about function later in Function Chapter.

Ex. 3.3 ( Print a message / text )

1 print("I am John")

I am John

💡 What if we want to print some message along with our variable?

Syntax to print message with a variable:

print("write your message here",name_of_the_variable)

Ex. 3.4 ( Print text along with a variable)

1 print("My age is",age)

My age is 21
EXERCISE 3.1

Create a variable "date" and store today's date then print it?

Hint: Output will be like below

Today's date is 6

1 # write your answer code here


2

💡 What if we want to submit value of a variable outside our code like questionnaire?

In such scenario we use input() function

What is input function?


input() is a function that can accept values from a user (you).

Syntax to submit value of a variable:

name_of_the_variable = input("Ask user to enter a value")

Ex. 3.5 ( Take input from a user )

1 age = input("Enter your age?\n")


2 print("Your age is",age)

Enter your age?


19
Your age is 19

Note: We can print meaningful text messages along with variables for better understanding.

Text message we should keep in within double quotes.


Text message and variable name should be separated by comma symbol.

EXERCISE 3.2

Create a variable "bd" and take input birth date from user then print it?

Hint: Output will be like below

Tell me your birthdate? 6

Your birthdate is 6
.

1 # write your answer code here


2

Invalid cases for variables


While defining variables in python,

Variable names should be on the left side.


Value should be on the right side.
Violating this will result in syntax error.

Ex. 3.6 ( Creating a variable in wrong direction )

1 17 = age

Cell In[8], line 1


17 = age
^
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

Rules for creating a variable


1. must start with letter or underscore

Ex. 3.7 ( Creating a variable with underscore )

1 _age = 23
2 print(_age)

23

2. cannot start with number

Ex. 3.8 ( Creating a variable starts with number )

1 1dollar = 76

Cell In[10], line 1


1dollar = 76
^
SyntaxError: invalid decimal literal
3. cannot use any special symbol

Ex. 3.9 ( Creating a variable with special symbol )

1 $dollar = 74

Cell In[11], line 1


$dollar = 74
^
SyntaxError: invalid syntax

4. can’t use space ( instead use underscore )

Ex. 3.10 ( Creating a variable using space )

1 My Age = 24

Cell In[12], line 1


My Age = 24
^
SyntaxError: invalid syntax

5. are case sensitive

PS. Case sensitive means you can’t use lowercase letters in place of uppercase and vice versa.

Ex. 3.11 ( Print a variable using wrong case )

1 age = 21
2 print(Age)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[13], line 2
1 age = 21
----> 2 print(Age)

NameError: name 'Age' is not defined

6. cannot be a keyword.

.
keyboard_arrow_down Lesson Two : Keywords
What is keyword?
Keywords are special reserved words, that have specific meanings and purposes.

All 33 keywords in python contain only alphabet symbols. All of them are in lower case except True, False,
and None.

To see all the keywords –

1 import keyword
2 keyword.kwlist

['False',
'None',
'True',
'and',
'as',
'assert',
'async',
'await',
'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']

PS. You cannot use these keywords as a variable, else will result in error.
Ex. 3.12 ( Creating a variable with keyword name )

1 class = 4

Cell In[15], line 1


class = 4
^
SyntaxError: invalid syntax

Multiple Variables in a Single Line


We can assign multiple variables to multiple values in a single one line. During assignment the variable name
on the left hand side should be equal with the values on the right hand side. If not it results in error.

Ex. 3.13 ( Assigning multiple variables)

1 Sid, age, grade = 4327, 24, 9


2 print(age, grade, Sid)

24 9 4327

Ex. 3.14 ( Unequal items on either side )

1 Sid, age, grade = 4327, 24

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[17], line 1
----> 1 Sid, age, grade = 4327, 24

ValueError: not enough values to unpack (expected 3, got 2)

Ex. 3.15 ( Unequal items on either side )

1 Sid, age = 4327, 24, 9

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[18], line 1
----> 1 Sid, age = 4327, 24, 9

ValueError: too many values to unpack (expected 2)


Single Value for multiple Variables
We can assign a single value to multiple variables simultaneously.

Ex. 3.16 ( Assign single value to multiple variables)

1 Sid = age = grade = 10


2 print(Sid, age, grade)

10 10 10

keyboard_arrow_down Lesson Three : Variable Operations


💡 What if we want to know memory location of a variable?

1. Memory Location of a variable

you can get Memory location of a variable using the syntax below:

id(variable_name)

PS. For sake of simplicity, from now onward MA means Memory Address of a variable.

Ex. 3.17 ( Get Memory Location of a variable )

1 dollar = 69
2 print("1$ = ",dollar)
3 print("MA of dollar:",id(dollar))

1$ = 69
MA of dollar: 140719801867176

💡 What if we want to change value of a variable?

2. Reassigning

you can update / reassign value of a variable using the syntax below:

variable_name = new_value

PS. While variable is reassigning, its memory location also changed.


Ex. 3.18 ( Updating the value of variable )

1 dollar = 69
2 print("In 2019, $1 =",dollar)
3 print("MA of dollar in 2019:",id(dollar))
4 dollar = 72
5 print("In 2020, $1 = ",dollar)
6 print("MA of dollar in 2020:",id(dollar))

In 2019, $1 = 69
MA of dollar in 2019: 140719801867176
In 2020, $1 = 72
MA of dollar in 2020: 140719801867272

💡 What if we want to delete a variable (remove from memory)?

3. Deleting

you can delete a variable using the syntax below:

del variable_name

Ex. 3.19 ( Deleting a variable )

1 book = 5
2 del book
3 print(book)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[22], line 3
1 book = 5
2 del book
----> 3 print(book)

NameError: name 'book' is not defined

Finally, What about Constants?


A constant is a type of variable whose value cannot be changed. It is helpful to think of constants as
containers that hold information which cannot be changed later.

Example – GRAVITY = 9.81

PS. We will discuss more about constants in later Chapter.


EXERCISE 3.3

Create a variable "ap" and accept "apple price" from user, then print user’s apple price
“ap” and its memory location, then next reassign apple price to 34, again print apple
price and its memory location, finally delete variable "ap"?

Hint: Output will be like below

NameError: name 'ap' is not defined


1 # write your answer code here
2

Key Takeaways

Variable is the name which we give to the memory location which holds some data.
Type, Scope, Value, Location and Lifetime are properties of a variable.
print() is a function that can print the specified message to your computer screen.
input() is a function that can accept values from a user (you).
Keywords are special reserved words, that have specific meanings and purposes.
Checking memory location, reassigning and deleting are operations you can perform on variables.

// END OF CHAPTER THREE

Click here for Chapter Four

You might also like