Thursday, 4 April 2024

Python Variable

 

Variable


A variable is a container for a value. It can be assigned a name, you can use it to refer to it later in the program.

Based on the value assigned, the interpreter decides its data type. You can always store a different type in a variable.

For example, if you store 5 in a variable, later, you can store ‘Balaji’.


1. Python Variables Naming Rules

There are certain rules to what you can name a variable(called an identifier).

Python variables can only begin with a letter(A-Z/a-z) or an underscore(_).


Program:1

answer=4

answer

# Scripts Ends 

Output:

4



Program:2

9lives=9

# Scripts Ends 

Output:

SyntaxError: invalid syntax


The rest of the identifier may contain letters(A-Z/a-z), underscores(_), and numbers(0-9).


Program:3

year2021_='Good'

year2021

# Scripts Ends 

Output:

Good

Python is case-sensitive, and so are Python identifiers. Name and name are two different identifiers.


Program:4

name='Balaji'

Name

# Scripts Ends 

Output:

NameError: name ‘Name’ is not defined


2. Assigning and Reassigning Python Variables

To assign a value to Python variables, you don’t need to declare its type.

You name it according to the rules stated in section 2a and type the value after the equal sign(=).

Like a=3,Bob=7,age=75 etc...


3. Multiple Assignment

You can assign values to multiple Python variables in one statement.

Or you can assign the same value to multiple Python variables.

Program:5

Zip,city=88901,'las vegas'

print(Zip,city)

#same value to multiple Python variables.

age_Bob=age_david=40

print(age_Bob,age_david)


# Scripts Ends 

Output:

88901 las vegas

40 40


4. Swapping Variables

Swapping means interchanging values. To swap Python variables, you don’t need to do much.


Program:6

colour_1,colour_2='red','blue'

colour_1,colour_2=colour_2,colour_1

print(colour_1,colour_2)

# Scripts Ends 

Output:

blue red


5. Deleting Variables

You can also delete Python variables using the keyword ‘del’.


Program:7

Colour_1='red'

del Colour_1

Colour_1

# Scripts Ends 

Output:

NameError: name 'Colour_1' is not defined


Reserved Words (Keywords)

The following identifiers are used as reserved words, or keywords of the language, and cannot be used as ordinary identifiers. They must be typed exactly as written here:


and

def

False

import

not

True

as

del

finally

in

or

try

assert

elif

for

is

pass

while

break

else

from

lambda

print

with

class

except

global

None

raise

yield

continue

exec

if

nonlocal

return



No comments:

Post a Comment

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts