Python Programming basics

Source: Internet
Author: User
This article mainly introduces some basic knowledge of getting started with Python programming, including the basic content such as annotation requirements and Shell command usage. For more information, see Python and Perl, C and Java have many similarities. However, there are also some clear differences between languages. This chapter aims to help you quickly learn the Python syntax.
The first Python program:
Interactive mode programming:

The following prompt is displayed when the interpreter is called without passing through the script file as a parameter:

$ pythonPython 2.6.4 (#1, Nov 11 2014, 13:34:43)[GCC 4.1.2 20120704 (Red Hat 5.6.2-48)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>>

Enter the following text at the Python prompt and press Enter:

>>> print "Hello, Python!";

If you are running a new Python version, you need to use print statement parentheses like print ("Hello, Python! ");. But in Python version 2.6.4, this will produce the following results:

Hello, Python!

Script mode programming:

Call the interpreter and script as parameters and start the script to be executed until the script is complete. When the script is complete, the interpreter is no longer active.

Let's write a simple Python program in the script. All Python files will have. py extensions. Therefore, write the following code in a test. py file.

print "Hello, Python!";

Here, I assume that you have set the Python interpreter in the PATH variable. Now, try to run this program as follows:

$ python test.py

This produces the following results:

Hello, Python!

Let's try another way to execute the Python script. The modified test. py file is as follows:

#!/usr/bin/pythonprint "Hello, Python!";

Here, we assume that the Python interpreter is available in the/usr/bin directory. Now, try to run this program as follows:

$ chmod +x test.py   # This is to make file executable$./test.py

This produces the following results:

Hello, Python!

Python identifier:

The Python identifier is used to identify the name of a variable, function, class, module, or other object. An identifier starts with the letter A to Z or? Z or followed by zero or multiple letters, underscores (_), and numbers (0? 9 ).

Punctuation marks, such as @, $, and %, are not allowed in the identifiers of Python. Python is a case-sensitive programming language. Therefore, Manpower and manpower are two different identifiers in Python.

The Python identifier naming conventions are as follows:

  • The class name must contain uppercase letters and all other identifiers in lower case.
  • The identifier starting with a single leading underline indicates that the identifier convention means private.
  • The identifier that starts with two leading underlines indicates a strong private identifier.
  • If an identifier ends with two underscores, the identifier is a special name defined by a language.

Reserved words:

The reserved words in Python are listed below. These reserved words cannot be used as constants, variables, or any other identifier. All Python keywords only contain lowercase letters.

Line and indent:

When a programmer learns Python, the first thing to note is that no parentheses are used to indicate the class and function definition block or process control of the code. The code block is indented by rows, which is strictly represented.

The number of indentations is variable, but all statements in the block must be indented to the same amount. In this example, both feature blocks are well-used:

if True:  print "True"else: print "False"

However, the second part in this implementation example will produce an error:

if True:  print "Answer"  print "True"else:  print "Answer" print "False"

Therefore, all spaces with continuous line indentation in Python will form blocks. The following are examples of various statement blocks:

Note: Do not try to understand the logic or different functions used. Just make sure you understand that even if their various modules do not require parentheses.

#!/usr/bin/pythonimport systry: # open file stream file = open(file_name, "w")except IOError: print "There was an error writing to", file_name sys.exit()print "Enter '", file_finish,print "' When finished"while file_text != file_finish: file_text = raw_input("Enter text: ") if file_text == file_finish:  # close the file  file.close  break file.write(file_text) file.write("\n")file.close()file_name = raw_input("Enter filename: ")if len(file_name) == 0: print "Next time please enter something" sys.exit()try: file = open(file_name, "r")except IOError: print "There was an error reading file" sys.exit()file_text = file.read()file.close()print file_text

Multi-line statement:

A Python statement usually ends with a new line. However, Python allows the continuation of the line character (\), and the row should continue (cross-row ). For example:

total = item_one + \    item_two + \    item_three

The statement contained in [], {}, or () brackets does not need to use a line break. For example:

days = ['Monday', 'Tuesday', 'Wednesday',    'Thursday', 'Friday']

Python quotation marks:

Python accepts single quotation marks ('), double quotation marks ("), and three (' or") references to indicate string constants, as long as they are strings of the same type of quotation marks starting and ending.

A string that spans multiple rows. For example, all of the following are valid:

word = 'word'sentence = "This is a sentence."paragraph = """This is a paragraph. It ismade up of multiple lines and sentences."""

Python notes:

A pound sign (#), which is not a comment at the beginning of a string. The characters after "#" and to the physical line are part of the annotation. The Python interpreter ignores them.

#!/usr/bin/python# First commentprint "Hello, Python!"; # second comment

This produces the following results:

Hello, Python!

Annotations may be expressed in the declaration or after the same row:

name = "Madisetti" # This is again comment

You can use multiline annotations as follows:

# This is a comment.# This is a comment, too.# This is a comment, too.# I said that already.

Use blank lines:

A row contains only spaces and may contain comments. if it is a blank line, Python ignores it completely.

In an interactive interpreter session, you must enter an empty physical row to terminate the multi-row statement.
Waiting for users:

The following line of the program displays a prompt, press the Enter key to exit, and wait for the user to press the Enter key:

#!/usr/bin/pythonraw_input("\n\nPress the enter key to exit.")

Here, "\ n" is used to create two line breaks before the actual line is displayed. Once you press the key, the program ends. This is a good technique. keep a console window open until the user finishes running the application.
Multiple statements in one row:

Semicolon (;) allows you to write multiple statements in a single row, regardless of whether the statement starts a new code block. The following example uses a semicolon:

import sys; x = 'foo'; sys.stdout.write(x + '\n')

Multiple statement groups are used as suites:

A group of separate statements are called sequences in a single Python code block. Complex statements, such as if, while, def, and class, require a header line and a suite.

The declaration (with the keyword) at the beginning of the header line, and termination with the colon (:), followed by one or more lines to form the suite. For example:

if expression :   suiteelif expression :   suite else :   suite

Command line parameters:

We may already see that, for example, many programs can run and they provide some basic information about how to run them. In Python, you can use-h to do this:

$ python -husage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...Options and arguments (and corresponding environment variables):-c cmd : program passed in as string (terminates option list)-d   : debug output from parser (also PYTHONDEBUG=x)-E   : ignore environment variables (such as PYTHONPATH)-h   : print this help message and exit[ etc. ]

You can also set your script to accept various options in this way. The command line parameter is an advanced topic and will be learned later when you use other Python concepts.

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.