Python variables&variable types

Definition:

A variable is the name of the memory address where the current data is stored.

Variable Name; value.

  • Creating a variable in memory will include:
    1. The name of the variable
    2. Variable saved data
    3. The type of variable storage data
    4. The address of the variable (indicated)

Note:

  • Variable names can only be used when First appearance That's what it is Define variables
  • The variable name reappears, not defining the variable, but directly using the previously defined variable
  • When defining variables, to ensure code formatting, one space should be left and one space should be left on each side of =
# 1. define the unit price of apples 
price = 8.5
# 2. choose apples 
weight = 7.5
# 3. calculate payment amount 
money = weight * price
# 4. just buy an apple and return 5 yuan 
money = money - 5
print(money)

Naming of variables

Identifiers

The identifier is defined by the programmer Variable Name Function Name .

  • name Need to have To see the name and understand the meaning The effect of
  • The identifier can be represented by letter Underline And number Composition
  • Cannot start with a number
  • Cannot have the same name as the keyword
  • Python identifier Yes Case sensitive

Naming conventions:

1. To see the name and understand the meaning.

2 Camel Naming Method .

  • When Variable Name When it is composed of two or more words, the camel hump naming method can be used to name it
  • Lower Camel Case
    • The first word starts with a lowercase letter, and the first letters of subsequent words are capitalized
    • For example: firstName, lastName
  • Upper Camel Case
    • Use uppercase letters for the first letter of each word
    • For example: FirstName, LastName, CamelCase

3. Underline .

In Python, if Variable Name Required by Two Or Multiple words When composing, it can be named in the following way.

  1. Use lowercase letters for each word
  2. Use between words _Underline Connection
  3. For example: first_name, last_name, qq_number, qq_password
Keywords

keyword It is the identifier already used within Python.

  • keyword Having special functions and meanings
  • Developer It is not allowed to define identifiers for names that match keywords

You can view the keywords in Python by using the following command.

In [1]: import keyword
In [2]: print(keyword.kwlist)

The data type of the variable

In Python, variables do not require specifying a type. Python can automatically deduce the type of data stored in variables based on the value to the right of the equal sign.

Python 3 Basic Data Types | Rookie Tutorial.

Three types of numbers

Int integer 3 float 3.14 complex complex complex 3; 2j (may not have a preceding real part, but must have a complex imaginary part).

Python 3 Number | Rookie Tutorial.

Boolean type

Bool Boolean type with uppercase first letter, note not to use quotation marks, usually used for conditional judgment.

  • True non-zero digits
  • False number 0

True and False can be added to numbers, True== 1. False= 0 will return True , but the type can be determined by is .

>>> True==1
True
>>> False==0
True
>>> True+1
2
>>> False+1
1
>>> 1 is True
False
>>> 0 is False
False

character string

Str string; Tom" Tom''' Tom''""" Tom""

In Python, strings can be separated using + Splicing to generate a new string.

In [1]: first_name = "three"
In [2]: last_name = "zhang"
In [3]: first_name + last_name
Out[3]: 'three sheets'

String variables Can communicate with integer Using * to repeatedly concatenate the same string.

In [1]: "-" * 50
Out[1]: '--------------------------------------------------'
Advanced Types

Please refer to another blog post for more details.

Advanced Variable Types in Python_One ² Å ¹ ⁹'s Blog - CSDN Blog.

list list [1,2.0,False,'tom'] 
tuple tuple (1,2 .0,False,'tom')
dict dictionary{'name':'tom','age':'29'}, tuples are composed of keys( key )sum value( value )the key value pairs formed 
set set {11,22,33,11} is unordered, creating an empty set set() 

None

None represents the specific type to be determined, or in other words, the specific type is uncertain.

Expansion:

 sequence( sequence):str、bytes、list、tuple
 shapes, floating-point, and boolean types have no length 
print(len({}))
print(len(9))  

Variable and immutable types

Immutable type The data in memory cannot be modified:

  • Number types int, bool, float, complex, long(2.x)
  • String str
  • Tuple tuple

Variable type The data in memory can be modified:

  • List list
  • Dictionary dict

take care .

  1. Variable type The data changes are achieved through method To achieve
  2. If a variable of variable type is assigned a new data value, References will be modified
    • Variables No longer Reference to previous data
    • Variables Change to Reference to newly assigned data
a = 1
a = "hello"
a = [1, 2, 3]
a = [3, 2, 1]
demo_list = [1, 2, 3]
print("define the memory address after the list %d" % id(demo_list))
demo_list.append(999)
demo_list.pop(0)
demo_list.remove(2)
demo_list[0] = 10
print("modified memory address after data modification %d" % id(demo_list))
demo_dict = {"name": "xiaoming"}
print("define the memory address after the dictionary %d" % id(demo_dict))
demo_dict["age"] = 18
demo_dict.pop("name")
demo_dict["name"] = "lao wang"
print("modified memory address after data modification %d" % id(demo_dict))

Expansion: Hash (hash)

  • There is a built-in function called hash(o) in Python;
    • Receive a Immutable type Data as parameter
    • return The result is a integer
  • Hashing is a type of algorithm Its function is to extract data Signature code (fingerprint)
    • Same content Obtain Same result
    • Different contents Obtain Different results
  • In Python, set the dictionary's Key value pairs At this time, key will first be subjected to hash to determine how to save dictionary data in memory, in order to facilitate follow-up Operation on dictionary: Add, delete, modify, check
    • The key of key value pairs must be immutable type data
    • The value of key value pairs can be any type of data

Local and global variables

Local variables

Local variables are variables defined within a function and can only be used within the function; Different functions can define local variables with the same name, but they do not affect each other.

def demo1():
num = 10
print(num)
num = 20
print("after modification %d" % num)
def demo2():
num = 100
print(num)
demo1()
demo2()
print("over")

The lifecycle of local variables: .

  • The so-called lifecycle refers to the process of variables being created and then recycled by the system;
  • Local variables are only created during function execution;
  • After the function execution is completed, the local variable is returned by the system

The role of local variables: .

  • Used internally within a function, temporarily saving the data needed within the function
Global variables

Global variables are variables defined outside of a function and can be used internally within all functions.

Note:

When a function is executed and variables need to be processed, it will:

  1. First, check if there is a local variable with the specified name inside the function. If there is, use it directly
  2. If not, check if there is a global variable with the specified name outside the function. If there is, use it directly
  3. If not yet, the program will report an error!

It is not allowed to directly modify the reference of global variables:

  1. Using assignment statements to modify the value of a global variable only defines a local variable and does not modify it to the global variable. It's just that the variable names are the same
  2. If global variables need to be modified in a function, they need to be declared using global

Location of global variable definition:

  • To ensure that all functions can use global variables correctly, global variables should be defined above other functions