Getting started with Python in 30 minutes-data type and control structure, python Data Type
Python is a scripting language and I have heard of it for a long time, but it is the first time that the real system came into contact with me from the end of last year (2013) to the beginning of this year (2014. I have to say that Python official documentation is quite complete. If you are learning Python on Windows, the "Python Manuals" that comes with the installation package is a good learning material (basically no other materials are required). Specifically, Tutorial is suitable for beginners. On the one hand, this article summarizes the core of the python language-data types and control structures; on the other hand, it compares with other languages to express some of my views on Python.
Python is concise because of its powerful type system support. The basic data types in the Python world include {int, long, float, complex, str, list, set, tuple, dict }, the following example uses the Python interpreter to demonstrate the input and output instances in interactive mode (with a leading character >>> or... input): tips: In the Python world, type (x) can be used to output the x type. int, long, float, str, complex
>>> type(123)<type 'int'>>>> type(-234)<type 'int'>>>> type(123456123456)<type 'long'>>>> type(-123456123456)<type 'long'>>>> type(123.456)<type 'float'>>>> type('abc')<type 'str'>>>> type("hello, world")<type 'str'>
From the last two inputs, we can see that Python strings can be enclosed in single or double quotation marks. In addition, you may wonder how big is int and long? Let's look at the details below:
>>> type(123456)<type 'int'>>>> type(123456789)<type 'int'>>>> type(1234567890)<type 'int'>>>> type(12345678901)<type 'long'>
We can see that the value 1234567890 or int indicates that the value 12345678901 is long, indicating that the int value has a range. Remember that the int length (4B) of C/C ++ knows that the int value range in C/C ++ is: [-2 ^ 31, 2 ^ 31-1], that is, [-2147483648,214 7483647]. Accordingly, we can look at the int range of Python:
>>> type(2147483647)<type 'int'>>>> type(2147483648)<type 'long'>>>> type(-2147483648)<type 'int'>>>> type(-2147483649)<type 'long'>
This test shows that the int range of Python is the same as that of C/C ++. So what if I want to specify a small long? You can add the L (or lowercase l) Suffix:
>>> type(1L)<type 'long'>>>> type(2l)<type 'long'>
In addition, the floating point number in Python is not double:
>>> type(123.456)<type 'float'>>>> type(123456123456.123456123456123456123456)<type 'float'>
The complex type of complex (plural) is not available in many languages. Python uses the integer plus J (or lowercase j) Suffix to indicate the plural:
>>> type(3+4j)<type 'complex'>>>> type(3+4J)<type 'complex'>>>> type(4j)<type 'complex'>>>> type(j)Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'j' is not defined>>> type(1j)<type 'complex'>
However, 1j cannot be directly written as j, and j will be searched as name. If not found, an error will be reported.
List, set, tuple, dictlist, tuple, and dict are lists, tuples, and dictionaries (some languages are called ing map ). These types are extraordinary in Python systems. In most compiled languages (C, C ++, Java, C #, etc, these types must be provided through libraries (such as C ++, Java, and C #), and some may not be provided (such as C ).
>>> type([1, 2, 3])<type 'list'>>>> type({2, 3, 4})<type 'set'>>>> type((3, 4, 5))<type 'tuple'>>>> type({'key1': 'value1', 'key2': 'value2'})<type 'dict'>
We can see that
(), [], {}, And a series of elements included in it, which are tuples, lists, and sets.. Dict is in the form of {key1: value1, [key2: value2. The element types of the various sets listed above are consistent, which is usually required in compiled languages, but not in Python:
>>> (1, 'two', 3.0)(1, 'two', 3.0)>>> [(1, 'two', 3.0), '4', 5][(1, 'two', 3.0), '4', 5]>>> {1, 2L, 3.0, 4j}set([1, 2L, 3.0, 4j])>>> {1: 'one', 'one': 1}{1: 'one', 'one': 1}
When the Structured Programming Method of the control structure is proposed, some predecessors have proved that any algorithm can be expressed in three structures: sequence, selection, and loop. The following shows the basic syntax of Python, as well as selection and loop.
There is nothing to say about the ordered structure. Here we will introduce other features of Python. Statement
The Python statement ends with a line break.(Unlike the end Of the semicolon in the C family ):
>>> print "hello, world"hello, world
In addition, the Python program does not have the so-called "entry", which is similar to most scripting languages.
Weak type
Python is of a weak type.That is, the variable type is not static. This is similar to many scripting languages.
>>> a = 123>>> b = "asdf">>> c = [3, 4, 5]>>> a123>>> b'asdf'>>> c[3, 4, 5]>>> a = b>>> b'asdf'
There are two differences between this interaction and C ++:
Tip: In the interaction mode of the Python interpreter, directly enter the variable name to display the variable value.The term "variable" should be called "name" (or symbol) in Python. in Python, you can assign any type of value to a symbol. Later, you will see that you can assign a value to an int object as a function and a class.
Function
The function definition in Python starts with def. If there is a returned value, return must be used to pass the returned value.For example, the following code defines a function named sayHello and uses 'jack' as the parameter for a call:
def sayHello(name):print 'Hello, ' + name + '!'sayHello('Jack')
The running result of this Code is: Hello, Jack! (You can save this code as sayHello. py, and then run python sayHello. py in the corresponding directory)
Class
The class definition of Python starts with class. attributes can be declared under class or implicitly declared through self. xxx in the _ init _ method.Let's take a look at the simplest code about the class:
class Man:def __init__(self, name):self.name = namedef hello(self):print 'Hello, ' + self.name + '!'m = Man('Jack')m.hello()
This Code also outputs: Hello, Jack!
Tips: the first parameter of the Python method must be a parameter named self, which is used to operate on members of an object. _ Init _ is similar to the "constructor" in other languages.
More features of the class are related to OOP. I will post a blog post later.
By the way, let's take a look at what functions, classes, and classes are in the eyes of the Python Interpreter:
>>> type(sayHello)<type 'function'>>>> type(Man)<type 'classobj'>>>> type(m)<type 'instance'>>>> type(m.hello)<type 'instancemethod'>>>> type(Man.hello)<type 'instancemethod'>
As you can imagine, everything in the Python world is "gray", and the interpreter treats them "equally". They never look at people by appearance, but only what labels they have ~
Select Structure
The Python selection structure starts with if.Boolif must involve bool values. Python bool values are True and False:
>>> type(1==1)<type 'bool'>>>> type(True)<type 'bool'>>>> type(False)<type 'bool'>
(I forgot to list the bool Type above)
For Number (int, long, float, complex), 0 is also False on the if condition:
>>> if 1:... print "true"...true>>> if 0:... print "true"... else:... print "false"...false>>> if 0.0:... print "0.0 is true"...>>> if 0j:... print "0j is true"...
Tip: Python uses code indentation to differentiate code blocks
In addition, the empty string and empty set (tuple, list, set) are also False:
>>> if '':... print 'null string is true'...>>> if ():... print 'null tuple is true'...>>> if []:... print 'null list is true'...>>> if {}:... print 'null set is true'...
If, if-else & if-elif-else the above example only has one branch. Of course, Python also supports the if:
>>> x = int(raw_input("Please enter an integer: "))Please enter an integer: 42>>> if x < 0:... x = 0... print 'Negative changed to zero'... elif x == 0:... print 'Zero'... elif x == 1:... print 'Single'... else:... print 'More'...More
Loop Structure
Python has two types of loops: for and while.No do-while or loop-.
The for loop of forPython is different from that of C. It is more like the new for loop in C ++ and Java:
>>> a = [1, 'two', 3.0]>>> for i in a:... print i...1two3.0
This for iteration set is very convenient.
But what should I do if I want to iterate an integer range like a for Loop in a typical C language? Don't be afraid. Python provides the built-in (built-in) function range (), which can return the list of integer ranges for your iteration and is convenient to use:
>>> for i in range(1, 6):... print i...12345>>> for i in range(10, 65, 10):... print i...102030405060
Here we show two call methods of range. One is range (a, B), which returns a value from a (including a) to B (not including) the list of Integers (list), another range (a, B, s), will return ~ B. list with s as the step:
>>> range(1, 6)[1, 2, 3, 4, 5]>>> range(10, 65, 10)[10, 20, 30, 40, 50, 60]
The while loop of whilePython is similar to the while loop of C:
>>> i = 1>>>>>> while i < 5:... i = i+1... print i...2345
By the way, I = I + 1 in Python cannot be written as I ++. Python does not support this syntax, but can be written as I + = 1:
>>> i5>>> i += 1>>> i6>>> i++ File "<stdin>", line 1 i++ ^SyntaxError: invalid syntax>>> ++i6>>> i6
You may wonder why ++ I does? Because pyhon supports the + (plus and minus signs) operation, ++ is considered as two normal operations. Similarly, ++ I and ++ I are the same; we can test the negative number calculation by the way:
>>> i6>>> +++i6>>> ++++i6>>> -i-6>>> --i6>>> ---i-6
Consistent with the expected results, Great!
Input/output (IO) when you want to write "more interesting" applets, you will find that apart from the three basic control structures and data types, what you need most is the IO function. Q: print can be used for output. What about input? Is it input? A: input is acceptable, but more often we need to use the raw_input and readline built-in functions, but readline is only applicable to Unix platforms. q: What is the difference between input and raw_input? A: Let's take A look at the interaction between me and the interpreter to see if you can discover their differences by yourself.
>>> varA = raw_input('please input:')please input:Life is too short, you need Python!>>> varA'Life is too short, you need Python!'>>> type(raw_input('input something:'))input something:asdf<type 'str'>>>> type(raw_input('input something:'))input something:123<type 'str'>
A: As you can see, raw_input returns the str type no matter what you input. This is why raw_input is called. A: continue. You will see the input:
>>> type(input('input sth:'))input sth:123<type 'int'>>>> type(input('input sth:'))input sth:asdfTraceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module>NameError: name 'asdf' is not defined>>> type(input('input sth:'))input sth:varA<type 'str'>>>> input('sth:')sth:varA'Life is too short, you need Python!'>>> input('try some input like your code:')try some input like your code:[1, 'two', 3.0][1, 'two', 3.0]>>> input('try again:')try again:'Oh!!!''Oh!!!'
Q: Oh, I know! Input will explain the input in the form of code! A: Well, you mentioned "explanation". It seems that you have realized the true meaning of Python. You can go down the hill! Q: Can this be done for the Master? I know too little, right? A: Here is A "Python secret". You can take it. You can find the answer to all the questions, but the answer may not be in this book. (apprentice A should leave Master Q, started his Python journey)
Postscript (my workshop) Python is an interpreted language, and its built-in collection type is very powerful! As a C-family language (C, C ++, Java, and C #), tuple, list, set, and dict are all built-in types, it's amazing! In my opinion:
1. Because of the language-level tuple, list, set, dict, Python is very suitable for writing algorithms.And the algorithm written by Python must be much simpler than other languages! 2. the Python syntax is concise and easy to understand. By default, it provides file management and other functions, which can replace most other scripts. 3. The weak type (with few constraints) of Python and the fun and convenience of the interpreter interaction mode are very suitable for teaching children and adolescents as the "first programming language.
Beginner in python Data Type
This has nothing to do with the xlrd module. The xlrd module should not have the get_Excel_value_S function, which should be defined by you and the returned data type is float, if you do not want to use data conversion, there are two solutions.
1. Write a function that returns an integer.
2. Confirm the table corresponding to this array and obtain this value through the cell in xlrd, such as xxx = table. cell (0, 0 ). value. Two zeros indicate the number of rows and the number of columns respectively.
Determine the value type in python
N = None
While not isinstance (n, int ):
N1 = raw_input ("Please input a number :")
Try:
N = eval (n1)
Except t:
N1 = raw_input ("Please input a number :")
# Try-exclude t exclude the input as a string. Because the string composed of letters cannot be eval, but '123' can be eval
# Isinstance (*, int) is the method for checking whether * is an integer.
Well, I think the code caused by this requirement is quite awkward.
N = int (raw_input ("Please input an integer :"))
Although not very robust...