Python Quick Start (1) and python Quick Start

Source: Internet
Author: User
Tags element groups floor division

Python Quick Start (1) and python Quick Start

I learned python more than a month later. While recording these essays, if you can see it, I hope it will help you. If there are any errors, please advise me!

The main record is an overall understanding of python.

1. print statement and "Hello World !"

  In the python interpreter, you can use the string of the print output variable or the variable name to display the value of the variable.

>>> str = 'Hello World!'>>> print strHello World!>>> str'Hello World!'>>> 

 

Note: When only the variable name is used, the output string is enclosed in single quotes. This is to enable non-string objects to be displayed on the screen as strings.

The underscore (_) indicates the value of the last expression in the interpreter. Therefore, after executing the code above, the underline variable contains a string.

>>> _'Hello World!'>>> 

 

The print Output Statement of python can be used in combination with various operators (%) of strings to replace strings. % S represents a string to replace, while % d represents an integer to replace. Another common one is % f, which represents replacement by a floating point number.

>>> print '%s is number %d' %('python',1)python is number 1>>> 

2. raw_input () built-in functions

  The easiest way to get data input from a user is to use the raw_input () built-in function. It reads the standard input and assigns the read data to the specified variable.

>>> user = raw_input("enter login name:")enter login name:xiaojian>>> print  "your login is :",useryour login is : xiaojian>>> 

 

3. Notes

>>> # this is acomment

 

4. Operators

  In Python, arithmetic operators include +-* // % ** plus, subtraction, multiplication, division, and remainder. Python has two division operators. A single slash is used as a traditional division, and a double slash is used as a floating point Division (rounding the result ). Traditional Division means that if both operands are integers, it will execute the floor Division (take the largest integer smaller than the quotient), while the floating point Division is the real division, no matter what type of operand, the floating-point Division always executes the real division. There is also a multiplication operator, double star number (**).

>>> print -2*4 +  3**21

 

Python also has standard comparison operators. A comparison operation returns a Boolean value based on the true or false values of the expression: <<=>>==! = <>! Both = and <> indicate "not equal", but the latter has been gradually eliminated.

>>> 2 < 4True>>> 2 == 4False>>> 2 > 4False>>> 

Python also provides the logical operators: and or not

>>> 2 < 4 and 2 == 4False>>> 2 > 4 or 2 < 4True>>> not 6.2 <= 6True>>> 3 < 4 < 5True

 

5. Variables and assignments

 The variable name rules in Python are the same as those in most other advanced languages. Python variable names are case sensitive.

Python is a dynamic type language, that is, the type of the variable does not need to be declared in advance. The type and value of the variable are initialized at the moment of value assignment. Variable value assignment is executed by equal signs.

>>> count = 2>>> price = 6488.0>>> name = 'apple'>>> prices = count * price>>> print 'the price of %d %s is %f' %(count,name,prices)the price of 2 apple is 12976.000000>>> 

Python also supports Incremental assignment, that is, the operator and equal sign are combined. Let's look at the following example: n = n * 10. Change the above example to the Incremental assignment method: n * = 10.

Python does not support the auto increment 1 and auto increment 1 operators.

6. Number

Python supports five basic numeric types, three of which are integer types.
(1) int (signed integer)
(2) long (long integer)
(3) bool (Boolean value)
(4) float (floating point value)
(5) complex (plural)

7. String

In Python, strings are defined as character set combinations between quotes. Python supports pair single or double quotation marks. Three double quotation marks (three consecutive single or double quotation marks) can be used to contain special characters. You can use the index operator ([]) and slice operator ([:]) to obtain the sub-string. Character strings have their own unique index rules: the index of the first character is 0, and the index of the last character is-1 plus sign (+) for string join operations, asterisks (*) it is used to repeat strings. The following are examples:

>>> str = 'python'>>> iscool = 'is cool!'>>> str[0]'p'>>> str[2:5]'tho'>>> iscool[:2]'is'>>> iscool[3:]'cool!'>>> iscool[-1]'!'>>> str + iscool'pythonis cool!'>>> str + ' ' + iscool'python is cool!'>>> >>> str * 2'pythonpython'>>> str = '''python... is cool'''>>> str'python\n... is cool'>>> print strpython... is cool>>> 

8. List and metadata

The list and element groups can be treated as common "arrays", which can store any number of Python objects of any type. Like arrays, elements are accessed through a digital index starting from 0, but lists and metadata can store different types of objects. Lists and metadata have several important differences. List elements are enclosed in brackets ([]). The number of elements and the value of the elements can be changed. Elements of tuples are enclosed in parentheses () and cannot be changed (although their content is acceptable ). Tuples can be viewed as read-only lists. The subset can be obtained through the slice operation ([] and [:]), which is the same as the use of strings.

>>> list = [1,'2',2.5,3]>>> list[1, '2', 2.5, 3]>>> list[0]1>>> list[2:][2.5, 3]>>> list[:3][1, '2', 2.5]>>> list[2] = 5>>> list[1, '2', 5, 3]>>> 

Creation of yuanzu

>>> Tuple = ('python', 66,88, 'good') >>> tuple ('python', 66, 88, 'good') >>> tuple [1; 3] SyntaxError: invalid syntax >>> tuple [] (66, 88) >>> tuple [1] = 'python3' # Traceback (most recent call last) cannot be modified ): file "<pyshell #33>", line 1, in <module> tuple [1] = 'python3' TypeError: 'tuple' object does not support item assignment >>>

9. Dictionary

A dictionary is a ing data type in Python. It works similar to a hash table and consists of key-value pairs. Almost all types of Python objects can be used as keys, but it is generally most commonly used as numbers or strings. The value can be any type of Python object, and the dictionary elements are wrapped in braces.

>>> Dict = {'host': 'global'} # create a dictionary >>> dict. keys () ['host'] >>> dict ['post'] = 80 >>> dict. keys () ['host', 'post'] >>> dict ['host'] 'global'

 10. code block and indent alignment

Code blocks express code logic through indentation alignment rather than using braces, because the program is more readable without additional characters. The indentation clearly shows the code block of a statement. Of course, a code block can contain only one statement.

11. Errors and exceptions

Syntax errors are checked during compilation, but Python also allows errors to be detected when the program is running. When an error is detected, the Python interpreter raises an exception and displays detailed information about the exception. Programmers can quickly locate and debug the problem based on the information and find a way to handle the error. To add error detection and exception handling to your code, you only need to encapsulate them in the try-retry t statement. The code group after try is the code you plan to manage. The code group after T is the code you handle the error.

12. Functions

How to define functions

A function must be defined before it is called. If the function does not have a return statement, it will automatically return the None object.

The syntax for defining a function is composed of the def keyword and the function name followed by the required parameters of the function.

>>> def add2(x):return (x+x)

Call a function

>>> add2(5)10>>> 

A function parameter can have a default value. If a default value is provided, the parameter is provided in the form of a value assignment statement in function definition. In fact, this is only the syntax that provides the default parameter. It indicates that if this parameter is not provided during function calling, it takes this value as the default value.

13. Class

Use the class keyword to define the class. You can provide an optional parent class or base class. If there is no suitable base class, you can use object as the base class. The class line is followed by an optional document string, static member definition, and method definition.

14. Module

A module is an organizational form that organizes Python code related to each other into independent files. A module can contain executable code, functions, classes, and combinations of these things.

When you create a Python source file, the module name is the file name without the. py suffix. After a module is created, you can import it from another module using the import Statement.

   ImportModule_name

Once the import is complete, the attributes (functions and variables) of a module can be accessed through the familiar. period attribute identification method.
Module. function ()

 

The record here is only a preliminary understanding of python for beginners. Next we will learn the record carefully.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.