Python [Post 02] | Variables

In Python a variable is created when we assign value to it. It does not required any explicit declaration. Use the assignment operator = to assign the value to a variable.

Variable Names Rules

  • Must start with a letter or the underscore character. Cannot start with a number.
  • Can only contain alpha-numeric characters and underscores (A-z, 0-9, & _ ).
  • Variable names are case-sensitive.
  • Avoid using Python Built-keywords. Like str, type, list etc.
#Example:

name = "John" # String Variable Assignment
age = 50 # Integer Variable Assignment
height = 150.50 # Float Variable Assignment

Using Python’s built-in function type() you can check what type of object is assigned to a variable.

Here are the list of Python data type:

  • int
  • float
  • str
  • list
  • tuple
  • dict
  • set
  • bool
# Exapmple

type(name)

str

## Dynamic Typing

In Python you can reassign variables to different data types. Python is very flexible in assigning data types.

# Example, Here Integer Assignment

x=50
type(x)

int

x="Hello, World!" # Re-assigned X Now String Assignment
type(x)

str

x=12.20+4j # Re-assigned X Now String Assignment
type(x)

complex

x=(1,2,3,4,5) # Re-assigned X Now Tuple Assignment
type(x)

tuple

## Re-assigning Variables

Python allow you to reassign variables with a reference to the same object.

a=50
print(a)

50

a = a + a
print(a)

100

a += 50
print(a)

150

a -= 10
print(a)

140

a *= 2
print(a)

280

a /= 5
print(a)

56.0

# Multiple Assignment

Python allows you to assign a value to multiple variables simultaneously.

# Example 1

length = width = height = 50
print (length)
print (width)
print (height)

50
50
50

# Example 2

length, width, height = (10,50,60)
print (length)
print (width)
print (height)

10
50
60


Thanks!

Happy Learning! Your feedback would be appreciated!

shobhitsingh.in

GitHub Code

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s