Python-1 python basics, python-1python

Source: Internet
Author: User

Python-1 python basics, python-1python

 

Python Lesson 1 code note hello world
[Root @ heartbeat-data-1 python] # vim hello1.py #! /Usr/bin/env pythonprint ('Hello world! ') [Root @ heartbeat-data-1 python] # python hello1.pyhello world!

Note:

#! /Usr/bin/python indicates that the python interpreter under/usr/bin is called when the operating system executes the script;
#! /Usr/bin/env python is used to prevent operating system users from installing python in the default/usr/bin path. When the system sees this line, it first searches for the python installation path in the env settings, and then calls the interpreter program in the corresponding path to complete the operation.
#! /Usr/bin/python is equivalent to writing the python path;
#! /Usr/bin/env python will go to the environment settings to find the python directory,This writing method is recommended.

 

[Root @ heartbeat-data-1 python] # vim hello2.py def main (): print ("hello") main () IndentationError: expected an indented block indent error [root @ heartbeat-data-1 python] # vim hello2.py def main (): print ("hello") main ()

 

 

Variable
[Root @ heartbeat-data-1 python] # vim plus. py x = 2y = 3 print (x + y) [root @ heartbeat-data-1 python] # python plus. py5 [root @ localhost python] # vim plus. py def main (): x = 2 y = 4
Print (x + y) main () # python plus. py
6. The upper case is usually a constant, and the lower case is the variable [root @ heartbeat-data-1 python] # vim test. py x = 2y = 3z = xx = 5 print ('z: ', Z) print ('x:', X) [root @ heartbeat-data-1 python] # python test. pyZ: 2X: 5 [root @ heartbeat-data-1 python] # vim test1.py a = 'abc' B = aa = 'xyz' print (B) print () [root @ heartbeat-data-1 python] # python test1.pyABCXYZ single-line comment: #, multi-line comment: '''three quotation marks # print 'ddd '[root @ localhost python] # vim zhushi. py print
'''Print 'ddd 'print 'ddd '------------------
'''

[Root @ localhost python] # python zhushi. py

Print 'ddd'

Print 'ddd'

Print 'ddd'

------------------

 

Understand the character delimiter:
 
# _ * _ Coding: utf8 _ * _ add the above sentence to the script to solve the Chinese problem

ASSIC (octal) UNICODE (hexadecimal) UTF8 (variable length) ASSIC: 1 byte, 8 bits, 2 to the power of 8, a maximum of 256 UNICODE: up to 65536UTF8 can be saved to the power of 2: [root @ heartbeat-data-1 Python-3.4.4] # python >>> ord ('A ') 97 >>> ord ('A') 65 >>> A = 'wwp' >>> type (a) <class 'str' >>>> len (a) 3

In [1]: name = 'coffee coa'

In [2]: name
Out [2]: '\ xe5 \ x92 \ x96 \ xe5 \ x95 \ xa1 \ xe5 \ x8f \ xaf \ xe4 \ xb9 \ x90'

In [3]: name. encode ('utf-8 ')
---------------------------------------------------------------------------
UnicodeDecodeError Traceback (most recent call last)
<Ipython-input-3-977844d87663> in <module> ()
----> 1 name. encode ('utf-8 ')

UnicodeDecodeError: 'ascii 'codec can't decode byte 0xe5 in position 0: ordinal not in range (128)

The default encoding used to read files is ascii instead of utf8, resulting in errors.

Solution

In [6]: import sys

In [7]: reload (sys)
<Module 'sys '(built-in)>

In [9]: sys. setdefaultencoding ('utf8 ')

In [10]: name. encode ('utf-8 ')
Out [10]: '\ xe5 \ x92 \ x96 \ xe5 \ x95 \ xa1 \ xe5 \ x8f \ xaf \ xe4 \ xb9 \ x90'

 

In [12]: name_utf8 = name. encode ('utf-8 ')

In [13]: len (name_utf8)
Out [13]: 12

 

 

Module
>>> import os>>> os.system('df -h')Filesystem            Size  Used Avail Use% Mounted on/dev/sda5              44G  2.2G   39G   6% /tmpfs                 491M     0  491M   0% /dev/shm0>>> os.system('free -m')             total       used       free     shared    buffers     cachedMem:           981        741        239          0         29        587-/+ buffers/cache:        125        855Swap:         2047          0       20470

 

Built-in modules

 
OS built-in modules

Used to provide system-level operations

OS. getcwd () obtains the current working directory, that is, OS. chdir ("dirname"), which is used by the current python script to change the working directory of the current script. It is equivalent to cd in shell.

OS. curdir :('.')

OS. pardir :('..')

OS. makedirs ('dirname1/dirname2 ') can generate multi-layer recursive directories.

OS. removedirs ('dirname1') if the directory is empty, delete it and recursively go to the upper-level directory. If the directory is empty, delete it.

OS. mkdir ('dirname') to generate a single-level Directory, which is equivalent to mkdir dirname in shell.

OS. rmdir ('dirname') deletes a single-stage empty directory. If the directory is not empty, it cannot be deleted and an error is returned. This is equivalent to rmdir dirname in shell.

OS. listdir ('dirname') lists all files and subdirectories in a specified directory, including hidden files, and prints them in list mode.

OS. remove () delete an object

OS. rename ("oldname", "newname") rename a file/directory

OS. stat ('path/filename ') to get the file/directory information

OS. sep: Specifies the path delimiter of the output operating system. The path in win is \, and the path in Linux is "/"

OS. linesep: output the line terminator used by the current platform. The line terminator is \ t \ n in win, and the line terminator is \ n in Linux"

OS. pathsep output the string used to split the file path

OS. name output string indicates the current platform. Win-> 'nt '; Linux-> 'posix'

OS. system ("bash command") run the shell command to directly display

OS. environ: Get system environment variables

OS. path. abspath (path) returns the absolute path of path normalization.

OS. path. split (path) splits the path into two groups: Directory and file name.

OS. path. dirname (path) returns the path directory. It is actually the first element of OS. path. split (path ).

OS. path. basename (path) returns the final file name of the path. If the path ends with a slash (/) or slash (\), a null value is returned. That is, the second element of OS. path. split (path ).

OS. path. exists (path) If path exists, True is returned. If path does not exist, False is returned.

OS. path. isabs (path) returns True if path is an absolute path.

OS. path. isfile (path) If path is an existing file, True is returned. Otherwise, False is returned.

OS. path. isdir (path) If path is an existing Directory, True is returned. Otherwise, False is returned.

OS. path. join (path1 [, path2 [,...]) returns the results after combining multiple paths. The parameters before the first absolute path are ignored.

OS. path. getatime (path) returns the last access time of the file or directory pointed to by path.

OS. path. getmtime (path) returns the last modification time of the file or directory pointed to by path.

 
 

Sys built-in Module

 

 

 

Sys. argv command line parameter List. The first element is the program path.

Sys. exit (n) exit the program. exit (0) when the program Exits normally)

Sys. version: get the version information of the Python interpreter.

Maximum Int value of sys. maxint

Sys. path: return the search path of the module. The value of the PYTHONPATH environment variable is used during initialization.

Sys. platform: returns the name of the operating system platform.

Sys. stdout. write ('Please :')

Val = sys. stdin. readline () [:-1]

 

 

Interactive
Interactive: raw_input outputs strings by default. The difference between numbers raw_input and input is: when the input format is anything, it is called. raw_input outputs strings by default.
Normal version
[Root @ python scripts] # vim test0.py #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ name = raw_input ('Please input your name: ') age = raw_input ("age :") print name, age

Upgrade [root @ python scripts] # vim test1.py #! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ name = raw_input ('Please input your name: ') age = raw_input ("age :") job = raw_input ("job:") salary = raw_input ("salary:") print '''personal information of % s: Name: % s Age: % s Job: % s Salary: % s ------------------- ''' % (name, name, age, job, salary) % s represents the string % d Represents the Number % f Represents the floating point number

 

 

Process Control
Process control statement: if statement if else
#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ name = raw_input ('Please input your name: ') age = input ("age :") job = raw_input ("job:") salary = raw_input ("salary:") if age> 30: msg = 'you are too fucking old! 'Else: msg = 'You are still young 'print ''' Personal information of % s: Name: % s Age: % d Job: % s Salary: % s --------------------- % s '''
% (Name, name, age, job, salary, msg)

If elif else
#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ name = raw_input ('Please input your name: ') age = input ("age :") job = raw_input ("job:") salary = raw_input ("salary:") if age> 40: msg = 'you are too fucking old! 'Elif age> 30: msg = 'You are still have a few years to hook up 'else: msg =' You are still young 'print ''' 'Personal information of % s: name: % s Age: % d Job: % s Salary: % s ------------------- % s '''
% (Name, name, age, job, salary, msg)

For statement:
#! /Usr/bin/env python # _ * _ coding: UTF-8 _ * _ name = raw_input ('Please input your name: ') job = raw_input ("job :") salary = raw_input ("salary:") real_age = 29for I in range (10): age = input ('Age: ') if age> 29: print 'Big! 'Elif age = 29: print' \ 033 [32; 1 mright! \ 033 [0m' color break else: print 'small' print 'You still got % s shots! '% (9-I) print ''' Personal information of % s: Name: % s Age: % d Job: % s Salary: % s ---------------------'''
% (Name, name, age, job, salary) while loop [root @ python scripts] # vim test4.py count = 0 while True: print 'loop ;', count + = 1 version 1print_num = input ('which loop do you want it to be printed out? ') Count = 0 while count <100000000: if count = print_num: print 'There you got the num:', count choice = raw_input ('Do U want to continue the loop? Y/N') if choice = 'N': break else: print 'loop: ', count + = 1 else: print 'loop: count ', count version 2print_num = input ('which loop do you want it to be printed out? ') Count = 0 while count <100000000: if count = print_num: print 'There you got the num:', count choice = raw_input ('Do U want to continue the loop? Y/N') if choice = 'N': break else: print_num = input ('which loop do you want it to be printed out? ') Else: print 'loop:', count + = 1 else: print 'loop: count', count version 3 [root @ python software] # vim test. py # _ * _ coding: UTF-8 _ * _ print_num = input ('which loop do you want it to be printed out? ') Count = 0 while count <100000000: if count = print_num: print 'There you got the num:', count choice = raw_input ('Do U want to continue the loop? Y/N') if choice = 'N': break else: while print_num <= count: print_num = input ('which loop do you want it to be printed out? ') Print "the num have passed" else: print 'loop:', count + = 1 else: print 'loop: count', count

 

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.