Python basic syntax and variables

Source: Internet
Author: User

Python basic syntax and variables
    • Basic syntax
    • Variable type
    • Percent% of formatted output
1. Basic syntax the first Python program

Interactive programming:

Interactive programming does not require the creation of a script file, it is written in the interactive mode of the Python interpreter.

On Linux you only need to enter the Python command at the command line to start interactive programming, prompting the following window:

After installing Python on window, you can run it in the CMD Command window with the following prompt:

C:\users\administrator>pythonpython 2.7.14 (v2.7.14:84471935ed, Sep, 20:19:30) [MSC v.1500 + bit (Intel)] on W In32type "Help", "copyright", "credits" or "license" for more information.>>>

Enter the following text information in the Python prompt, and then press ENTER to see the effect of the operation:

>>> print "Hello,python" Hello,python

Script-type programming:

Invoking the interpreter from the script parameter begins execution of the script until the script finishes executing. When the script finishes executing, the interpreter is no longer valid.

[email protected] tmp]# cat python.py#!/usr/bin/python#-*-coding:utf-8-*-print "hello,python!" [email protected] tmp]# python python.py hello,python! [Email protected] tmp]# chmod +x python.py [[email protected] tmp]#./python.py hello,python!
Python identifiers

In Python, identifiers are made up of letters, numbers, and underscores.

In Python, all identifiers can include English, numeric, and underscore (_), but cannot begin with a number.

Identifiers in Python are case-sensitive.

Identifiers that begin with an underscore are of special significance. A class attribute that begins with a single underscore, which is not directly accessible by the _foo, must be accessed through the interface provided by the class and cannot be imported with the FROM XXX import *;

A __foo that begins with a double underscore represents a private member of a class; A __foo__ that begins and ends with a double underscore represents a special method-specific identifier for Python, such as __init__ (), which represents the constructor of a class.

Python can display multiple statements on the same line, separated by semicolons , such as:

>>> print "123";p rint "456" 123456
Python reserved characters

The following list shows the reserved words in Python. These reserved words cannot be used as constants or variables, or as any other identifier name.

All Python keywords contain only lowercase letters.

and Exec Not
Assert Finally Or
Break For Pass
Class From Print
Continue Global Raise
Def If Return
Del Import Try
Elif Inch While
Else Is With
Except Lambda Yield

Line and indent

The biggest difference between Python and other languages is that Python's code block does not use curly braces {} to control classes, functions, and other logical judgments. Python's most distinctive feature is the use of indentation to write modules. The amount of whitespace indented is variable, but all code block statements must contain the same amount of indentation whitespace, which must be strictly enforced.

Multi-line statements

A new line is generally used as the Terminator for a statement in a Python statement. But we can use a slash (\) to divide a line of statements into multiple lines of display, as follows:

Print ("zjkzjk123123456456")--------output-----------zjkzjk123123456456

The statement contains [], {}, or () parentheses do not need to use a multiline connector. The following example:

Print ([1,2,3,4,5,6])---------output----------[1, 2, 3, 4, 5, 6]
Python Quotes

Python can use quotation marks ( ' ), double quotation marks ( " ), three quotation marks (" ' or "") to denote a string, and the beginning and end of the quotation mark must be of the same type. Where three quotation marks can be composed of more than one line, writing a shortcut syntax for multiple lines of text, often used in a document string, at a specific location of the file, as a comment.

Word = ' word ' sentence = ' This is a sentence. "paragraph =" "" This is a paragraph. Contains multiple statements "" "

Python comments

A single line comment in Python starts with #:

#这是一个python脚本print ("ZJK")
---------The result of the output-------------
Zjk

Annotations can be at the end of a statement or an expression line:

Print ("ZJK")   #这是一个注释---------output------------ZJK

A multiline comment in Python uses three single quotation marks ("') or three double quotation marks (" ""):

"" This is a multiline comment, using double quotation marks; This is a multi-line comment, using double quotation marks; This is a multiline comment, using double quotation marks; "" "This is a multiline comment, using single quotation marks; This is a multiline comment, using single quotation marks; This is a multiline comment, using single quotation marks;" "Print (" ZJK ")------------------output-----------ZJK
Python Empty Line

A blank line separates between functions or methods of a class, representing the beginning of a new piece of code. The class and function entries are also separated by a line of blank lines to highlight the beginning of the function entry.

Blank lines are different from code indentation, and empty lines are not part of the Python syntax. When you write without inserting a blank line, the Python interpreter runs without errors. However, the purpose of a blank line is to separate the code of two different functions or meanings, which facilitates the maintenance or refactoring of future code.

Remember: Blank lines are also part of your program code.

Show multiple statements on the same line

Python can use multiple statements in the same row, with semicolons (;) split between statements, and here's a simple example:

Print ("Hello");p rint ("World")-------------output--------------Hello World
2. Variable type variable definition

The value that the variable is stored in memory. This means that there is a space in memory when creating variables. Based on the data type of the variable, the interpreter allocates the specified memory and determines what data can be stored in memory. Therefore, variables can specify different data types, which can store integers, decimals, or characters.

Understood by literal meaning as the amount of change. The specific explanation is: Save the State (the operation of the program is the nature of a series of state changes, the purpose of the variable is to save the state, the variable is worth the change in the hook program to run different results)

Variable name naming rules
    1. Variable names consist of letters, numbers, and underscores;
    2. The variable name cannot be a pure number or a number;
    3. The variable name cannot be a python keyword;
    4. Variable names are case-sensitive;
    5. Variable names cannot be in Chinese;
    6. Variable names cannot be too long;
    7. The variable name should be meaningful;
    8. Variable names are best used in hump or underline format;
Assigning values to variables

Variable assignments in Python do not require a type declaration. Each variable is created in memory and includes information about the identity, name, and data of the variable. Each variable must be assigned before it is used, and the variable will not be created until the variable is assigned. The equals sign (=) is used to assign a value to a variable. The left side of the equals sign (=) operator is a variable name, and the right side of the equals sign (=) operator is the value stored in the variable.

Assigning values to multiple variables

Python can assign values to multiple variables at the same time, such as:

A = b =c = 1

The above example creates an integer object with a value of 1 and three variables allocated to the same memory space.

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

A, b, C = 1, 2, "ZJK"

For the above example, two integer objects 1 and 2 are assigned to variables A and B, and the string object "ZJK" is assigned to the variable C.

3. Formatted output

In many programming languages, there is the ability to format strings, such as formatted input and output in C and Fortran languages. Python has a built-in operation to format a string.

  Templates

When formatting a string, Python uses a string as a template. There are formatting characters in the template that reserve locations for real values and describe the format in which real values should be rendered. Python uses a tuple to pass multiple values to the template, each of which corresponds to a format character.

For example:

Print ("My name is%s,i ' m%d year old"% ("Zhang Yikang", 23))

-----------------The result of the output-----------------------------

My name is Zhang Yikang, I ' m

Description

"My name is%s,i ' m%d year old" as a template, and%s is the first format character, representing a string. %d is the second format character, which represents an integer. ("Zhang Yikang", 23) two elements "Zhang Yikang" and 23 are substituted for the true values of%s and%d.

Between the template and the tuple, there is a% number separated, which represents the format operation.

The entire "My name is%s,i ' m%d"% ("Zhang Yikang", 23) actually forms a string expression. We can assign a value to a variable as if it were a normal string. Like what:

A = "My name is%s,i ' m%d"% ("Zhang Yikang") print (a)----------------output---------------------------My name is Zhang Yikang, I ' m *

You can also use a dictionary to pass real values. As follows:

Print ("My name is%" (name) S,i ' m% (age) D-old "% ({" name ":" Zhang Yikang "," Age ": $})---------------Results The following-----------------------------My name is Zhang Yikang, I ' m

As you can see, we have named two of the format characters. The name is used () enclosed. A key for each named corresponding dictionary.

Format character

The format character reserves the location for the real value and controls the format of the display. A format character can contain a type code that controls the type of display, as follows:

%s string (shown with STR ())

%r string (shown with repr ())

%c single character

%b binary integers

%d decimal integers

%i Decimal Integer

%o Eight-binary integers

%x hexadecimal integer

%e index (base written as E)

%E index (base written as E)

%f floating Point

%F floating-point number, same as above

%g index (e) or floating point number (depending on display length)

%G Index (E) or floating point number (depending on display length)

Percent% character "%"

  

The format can be further controlled in the following ways:

  Format:%[(name)][flags][width]. [Precision]type

  Parameter description:

(name) is named

Flags optional value; + for right alignment;-for left alignment; "' is a space that fills a space on the left side of a positive number to align with negative numbers. 0 means using 0 padding. Add 0,16 to fill 0x, binary fill 0b in front of #表示八

Width indicates display widths

. Precision represents the number of digits of precision after the decimal point, such as accurate to 2 bits:%.2f

Type input format, see above

Example:

1. Print the string;

Print ("%s Welcome!" % "Beijing")------------------output Results-----------------------Welcome to Beijing!

2. Print integers;

Print ("Today's maximum temperature%d°"%)------------------------output----------------------today's highest temperature 40°

3. Print floating-point numbers

Print ("His height is%f m"% (1.83))-----------------------output----------------------His height is 1.830000 meters.

4. Print floating-point numbers, specify the number of decimal places reserved

Print ("His height is%.2f m"% (1.83))--------------------output------------------------His height is 1.83 meters.

5. Specify the placeholder width

Print ("name:%5s  age:%5d   height:%8.2f"% ("ZJK", 23,18.88))----------------------- Output---------------------------Name:  ZJK Age  :   Height:   18.88

6. Specify the placeholder width (left-justified)

Print ("name:%-5s  age:%-5d   height:%-8.2f"% ("ZJK", 23,18.88))---------------------- Output-------------------------name:zjk    age:23      height:18.88

7. Specify placeholders (with 0 padding)

Print ("name:%05s  age:%05d   height:%08.2f"% ("ZJK", 23,18.88))
--------------------------Output------------------------------Name: ZJK age:00023 height:00018.88

8. Print percent sign;

Print ("Download has been%s%%"%)------------------output----------------------downloaded 80%

Python basic syntax and variables

Related Article

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.