python basis - variables and constants

constant

  • A memory unit for storing a fixed value, the value of a constant can not be changed in the program; Python was not named constant , that is not as constant as the C language to a name.
  • Constant python comprising: a number, string, Boolean, null ;

>>> 'python'
'python'
>>> 3
3
>>> True
True
>>> []
[]

 

variable

  • Python is no need to declare variables. Each variable must be assigned before use , variable assignment after the variable will be created.
  • In Python, a variable is a variable, it is not the type we call "type" is the type of objects in memory within the meaning of the variables.
  • Equal sign (=) is used to assign values ​​to variables.
  • The left side of the equal sign (=) operator is a variable name, an equal sign (=) operator is the right value stored in the variable
# Variables must "define" before use (ie to the variable a value), or an error:
>>> the n-    # try to access an undefined variable
Traceback (MOST recent Results Last Call):
File "<stdin>", . 1 Line, in <Module1>
NameError: name 'n-' IS Not defined

# Variable assignment
>>> counter = 100 # integer variable >>> = 1000.0 Miles # float variable >>> name = " runoob " # string >>> Print (counter) 100 >>> Print (Miles) 1000.0 >>> Print (name) runoob

# variable value exchange
>>> A =. 1
>>> B = 2
>>> A, B = B, A
>>> Print (A, B)
2. 1


plurality of variable # assignment
>>> a = b = c = 1
>>> print(a,b,c)
1 1 1
>>> a, b, c = 1, 2, "python"
>>> print(a,b,c)
1 2 python
 

 

 

id (identity)

A =. 1 >>> 
>>> ID (A) indicates a value #id location in memory, it may determine whether the two values are the same object
 498 232 336 
>>> ID (A) represented by two values are the same values #id in memory the same place, the same thing
 498 232 336 
>>> B = 300 
>>> ID (B)
 59,417,712 
>>> ID (30 )
 498 233 264

 Note: number between 1-256 in memory in python present in the same location

Example:

>>> a=1001
>>> a is 1001
False
>>> b=1
>>> b is 1
True

# Assignment by reference (the same memory address)

>>> a=1000
>>> id(a)
57192176
>>> b=a  #=引用赋值
>>> id(b)
57192176

 

Exercise: Write a program to find the id number is not the same, from a number of traversing back, first find a different number

algorithm:

1. Generate a 300 number for

2. Take a few contrast, it is determined whether the same id declare a constant value, after each comparison +1

3. Stop the cycle after the find and print

>>> num =0
>>> for i in range(300):
...     if id(i) != id(num):
...         print(i)
...         break
...     num +=1
...
257

 

Guess you like

Origin www.cnblogs.com/wenm1128/p/11549658.html