Define variable in Python

Literal

A literal is a number or string that appears directly in a program.

The following are all literals in Python:


42                       # Integer literal
3.14                     # Floating-point literal
1.0j                     # Imaginary literal
'hello'                  # String literal
"world"                  # Another string literal
"""Good night"""         # Triple-quoted string literal
#   w  ww . j  av a  2s  .c  o m

Using literals and delimiters, you can create data values of some other fundamental types:


[ 42, 3.14, 'hello' ]    # List
( 100, 200, 300 )        # Tuple
{ 'x':42, 'y':3.14 }     # Dictionary

Define variables

A variable is basically a name that represents some value.

You have to assign a value to a variable before you use it.


x = 3 
print x * 2 

The code above generates the following result.

Once a variable has been assigned, you can access it by using its name.


x = 4
y = 'this is a string'
print x
print y 

The code above generates the following result.

Chained Assignments


x = y = 2 

print x
print y

The code above generates the following result.

Augmented Assignments


x = 2 
x += 1 
x *= 2 
print x 

The code above generates the following result.

Sequence Unpacking


x, y, z = 1, 2, 3 
print x, y, z 
x, y = y, x 
print x, y, z 

The code above generates the following result.

Dynamically typed

Python is dynamically typed, no pre-declaration of a variable or its type is necessary.

The type and value are initialized on assignment. Assignments are performed using the equal sign.


counter = 0# from  w  w w. j av a2s  . c o m
miles = 1000.0
name = 'Bob'
counter = counter + 1
kilometers = 1.609 * miles
print '%f miles is the same as %f km' % (miles, kilometers)

The code above generates the following result.

None placeholder


X = None                                     # None placeholder
print X #   w  w w  . j  a  v a  2s  .co m
L = [None] * 100                             # Initialize a list of 100 Nones
print L 

print type(L)                                # Types
print type(type(L))                          # Even types are objects

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules