search
HomeBackend DevelopmentPython TutorialIntroduction to variables and data types in Python
Introduction to variables and data types in PythonJun 30, 2017 pm 01:39 PM
pythonBaseSummarize

1. Variables and data types

1.1 Variables

1. Each variable stores a value—the information associated with the variable.

2. Variables can be not only integers or floating point numbers, but also strings, and can be of any data type.

1.1.1 Naming and using variables

Variable names can only contain letters, numbers and underscores, and cannot begin with numbers. Variable names cannot contain spaces, but can be separated by underscores. Python keywords and function names cannot be used as variable names. Variable names should be short and descriptive. Be careful with the lowercase l and uppercase O, as they can be mistaken for the numbers 1 and 0.

1.1.2 Avoid naming errors when using variables

The interpreter will provide a traceback when an error occurs. A traceback is a record that points out where trouble occurred.

1.2 String str

1.String is a series of characters. It is a data type. In Python, all strings enclosed by quotes can be single quotes or double quotes.

2. The Unicode standard is also constantly evolving, but the most commonly used one is to use two bytes to represent a character (if you want to use very remote characters, you need 4 bytes). Modern operating systems and most programming languages ​​support Unicode directly. Convert Unicode encoding into "variable length encoding" UTF-8 encoding.

3.Python uses single quotes or double quotes with b prefix to represent bytes type data: x = b'ABC'. Str expressed in Unicode can be encoded into specified bytes through the encode() method.

'ABC'.encode('ascii')

b'ABC

Conversely, if we read a byte stream from the network or disk, the data read is bytes. To change bytes into str, you need to use the decode() method:

b'ABC'.decode('ascii')

'ABC

4. For the encoding of a single character, Python provides the ord() function to obtain the integer representation of the character, and the chr() function converts the encoding to the corresponding Characters:

##>>> ord('A')

65

>> > ord('中')

20013

>>> chr(66)

'B'

>> > chr(25991)

'文'

5. To calculate how many characters str contains, you can use the len() function, The len() function calculates the number of characters in str. If it is changed to bytes, the len() function calculates the number of bytes. It can be seen that a Chinese character usually occupies 3 bytes after UTF-8 encoding, while an English character only occupies 1 byte.

1.2.1 Operations on strings

1. Methods are operations that Python can perform on data.

2.title() displays each word with the first letter capitalized, that is, changes the first letter of each word to capitalized.

3.upper() changes the string to all uppercase. lower() changes the string to all lowercase.

4. If the string has at least one letter, and all letters are uppercase or lowercase, the isupper() and islower() methods will return the Boolean value True accordingly. Otherwise, the method returns False.

5.salpha() returns True if the string only contains letters and is not empty;

6.isalnum() returns True if the string only contains letters and numbers and is not Empty;

7.sdecimal() returns True if the string only contains numeric characters and is not empty;

8.sspace() returns True if the string only contains spaces, spaces table character and line break, and is not empty;

9.istitle() returns True if the string only contains words starting with an uppercase letter and followed by lowercase letters.

10. The startswith() and endswith() methods return True if the string they are called starts or ends with the string passed in by this method. Otherwise, the method returns False.

11. The join() method is called on a string, the parameter is a list of strings, and a string is returned.

##>>> ', '.join(['cats', 'rats', 'bats'])12. The split() method does exactly the opposite: it is called on a string and returns a list of strings. You can also pass a split string to the split() method and specify it to split according to different strings.

'cats, rats, bats'

>>> ' '.join(['My', 'name', 'is', 'Simon'])

'My name is Simon'

>>> 'ABC'.join(['My', 'name', 'is', 'Simon'])

'MyABCnameABCisABCSimon'

##>>> 'My name is Simon'.split()

13. The rjust() and ljust() string methods return padded versions of the strings on which they are called, with spaces inserted to align the text. The first argument to both methods is an integer length used to align the strings. The second optional argument to the rjust() and ljust() methods specifies a fill character to replace the space character.

['My', 'name', ' is', 'Simon']

##>>> 'Hello'.rjust(20, '*')

'******* ********Hello'

>>> 'Hello'.ljust(20, '-')

'Hello-------- -------'

14.center() string method is similar to ljust() and rjust(), but it centers the text, Instead of left or right alignment.

15.sort() sorts strings.

16. Please be sure to note that Python programs are

case sensitive. If the wrong case is entered, the program will report an error.

17. Merge - Python uses the plus sign + to merge strings

18. Can be before the quotation mark at the beginning of the string Add r to make it a raw string. "Raw string" completely ignores all escape characters and prints all backslashes in the string.
    ##first_name = "ada"
  1. last_name = "lovelace"
  2. full_name = first_name + " " + last_name
  3. print( full_name)
  4. ada Lovelace

##>>> print(r'That is Carol\'s cat.')19. Delete blanks: method rstrip() right lstrip() left strip() both sides
That is Carol\'s cat.

20.

Syntax Error:

is an error that is encountered from time to time. In a string enclosed in single quotes, if an apostrophe is included, it will cause an error. Double quotes won't.

21.Print() prints, the comma will be one space empty.

22. The pyperclip module has copy() and paste() functions that can send text to or receive text from the computer's clipboard.

23. String has a replace() method

##>>> a = 'abc'>>> a.replace('a', 'A')The null value is a special value in Python, represented by None. None cannot be understood as 0, because 0 is meaningful, and None is a special null value.

'Abc'

##1.2.2 empty Value
1.2.3 Constants

Constants are variables that cannot be changed. For example, the commonly used mathematical constant π is a constant. In Python, variable names in all uppercase letters are usually used to represent constants: PI = 3.14159265359

##1.2.4 Assignment

In Python, the equal sign = is an assignment statement, and any data type can be assigned a value To a variable, the same variable can be assigned repeatedly, and it can be a variable of different types:

a = 123 # a is an integer

print (a)a = 'ABC' # a becomes a string

print(a)

Assignment statement : a, b = b, a + b

##t = (b, a + b) # t is a tuple

a = t [0]b = t[1]

1.2.5 Formatting

There are two types of formatting in Python The first one is implemented with %, and the second one is { } format.

'Hello, %s' % 'world'

%?, the brackets can be omitted.
% operator is Used to format strings. Within the string, %s means replacing with a string, %d means replacing with an integer, there are several %? placeholders, followed by several variables or values, and the order must be corresponding.

If there is only one

Commonly used placeholders:

##%d Integer%f Floating point number

%s String%x Hexadecimal integer

Among them, formatted integers and floating point numbers can also specify whether to add 0 And the number of digits in integers and decimals:

#>>> '%2d-%02d' % (3, 1)

' 3-01'

>>> '%.2f' % 3.1415926'3.14'1. Normal use

If you are not sure what to use, %s will always work, it will convert any data type to a string.

Sometimes, the % in the string is an ordinary character and needs to be escaped. Use %% to represent a %.

The second formatting method, format, replaces % with {}.

##>>> print("My name is {} and I am {} years old this year".format ("Xiao Li", 20))

My name is Xiao Li, I am 20 years old this year

2. You can also modify the formatting order by filling in numbers in brackets

##>>> print("My name is {1 }, this year is {0} years old".format("Xiao Li", 20))

My name is 20, this year Xiao Li is years old

3. Get variables through key

##>>> print("My name is {name} and I am {age} years old this year". format(name="Xiao Li", age=20))1.2.6 Escape Characters

My name is Xiao Li, I am 20 years old this year

Whitespace - refers to any non-printing characters such as spaces, tabs, and newlines.

Escape character\ can escape many characters\t tab character \n newline

character\ itself also needs to be escaped, so the character represented by \\ is \

If there are many characters in the string that need to be escaped, you can use r'' in Python to represent ''. The internal string is not escaped by default:

>>> print('\\\t\\')1.3 Number

\ \

>>> print(r'\\\t\\')

\\\t\\

1.3.1 Integer int

can be performed Arithmetic.

Since computers use binary, it is sometimes more convenient to use hexadecimal to represent integers. Hexadecimal is represented by the 0x prefix and 0-9, a-f, for example: 0xff00, 0xa5b4c3d2, etc.

Division of integers

is exact. In Python, there are two kinds of division. One division is /, /The result of division is a floating point number. Even if two integers are exactly divisible, the result is a floating point number. Another kind of division is //, called floor division. The division of two integers is still an integer. % Take the remainder.

1.3.2 Floating point number float

Python calls numbers with decimals floating point numbers. The reason why they are called floating point numbers is because when expressed in scientific notation, a floating point number The decimal point position is variable. For example, 1.23x10

9

and 12.3x108 are completely equal. For very large or small floating point numbers, they must be expressed in scientific notation. Replace 10 with e. 1.23x109 is 1.23e9, or 12.3e8, 0.000012 can be written as 1.2e-5, etc.

1.3.3 Use the function str() to avoid errors

Data type checking can be implemented using the built-in function isinstance():

def my_abs(x):

if not isinstance(x, (int, float)):

raise TypeError('bad operand type')

if x >= 0:

                                                                        ’ s ’ ’ through through through through through through through through out out off off out off out through out through out out through out right Through out through over over over ‐ After ‐ ‐ n w w w w‐ ‐ to to to to to to to to to come a 1.4 Notes

#1. Statements starting with # are comments. Comments are for human viewing and can be any content. The interpreter will ignore the comments. Each other line is a statement, and when the statement ends with a colon:, the indented statement is considered a code block.

#. . . . . .

2. Since the Python source code is also a text file, when your source code contains Chinese, you need to Be sure to specify saving as UTF-8 encoding. When the Python interpreter reads the source code, in order for it to be read in UTF-8 encoding, we usually write these two lines at the beginning of the file:

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

3.Document string Comments ””” ”””1.5Zen of Python
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.

Simple is better than complex.

  1. Complex is better than complicated.

  2. Flat is better than nested.

  3. Sparse is better than dense.

  4. Readability counts.

  5. Special cases aren't special enough to break the rules.

  6. Although practicality beats purity.

  7. Errors should never pass silently.

  8. Unless explicitly silenced.

  9. In the face of ambiguity, refuse the temptation to guess.

  10. There should be one-- and preferably only one --obvious way to do it.

  11. ##Although that way may not be obvious at first unless you're Dutch.
  12. Now is better than never.
  13. Although never is often better than *right* now.
  14. If the implementation is hard to explain, it's a bad idea.
  15. If the implementation is easy to explain, it may be a good idea.
  16. Namespaces are one honking great idea -- let's do more of those!

The above is the detailed content of Introduction to variables and data types in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.