Bytes

Variables in Python

Module - 2 Basics of Python Programming
Variables in Python

Overview

One of the fundamental concepts in Python is variables . Variables store information and give it a name to be referenced later in the code . They can be defined using a single equals sign (=) and hold many different types of data, such as strings 💬, integers 🔢, and booleans . In this tutorial, we will learn about variables in Python in depth .

What is a Variable?

Frame 15-min.png

A variable is a named storage location 📦 in a computer's memory 💾 that can hold a value 🔢, which can be changed 🔁 during the execution 💻 of a program

📝

📝
or script 📃. It is often used to store data 📊 that the program, such as user input , calculations 🧮, or intermediate results , may modify.

There are different types of variables, such as:

  • Numeric variables: 🔢
  • String variables:
    📝
    📝
  • Boolean variables: :green_circle:🔴
  • List variables: 📜
  • Tuple variables: 📦
  • Set variables: 🧮
  • Dictionary variables:
    📖
    📖

Imagine you work in a showcasing office📈and have been entrusted with following the execution of a unused promoting campaign for a client's item. To do this, you'll get to use variables in Python to store and control information. For that, we ought to get it how to make a variable.

How to create a variable

Frame 16-min.png

:man_technologist: Creating a variable is a fundamental concept in programming and can be done in several ways. The simplest way is to choose a name for your variable and use the assignment operator = to assign a value to it. This process allows you to store data in memory and reference it later in your program. To create a variable in Python, use this syntax:

 variable_name = value

Python is a dynamically typed language that infers the variable type at runtime. This allows for greater flexibility in programming and can make code easier to read and write.💰 We can create a variable to represent the budget for the campaign. You could name this variable "campaign_budget" and assign it a value of the total amount allocated for the campaign.

💸

campaign_budget = 50000

We need to track the number of impressions and clicks the campaign generates. Using multiple assignments, we can create two separate variables, "impressions" 📈 and "clicks"👆, to store this data. Additionally, Python supports multiple assignments, meaning you can assign multiple variables simultaneously.

impressions, clicks = 1000000, 5000

Creating a variable in Python is a simple process that involves choosing a name and assigning a value using the assignment operator. This assigns 1000000 to variable impressions and 5000 to variable clicks. This concept is crucial to programming in Python and is used extensively throughout the language.

Rules for creating a variable

Frame 39-min.png

There are a few rules we need to follow while creating a variable in Python:

  • Please ensure that the name only includes letters, numbers, and underscores. No other special characters are permitted like @,#,&.
  • The variable name should either begin with an Uppercase(A to Z) or Lowercase(a to z) character or an underscore(_). 🔡
  • The name must not begin with a number.
  • The name should be descriptive and easy to understand. 💡
  • The name is case-sensitive, meaning "age" and "Age" are two different variables. 🔤
  • Avoid using Python reserved words as variable names. ⚠️

Some valid variable names are:

harry
harry_potter
harryPotter
harryPotter2

Some invalid variable names are:

2harry   # cannot start with a number
harry-potter # cannot contain a hyphen
h@rry  # cannot contain a special character
harry potter #Spaces are not allowed in var names

How to re-declare a Variable in Python? :thinking:

In Python, you can redeclare a variable by assigning a new value. This is a fundamental operation in Python. Nevertheless, redeclaring a variable can cause unintended consequences, particularly if used in several places in your code. It is usually suggested to use new variable names rather than redeclaring current ones. If you need to redeclare a variable, make sure to thoroughly review your code for any potential issues that may arise.

number=12
print("Value before re-declaring the variable value", number)
number=189
print("Value after re-declaring the variable value", number)

How to assign the same value to multiple variables? :thinking:

To assign the same value to multiple variables, you can either use the assignment operator for each variable or a loop to assign the value to each variable. Before assigning, please verify that the assigned value is suitable for each variable and meets any constraints, such as data type or range.

number1=number2=number3=899

Casting of Variable↔️

Frame 17-min.png

The casting of variables involves converting a variable from one data type to another, and Python has a variety of built-in functions for converting variables, including:

int()

To cast a variable to an integer data type, use the int() function. Here's an example:

float_var = 8.5
cast_to_int = int(float_var)
print(cast_to_int) 

We used the int() function to convert the value of x to an integer and assign the result to a new variable called cast_to_int.

float()

To convert a variable to a float data type, use the float() function. See below for an example:

int_var = 11
cast_to_float = float(int_var)
print(cast_to_float)   

We use the float() function to convert x to a float and assign the result to a new variable cast_to_float.

str()

To turn a variable into a string data type, use the str() function. Here's an example:

int_var = 76
cast_to_str = str(int_var)
print(cast_to_str)   

We use the str() function to convert x to string and assign the result to a new variable cast_to_str.

bool()

To convert a variable to its boolean data type, you can use the bool() function. Here's an example:

int_var = 5
cast_to_bool = bool(int_var)
print(cast_to_bool)   

We use the bool() function to convert x to a boolean data type and assign the result to a new variable cast_to_bool.

Keywords in Python 🔑

Python keywords are unique words that have a specific meaning in the language. These words have a particular purpose and cannot be used as names for variables, functions, or anything else in your Python code. Here is a complete list of Python keywords:

  • and
  • as
  • assert
  • break
  • class
  • continue
  • def
  • del
  • Elif
  • else
  • except
  • False
  • finally
  • for
  • from
  • global
  • if
  • import
  • in
  • is
  • lambda
  • None
  • nonlocal
  • not
  • or
  • pass
  • raise
  • return
  • True
  • try
  • while
  • with

Conclusion:

Variables act as containers for information of various types, counting numbers, strings, lists, sets, dictionaries, and more. All through this instructional exercise, we've secured the essential concept of variables in Python. We've talked about how to make and name variables and reassign values and assign the same value to multiple factors. By acing these basics, readers are well-equipped to start their travel into programming with Python.

Key Takeaways:

  • In this lesson, we covered the topic of variables in Python. Variables serve as containers for data that can take on different data types.📦
  • In Python, we can create variables using the assignment operator and assign multiple ones simultaneously.
  • During our discussion, we covered the guidelines for creating variables in Python and their local or global scope. 🌎
  • We also learned how to redeclare a variable and assign the same value to multiple variables.🔄
  • Variables are an essential concept in programming, and it is necessary to comprehend them to write effective Python code.💻

Quiz:

  1. How do we create a variable in Python?
    1.  Choose a name for variable and use assignment operator to assign value to it 
    2. Choose a name for variable and use equals operator to assign value to it
    3. Choose a name for variable and use semicolon to assign value to it  
    4. None of the above

Answer: a) Choose a name for variable and use assignment operator to assign value to it

  1. What is the type of value inferred for a variable in Python? 
    1. static 
    2. dynamic 
    3. complex 
    4. None of the above

Answer: b) dynamic

  1. What is the syntax for multiple assignment in Python? 
    1. a, b, c = 1, 2, 3  
    2. a=1,b=2,c=3 
    3. a, b = 1, 2, 3 
    4. a and b

Answer: a) a, b, c = 1, 2, 3

  1. What is the scope of a variable in Python? 
    1. Determines the variable name 
    2. Determines the size of variable 
    3. Determines where it can be accessed in the program 
    4. Determines the type of variable

Answer: c) Determines where it can be accessed in the program

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter