Python Road II

Source: Internet
Author: User
Tags python list

What the hell is a. pyc?

1. Is python an interpreted language?

The first thing I heard about Python when I was a beginner python was that Python was an explanatory language, and I kept believing until I found the *.pyc file. If it is an interpreted language, what is the generated *.pyc file? c should be the abbreviation of compiled!

In order to prevent other people who learn python from being misunderstood by this remark, we will clarify this issue in the text and make some basic concepts clear.

2. Explanatory and compiled languages

Computers are not able to recognize high-level languages, so when we run a high-level language program, we need a "translator" to engage in the process of translating high-level languages into machine languages that computers can read. This process is divided into two categories, the first of which is compilation, and the second is interpretation.

A compiled language before a program executes, the program executes a compilation process through the compiler, transforming the program into machine language. The runtime does not need to be translated and executes directly. The most typical example is the C language.

The explanatory language does not have this process of compiling, but rather, when the program is running, it interprets the program line by row, then runs directly, and the most typical example is Ruby.

Through the above example, we can summarize the advantages and disadvantages of the explanatory language and the compiled language, because the compiler language before the program has already made a "translation" of the program, so at run time there is less "translation" process, so the efficiency is higher. But we also can't generalize, some interpretive languages can also be optimized by the interpreter to optimize the whole program when translating the program, thus more efficiently than the compiled language.

In addition, with the rise of virtual machine-based languages such as Java, we cannot simply divide the language into two types-----explanatory and compiled.

In Java, for example, Java is first compiled into a bytecode file by a compiler and then interpreted as a machine file by the interpreter at run time. So we say that Java is a language that is compiled and interpreted first.

3. What exactly is Python?

In fact, Python, like java/c#, is also a virtual machine-based language, let's start with a simple look at the Python program's running process.

When we enter Python hello.py on the command line, we actually activate the Python interpreter and tell the interpreter: You're going to start working. But before the "explain", the first thing that actually executes is the same as Java, which is compiled.

Students familiar with Java can consider how we execute a Java program on the command line:

Javac Hello.java

Java Hello

Just when we were using an IDE like Eclipse, we fused these two parts into a piece. In fact, Python is also the same, when we execute Python hello.py, he also executes such a process, so we should describe the Python,python is a first compiled after the interpretation of the language.

4. Brief description of Python's running process

Before we say this question, let's start with two concepts, pycodeobject and PYC files.

The PYC we see on the hard drive naturally doesn't have to say much, and pycodeobject is actually the result of a Python compiler actually compiling it. Let's just get to the bottom of it and keep looking down.

When the Python program runs, the result of the compilation is saved in the Pycodeobject in memory, and when the Python program finishes running, the Python interpreter writes Pycodeobject back to the PYc file.

When the Python program runs for the second time, the program will first look for the PYc file on the hard disk, and if it is found, load it directly or repeat the process.

So we should be able to locate Pycodeobject and pyc files, we say that PYc file is actually a kind of persistent saving way of pycodeobject.

Data type First Knowledge 1, number

2 is an example of an integer.
Long integers are just larger integers.
3.23 and 52.3E-4 are examples of floating-point numbers. The e tag represents a power of 10. Here, 52.3E-4 means 52.3 * 10-4.
( -5+4j) and (2.3-4.6j) are examples of complex numbers, where -5,4 is a real number, j is an imaginary number, and what is the plural in mathematics?

int (integral type)

On a 32-bit machine, the number of integers is 32 bits and the value range is -2**31~2**31-1, which is -2147483648~2147483647
On a 64-bit system, the number of integers is 64 bits and the value range is -2**63~2**63-1, which is -9223372036854775808~9223372036854775807long (Long integer)
Unlike the C language, Python's long integers do not refer to the positioning width, that is, Python does not limit the size of long integer values, but in fact, because of limited machine memory, we use a long integer value can not be infinite.
Note that, since Python2.2, Python automatically converts integer data to long integers if an integer overflows, so it does not cause any serious consequences if you do not add the letter L after long integer data.
Float (float type)
A floating-point number is used to process real numbers, which are numbers with decimals. Similar to the double type in C, accounting for 8 bytes (64 bits), where 52 bits represent the bottom, 11 bits represent the exponent, and the remaining one represents the symbol.
Complex (plural)
The complex number consists of real and imaginary parts, the general form is X+yj, where x is the real part of the complex, and Y is the imaginary part of the complex, where x and y are real numbers. Note: Small number pools exist in Python:-5 ~ 257 2, Boolean true or False 1 or 03, string
"Hello World"
string concatenation of all evils: the string in Python is embodied in the C language as a character array, each time you create a string, you need to open a contiguous space in memory, and once you need to modify the string, you need to open up again, the evil + sign every occurrence will re-open a space within. list, tuple operations

The list is one of the most commonly used data types in the future, and the list allows for the most convenient storage, modification and other operations of the data.

Create a list by enclosing separate data items separated by commas in square brackets. As shown below:

name = ["111", "222", "333","AA"]

Use the subscript index to access the values in the list, and you can also use square brackets to intercept the characters as follows:
Print (name[0][1])
Print (name[0:3])
You can modify or update the list's data items, or you can use the Append () method to add the list items as follows:
Name.append ("444")
name["abc"


You can use the DEL statement to delete the elements of a list, as in the following example:
Del name[0]
Python List script operators

The operands of the list to + and * are similar to strings. The + sign is used for the combined list, and the * number is used for repeating lists.

As shown below:

Python Expressions Results Description
Len ([1, 2, 3]) 3 Length
[1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] Combination
[' hi! '] * 4 [' hi! ', ' hi! ', ' hi! ', ' hi! '] Repeat
3 in [1, 2, 3] True Whether the element exists in the list
For x in [1, 2, 3]: print x, 1 2 3 Iteration
Python list interception

The list of Python intercepts the type of string manipulation as follows:

=[' spam ',' spam ',' spam! ' ]

Operation:

Python Expressions Results Description
L[2] ' spam! ' Read the third element in the list
L[-2] ' Spam ' Reads the second-to-last element in a list
L[1:] [' Spam ', ' spam! '] To intercept a list starting with the second element



python list Functions & methods
Python contains the following functions:
1 cmp (List1, List2)
compare two elements of a list
2 len (list)
number of list elements
3 max (list)
returns the maximum value of a list element
4 min (list)
returns the minimum value of a list element
5 list (seq)
convert a tuple to a list
Python contains the following methods:
1 list.append (obj)
add a new object at the end of the list
2 list.count (obj)
Count the number of occurrences of an element in a list
3 list.extend (seq)
append multiple values from another sequence at the end of the list (extend the original list with a new list)
4 list.index (obj)
find the index position of the first occurrence of a value from the list
5 List.insert (index, obj)
inserting an object into a list
6 List.pop (obj=list[-1])
removes an element from the list (the last element by default), and returns the value of the element
7 list.remove (obj)
to remove the first occurrence of a value in a list
8 List.reverse ()
reverse List of elements
9 List.sort ([func])
sort the original list

What is a dictionary?

A dictionary is the only type of mapping in the Python language.

A hash value (key, key) and a pointer to an object (values, value) are a one-to-many relationship that is often considered a mutable hash table in the mapping type object.

The Dictionary object is mutable, which is a container type that can store any number of Python objects, including other container types.

The difference between a dictionary type and a sequence type:

1. Access to and access to data differs in different ways.
2. The sequence type only uses the key of the numeric type (indexed in numerical order from the beginning of the sequence);
3. The mapping type can be used as a key for other object types (such as numbers, strings, ganso, generally with strings as keys), and the key of the sequence type is different, the mapping type of the key is straight 4. Associate or indirectly with the stored data value.
5. The data in the mapping type is unordered. This is not the same as the sequence type, and the sequence type is numerically ordered.
6. The mapping type is directly "mapped" to a value with a key.

Dictionaries are one of the most powerful data types in Python.

Basic operation of the dictionary

1. How do I access the values in the dictionary?
Adict[key] Returns the value of key key, if key is not in the dictionary, a keyerror is raised.

2. How to check if key is in the dictionary?

A, Has_key () method shape: Adict.haskey (' name ') has –>true, no –>false
b, in, No in shape: ' Name ' in adict with –>true, no –>false

3, how to update the dictionary?

A, add a data item (new Element) or key-value pair
Adict[new_key] = value form adds an item
B. Update a data item (element) or key-value pair
Adict[old_key] = New_value
C. Delete a data item (element) or key-value pair
Del Adict[key] Delete key key item/del adict delete entire dictionary
Adict.pop (key) deletes the key keys and returns the value corresponding to key

The method of the dictionary

1, Adict.keys () returns a list containing all keys of the dictionary;
2, Adict.values () returns a list containing all the value of the dictionary;
3, Adict.items () returns a list containing all (key, value) Ganso;
4, adict.clear () Delete all the items or elements in the dictionary;
5, Adict.copy () returns a copy of a shallow copy of a dictionary;
6, Adict.fromkeys (seq, val=none) creates and returns a new dictionary, with the element in SEQ making the dictionary key, and Val does the initial value corresponding to all the keys in the dictionary (default is None);
7, Adict.get (key, default = None) returns the value corresponding to the key in the dictionary, and returns the value of default if the key does not exist in the dictionary (default defaults to none);
8, Adict.has_key (key) If key is in the dictionary, returns True, otherwise false. Now with in, not in;
9, Adict.iteritems (), Adict.iterkeys (), Adict.itervalues () and their corresponding non-iterative methods, the difference is that they return an iteration, rather than a list;
10, Adict.pop (Key[,default]) is similar to the Get method. If there is a key in the dictionary, delete and return the key corresponding to the Vuale; if the key does not exist and the default value is not given, the keyerror exception is thrown;
11, Adict.setdefault (key, Default=none) and set () method similar, but if the dictionary does not exist in the key key, by adict[key] = default for it assignment;
12, Adict.update (bdict) adds the dictionary bdict key-value pairs to the dictionary adict.

Shopping Cart Practice

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Shangpin_list = [("iphone","5000"), ("Bike","2000")]
Gouwu_list = []
Money =Input"Your Money")
If Money.isdigit ():
Money =Int (money)
While True:
For Idx,itemInchEnumerate (shangpin_list):
Print (Idx,item)
user =Input"Select your Product")
If User.isdigit ():
user =Int (user)
If user <Len (shangpin_list)and user >=0:
P_item = Shangpin_list[user]

IfInt (p_item[1]) <= money:
Gouwu_list.append (P_item)
Money-=Int (p_item[1])
print ("remaining%s"% (money))
Print (gouwu_list)
Else:
print ("can't afford")
Else:
Print ("input error")
elif User.txt = = "Q":
For i in gouwu_list:
Print (i)
















Python Road II

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.