Python101: 3. Variables and Data Types

post thumb
Python
by Admin/ on 01 Jul 2021

Python101: 3. Variables and Data Types


In this article we will learn about Python variables and data types.

Variables


Variables come from mathematics, and are abstract concepts in computer languages that can store the results of calculations or represent values, and can be accessed by variable names. In Python, variable names must be a combination of upper and lower case English, numbers, and underscores (_), and cannot begin with a number.

Variable naming rules:

  • Variable names can only be any combination of letters, numbers and underscores
  • The first character of the variable name cannot be a number
  • Variable names are case-sensitive, upper and lower case letters are considered to be two different characters
  • Special keywords cannot be named as variable names

Declare variables

Variables in Python do not need to be declared; each variable must be assigned a value before it can be used, and the variable is not created until it is assigned a value. In Python, a variable is a variable; it has no type, and what we mean by “type” is the type of the object in memory to which the variable refers.

name = "neo"

The above code declares a variable named: name, with the value of “neo”.

Variable assignment

In Python, the equal sign = is an assignment statement that allows you to assign any data type to a variable, and the same variable can be assigned repeatedly, and can be of different types.

a = 123 # a is an integer
a = 'abc' # a is a string

Such languages where the variables themselves are not of a fixed type are called dynamic languages, and their counterparts are static languages. Static languages must specify the type of the variable when defining the variable, and if the type does not match when assigning the value, an error will be reported. For example, if Java is a static language, the assignment will result in the following error.

Multiple variable assignment

Python allows you to assign values to multiple variables at the same time. For example.

a = b = c = 1

In the above example, an integer object is created with a value of 1. Assigning the value from back to front, the three variables are given the same value.

You can also specify multiple variables for multiple objects. For example.

a, b, c = 1, 2, "neo"

In the above example, the two integer objects 1 and 2 are assigned to variables a and b, and the string object “neo” is assigned to variable c.

Constant

A constant is a variable that cannot change, such as the common mathematical constant π, which is a constant. In Python, constants are usually represented by all-caps variable names.

BI = 3.14

But the fact is that BI is still a variable, and Python can’t guarantee that BI won’t be changed at all, so using all-caps variable names for constants is just a convention, and the syntax won’t report an error if you have to change it.

Data Type


There are six standard data types in Python3: Number, String, List, Tuple, Sets, and Dictionary.

Of Python3’s six standard data types:

  • Immutable data (3): Number (number), String (string), Tuple (tuple).
  • Variable data (3): List (list), Dictionary (dictionary), Set (collection).

We describe the use of each of these data types below.

Number

Python3 supports int, float, bool, and complex (plural).

The numeric type is, as the name implies, used to store numeric values, and it is important to remember that, somewhat similar to Java’s string flavor, if the value of a numeric data type is changed, memory space will be reallocated.

Python supports three different types of values.

  • Integer (int) - commonly referred to as an integer or integer, a positive or negative integer without a decimal point. python3 integers are not limited in size and can be used as Long types, so Python3 does not have the Python2 Long type.
  • Float (float) - a floating-point type consists of an integer part and a fractional part; floats can also be expressed in scientific notation (2.5e2 = 2.5 x 102 = 250)
  • Complex (complex) - complex numbers consist of a real part and an imaginary part, and can be represented as a + bj, or complex(a,b), where both the real part a and the imaginary part b of the complex number are floating point.

Example.

#! /usr/bin/python3

counter = 100 # Integer variable
miles = 1000.0 # Floating-point variable
name = "test" # String

print (counter)
print (miles)
print (name)

Numeric Type Conversion

  • int(x) Converts x to an integer.
  • float(x) converts x to a floating point number.
  • complex(x) converts x to a complex number, with the real part being x and the imaginary part being 0.
  • complex(x, y) converts x and y to a complex number, with the real part being x and the imaginary part being y. x and y are numeric expressions. Additional notes

Like other languages, numeric types support a variety of common operations, but Python’s operations are richer than those of most other common languages, and there are a large number of rich methods that provide more efficient development.

Examples of numerical operations.

print(5 + 4) # add Output 9
print(4.3 - 2) # Subtract Output 2.3
print(3 * 7) # Multiply Output 21
print(2 / 4) # Divide to get a floating point number Output 0.5
print(2 // 4) # Divide to get an integer Output 0
print(17 % 3) # Divide and output 2
print(2 ** 5) # Multiply by the square Output 32

String

Creating strings can use single quotes, double quotes, triple single quotes, and triple double quotes, where triple quotes can define strings on multiple lines. Python does not support single character types, and single characters are also used as a string in Python as well.

We define an s=‘python’ statement, which is executed in the computer by first creating a string Python in memory, creating a variable s in the program stack register, and finally assigning the address of Python to s.

To look at some more common operations on strings.

s = 'Learn Python'
# slice
s[0], s[-1], s[3:], s[::-1] # 'Yu', 'n', 'Python', 'nohtyP's YaYu'

# replace, you can also use regular expressions to replace
s.replace('Python', 'Java') # 'Learn Java'

# find, find(), index(), rfind(), rindex()
s.find('P') # 3, returns the subscript of the first occurrence of the substring
s.find('h', 2) # 6, set the subscript 2 to start the search
s.find('23333') # -1, return -1 if not found
s.index('y') # 4, return the subscript of the first occurrence of the substring
s.index('P') # different from find(), throws exception if not found

# case-sensitive, upper(), lower(), swapcase(), capitalize(), istitle(), isupper(), islower()
s.upper() # 'learn PYTHON'
s.swapcase() # 'learn pYTHON', case swapping
s.istitle() # True
s.islower() # False

# remove spaces, strip(), lstrip(), rstrip()
# Formatting
s1 = '%s %s' % ('Windrivder', 21) # 'Windrivder 21'
s2 = '{}, {}'.format(21, 'Windridver') # recommended formatting string
s3 = '{0}, {1}, {0}'.format('Windrivder', 21)
s4 = '{name}: {age}'.format(age=21, name='Windrivder')

# joins and splits, using + to join strings, each operation will recalculate, open and free memory, which is inefficient, so it is recommended to use joins
l = ['2017', '03', '29', '22:00']
s5 = '-'.join(l) # '2017-03-29-22:00'
s6 = s5.split('-') # ['2017', '03', '29', '22:00']

These are some common operations.

Another thing to keep in mind is string encoding. All Python strings are Unicode strings, so when you need to save a file to a peripheral or transfer it over the network, you need to perform an encoding conversion, converting characters to bytes for efficiency.

# encode Converts characters to bytes
str = 'Learn Python'
print (str.encode()) # The default encoding is UTF-8 Output: b'\xe5\xad\xa6\xe4\xb9\xa0Python'
print (str.encode('gbk')) # output b'\xd1\xa7\xcf\xb0Python'

# decode converts bytes to characters
print (str.encode().decode('utf8')) # output 'Learn Python'
print (str.encode('gbk').decode('gbk')) # output 'Learn Python'

List

Java List-like collection interface

Lists are lists of elements written between square brackets [], separated by commas, and can be implemented as data structures for most collection classes. The elements of a list can be of different types, it supports numbers, strings and even contains lists (so-called nesting), and the elements of a list are changeable.

Example.

Weekday = ['Monday','Tuesday','Wednesday','Thursday','Friday']
print(Weekday[0]) # Output Monday

#list Search
print(Weekday.index("Wednesday"))

#list add elements
Weekday.append("new")
print(Weekday)

# list Delete
Weekday.remove("Thursday")
print(Weekday)

Tuple (tuple)

A tuple is similar to a list, except that the elements of a tuple cannot be modified. The tuple is written in parentheses (), the elements are separated by commas, and the elements in the group can be of different types.

Example.

letters = ('a','b','c','d','e','f','g')
print(letters[0]) # Output 'a'
print(letters[0:3]) # Output a set ('a', 'b', 'c')

Sets (collections)

Java Set-like collection interface

A set is an unordered sequence of unduplicated elements, created using curly braces {} or the set() function.

Sets cannot be sliced or indexed, except for set operations, and set elements can be added and deleted.

Example.

a_set = {1,2,3,4}

# Add
a_set.add(5)
print(a_set) # output {1, 2, 3, 4, 5}

# Delete
a_set.discard(5)
print(a_set) # output {1, 2, 3, 4}

Dictionary

Java Map-like collection interface

A dictionary is a mapping type whose elements are key-value pairs, and the keywords of a dictionary must be immutable types and cannot be duplicated. To create an empty dictionary use {} .

Example.

Logo_code = {
 'BIDU':'Baidu',
 'SINA':'Sina',
 'YOKU':'Youku'
 }
print(Logo_code)
# Output {'BIDU': 'Baidu', 'YOKU': 'Youku', 'SINA': 'Sina' }
print (Logo_code['SINA']) # Output the value of the key 'one'
print (Logo_code.keys()) # Output all keys
print (Logo_code.values()) # Output all values
print (len(Logo_code)) # Output the length of the field

Summary


This section introduces you to Python variables and the six standard data types, showing you the use of variables and the common operations of the six standard data types.


Reference:

https://www.cnblogs.com/wang-yc/articles/6423951.html https://segmentfault.com/a/1190000014511963 https://www.runoob.com/python3/python3-data-type.html https://zhuanlan.zhihu.com/p/26079855 https://github.com/JustDoPython/python-100-day/tree/master/day-003

comments powered by Disqus