0% found this document useful (0 votes)
8 views1 page

Understanding Python Variables

The document explains the concept of variables in programming, including how to declare, assign, and modify them. It outlines naming rules for variables, common errors such as NameError, and demonstrates various operations like changing values and deleting variables. Additionally, it provides examples of valid and invalid variable names, as well as exercises for practice.

Uploaded by

Atharv Kulkarni
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)
8 views1 page

Understanding Python Variables

The document explains the concept of variables in programming, including how to declare, assign, and modify them. It outlines naming rules for variables, common errors such as NameError, and demonstrates various operations like changing values and deleting variables. Additionally, it provides examples of valid and invalid variable names, as well as exercises for practice.

Uploaded by

Atharv Kulkarni
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

Variables

Variables are used to store data types like string, integer and float values.

In [1]: message1 = 'Hello python world'


message2 = "Hello python world"
message3 = """Hello python world"""
message4 = 100
print(message1)
print(message2)
print(message3)
print(message4)

Hello python world


Hello python world
Hello python world
100

A variables holds a value that can be modified or changed at any point.

Naming Rules:

1. Variables name can only contain letters, numbers, and underscores.


2. Variable names can start with a letter or an underscore, but can not start with a number.
3. Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of "student name".
4. You cannot use Python keywords as variable names.
5. Variable names should be descriptive, without being too long. For example mc_wheels is better than just "wheels", and number_of_wheels_on_a_motorycle.
6. Variable names are case-sensitive (Ram, ram and RAM are three different variables)

In [2]: #Valid variable names:


myvar = "Hello World"
my_var = "Hello World"
_my_var = "Hello World"
myVar = "Hello World"
MYVAR = "Hello World"
myvar2 = "Hello World"
#Invalid variable names:
2myvar = "Hello World"
my-var = "Hello World"
my var = "Hello World"
in = "Hello World"

Cell In[2], line 9


2myvar = "Hello World"
^
SyntaxError: invalid decimal literal

Name Error:
There is one common error when using variables, that the user will almost certainly encounter at some point. Take a look at this code, and see if you can figure out why it causes an error.

In [3]: # my assigned variable name is message and not messages


message = "Hello World"
print(messages)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[3], line 3
1 # my variable name is message and not messages
2 message = "Hello World"
----> 3 print(messages)

NameError: name 'messages' is not defined

In [4]: # Similarly, my assigned variable namem in this code is variable and not Variable
variable = "Hello World"
print(Variable)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 3
1 # Similarly, my assigned variable namem in this code is variable and not Variable
2 variable = "Hello World"
----> 3 print(Variable)

NameError: name 'Variable' is not defined

Assigning a value to a variable


In [5]: #Assigning a value to a variable
school = "Elpro International School: A Powerhouse of Learning"
print(school)

Elpro International School: A Powerhouse of Learning

Changing value of a variable


In [6]: #Changing value of a variable
school = "Elpro International School: A Powerhouse of Learning"
print(school)
school = "Best School in Pune"
print(school)

Elpro International School: A Powerhouse of Learning


Best School in Pune

Assigning different values to different variables in single line


In [7]: # Assigning different values to different variables in single line
x,y,z = 7,3.1415,"Hello World"
print(x)
print(type(x))
print(y)
print(type(y))
print(z)
print(type(z))

7
<class 'int'>
3.1415
<class 'float'>
Hello World
<class 'str'>

Assigning same value to different variables


In [9]: # Assigning same value to different variable
a=b=c="Hello World"
print(a)
print(b)
print(c)

Hello World
Hello World
Hello World

In [10]: # Assigning same value to different variable


l=m=n="Hello World"
print(l)
print(m)
print(n)

Hello World
Hello World
Hello World

Deleting a variable
In [11]: # deleting a variable
var = "Newton's third law states that for every action in nature there is an equal and opposite reaction."
print(var)
del var
print(var)

Newton's third law states that for every action in nature there is an equal and opposite reaction.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[11], line 5
3 print(var)
4 del var
----> 5 print(var)

NameError: name 'var' is not defined

Types of Variables
In [12]: #Types of Variables
var = "Hello Friends, Good Morning" # string type variable
var1 = 99 # integer type variable
var2 = 3.1415 # float type variable
var3 = True # boolean type variable
var4 = False # boolean type variable

Exercises:
1. Hello World - variable: Store your own version of the message "Hello World" in a variable, and print it.

In [13]: variable = "Hello World"


print(variable)

Hello World

1. One Variable, Two Messages: Store a message in a variable, and then print that message. Store a new message in the same variable, and then print that new message.

In [14]: variable = "Hello Python"


print(variable)

variable = "Hello Java"


print(variable)

Hello Python
Hello Java

Common questions

Powered by AI

Deletion of a variable in Python is executed using the 'del' statement (e.g., 'del var'). If a deleted variable is subsequently referenced, it results in a NameError as the reference is undefined after deletion . This requires programmers to carefully manage variable scope and existence in code .

In Python, variable assignment links a name to a value (e.g., 'school = "Elpro International School"'). Re-assignment changes the value of an existing variable to a new one (e.g., 'school = "Best School in Pune"'). This flexibility allows variables to be updated as needed during program execution .

Python handles different data types through dynamic typing, which allows variables to change their type during execution without explicit type declarations. For instance, a variable initially assigned an integer can later be assigned a string. This flexibility enhances coding efficiency but necessitates careful type management to avoid runtime errors .

Assigning the same value to multiple variables can be beneficial for initializing them with a common starting value, facilitating consistent behavior in different parts of a program. Python simplifies this with syntax like 'a = b = c = "Hello World"', which assigns the same value to 'a', 'b', and 'c' simultaneously .

Key rules for variable naming in Python include: starting names with a letter or underscore, using only letters, numbers, and underscores in the name, avoiding spaces (using underscores instead), not using Python keywords, and ensuring names are case-sensitive . These rules are crucial for avoiding syntax errors, ensuring code readability, and preventing naming conflicts in programming .

Descriptive naming conventions enhance code readability by providing clear context and intent, making it easier to understand and maintain the code over time. For example, 'number_of_wheels' is more descriptive than just 'wheels' . Consistent naming practices contribute to effective communication among team members and facilitate debugging .

Python does not allow spaces within variable names, necessitating the use of underscores (_) as substitutes, as shown in 'student_name' . This restriction ensures that variable names are interpreted correctly without confusion with separate tokens, maintaining syntactic clarity .

Case sensitivity in Python variable names can lead to NameError if a programmer inconsistently uses different casing for the same variable. For instance, defining 'variable' but mistakenly using 'Variable' in the code results in an undefined name error . This necessitates attention to detail when debugging to ensure consistency in variable naming .

Common errors with variables in Python include SyntaxError from invalid naming, NameError from undefined variables, and unintended results from case sensitivity. These can be prevented by adhering strictly to naming conventions, ensuring consistent usage of variable names, and using descriptive variable names to enhance readability and maintainability .

Using Python keywords as variable names leads to syntax errors because these keywords are reserved for specific functions in the language's syntax . To avoid errors, developers should consult Python's list of keywords and ensure that variable names are descriptive and distinct from these reserved words .

You might also like