DAY01-DAY04 Summary-Python data types and their usage

Source: Internet
Author: User
Tags string methods

Python data types and their usage: This article summarizes the various data types used in Python, and how they can be used to make our code concise. Basic structure The first thing we want to see is a data type that almost any language has, including string, Integer, float, and Boolean types. These basic data types form the base control block to create our Python application. A string string is a text character that is usually output to the user in some form. If we open the Python interpreter, we try the most common output "Hello world!" Apply:>>> print ("Hello, world!") Hello, world!. The data type in Python does not require a definition as shown in Java or C, which means that the string in Python is simply labeled in quotation marks, to the "Hello, world!" above That We can also use single quotes instead of double quotes, and when we have double quotes in a string, it is more convenient to use single quotes to represent the entire string, such as:>>> print ("This is David's program"), which is David's program>>> print (' "Hello", said David ') "Hello", said David from above you can see how to cross the different quotes under different conditions. Strings provide a number of built-in functions that are useful in many Python programs, including: EndsWith ()-Checks if a string ends with a given string startswith ()-Checks whether the string starts with the given string upper ()- Converts all characters of a string to uppercase lower ()-converts all characters of a string to lowercase isupper ()/islower ()-detects whether the string is all uppercase/lowercase we can also pass the string as a parameter to the function Len () to return the length of the string, such as Len (" David ") The string in Python is also iterative, and the concept of iteration can be further understood in the list and dictionary data types. This means that we can loop through each character in the string in turn, which is generally not possible in other languages. Another trick about strings is that we can format strings. The best way to do this is to use the format statement, which shows you the type of your incoming object as a string, so you can pass in any type of object to the format method for output. The following:>>> string_1 = "HeLlo, {}, here's your string ". Format (" David ") ' Hello, David, here is your string ' >>>>>> string_2 =" Hello , {}, your is {} years old ". Format (" David "," page ") ' Hello, David, you're all years old ' >>>>>> string_3 =" H Ello, {}, your is {} years old ". Format (" David ", 23.5) ' Hello, David, you're 23.5 years old ' from the code above can be clearly seen, the format method can be used to put any The Python data type is replaced with a string. Boolean types and if statements Boolean values (True or False) are critical in any language, and they allow us to make judgments based on the true and false values of variables that can be used by code to control the path of a program. In Python, the first letter of a Boolean value is capitalized: True and False. For example, using some of the above mentioned string methods, we can test whether a string is uppercase and output the correct result:>>> if "David". Isupper ():p rint (' David ' is uppercase ') else :p rint (' David ' is lowercase ') The IF statement in "David" is lowercasepython to check if the first condition is true, and if true it prints "David" is uppercase. In this case, however, it returns false, so the else block executes and prints out "David" is lowercase. In Python, the data has its implicit true and false values, which helps to make the code short and accurate, and it doesn't need to be judged everywhere. Here's an example of using an implicit Boolean in Python:>>> bool (') false>>> bool (' hello ') true>>> a = none>>> B = 1 >>> BOOL (a) false>>> bool (b)true>>> if A:print ("yes") >>> if B:print ("yes") Yes in this case, you can see that we can check the true and false values of the variables. return TRUE or False by invoking the bool method, passing in our variable to give it a parameter. Null or None (a value like null or Nil in other languages in Python) would be considered False, while others would be considered True. Integer, floating point, complex number (Numbers) in Python as the usual format represents, integer types such as 1,10,56,1045,100433 and so on. Floating point type, usually we need to use decimals, such as 1.23, 0.34532, 23.4667, and so on. Python supports simple and advanced mathematical calculations, has a wide range of uses, the most common or basic arithmetic operations:>>> 1 + 12>>> 1-10>>> 2 * 24>>> 2/21 view P Ython Docs, the plural type is interpreted as follows: Complex numbers is also supported; Imaginary numbers is written with a suffix of J or J. Complex numbers with a nonzero real component is written as (real+ IMAGJ), or can be created with the complex (real, imag) function.>>> 1j * 1J ( -1+0J) >>> 1j * Complex (0,1) ( -1+0J) >>> 3+1j*3 (3+3j) >>> (3+1j) (9+3j) >>> (1+2j)/(1+1J) (1.5+0.5j) Complex numbers is Always represented as-floating point numbers, the real and imaginary part. To extract these parts from a complex number z, use Z.real and Z.IMAG.≫>> a=1.5+0.5j>>> a.real1.5>>> a.imag0.5 More advanced structure lists and a For loop list is one of the most commonly used data structures in Python and other languages. Python uses brackets () to parse the list, allowing you to store the data in any order for easy processing. For example, if we need to extract some data from an object, we can put that data in the list for later use:>>> my_list = []>>> for object in Objects:my_ List.append (object.name) >>> print (my_list) [' Name_1 ', ' name_2 ', ' name_3 '] above example is not good, but you can see that we are if we extract data from the object, And put them in our list. Similarly, if we have two lists, using the Extend method we can combine them into a:>>> list_1 = [1,2,3]>>> list_2 = [4,5,6]>>> print ( List_1.append (list_2)) [1,2,3,[4,5,6]]>>> print (List_1.extend (list_2)) [1,2,3,4,5,6] This can clearly see the difference between these two important methods. In our first example, using a For loop to form a list from our data, a more concise workaround is to use the list extension, which compresses the entire process into one line. This is an efficient solution provided by python:>>> my_list = [Object.name for object in objects]>>> print my_list[' name_1 ', ' Name_2 ', ' name_3 '] and see how this is mapped to the first method: In the list, we traverse the objects, use object as the variable name for each element from objects, and finally we take out the name of object to form our list. In addition to using square brackets to construct list objects, we can use list constructors to create our list, as follows:>>> list (' a ') [' a ']>>> values= (1,2,3,4) # A Tuple object see below>>> list [1,2,3,4] dictionary another commonly used Python data structure is the dictionary (dictionaries). Dictionaries are used to store large amounts of data and provide a quick way to process them. An example of a common dictionary application is the Address Book system. In this data structure of the dictionary, you need a unique ' key ' to query its corresponding ' value '. In the Address book, the only ' key ' can be a phone number, so the dictionary structure is:>>> phonebook = {' 012345678 ': ' A person ', ' 987654321 ': ' A.N Other '} Here we have a dictionary, the phone number as ' key ', corresponding to the name as ' value '. Now we can use this structure to query, as follows:>>> phonebook[' 012345678 ' ' A person ' Python dictionary also provides the standard method for iterating through each number, which are: Iteritems, Iterkeys and Itervalues. These functions allow us to iterate keys and values, iterate only keys, and iterate only on values. Here's an example: Iterate over all items:>>> for key, value in Phonebook.iteritems (): Print (key, value) 987654321 A.N Other012345678 A person Iterates over all keys:>>> for keys in Phonebook.iterkeys (): Print (key) 987654321012345678 iterates over all values:>>> for Value in Phonebook.itervalues (): print (value) A.N Othera There are more than one way to create a dictionary, as is the list. So far, we have only used a method that is enumerated individually and enclosed in curly braces to create a dictionary. However, we can also create using the dictionary constructor as follows, we need to pass in keyword arguments to create our dictionary key value pair:>>> dict (a=1, b=2, c=3) {' A ': 1, ' C ': 3, ' B ': 2}sets and Frozensets similar to lists, we also have collections (sets) and FrThe data structure of the ozensets. Collections allow us to store data like a list, but the difference is that duplicate elements are not allowed in the collection. This is great when we want to make sure that every piece of data has only one copy. Frozensets is almost the same as a normal collection, but it is an immutable type (immutable), which means that once it is created, it can no longer be changed in any way. Similarly, we have enumerated methods for creating collections (note: The same elements are automatically deleted):>>> a = {1,2,3,3}set ([1, 2, 3]) can also use the constructor:>>> set ([1,2,3,3]) set ([1, 2, 3]) Python provides a powerful set of operation methods, we can complete the mathematical set of the combination, intersection, difference set, and so on, as follows:>>> a = {1,2,3}>>> B = {3,4,5}>>> A.union (b) Set ([1, 2, 3, 4, 5]) >>> >>> a.difference (b) Set ([1, 2]) >>> >>> A.intersection (b) Set ([3]) The last Python data type presented in the tuple is a tuple (tuples). Tuples are similar to lists, separated by commas (,) to separate stored data, unlike lists where tuples are immutable types (immutable), and lists can be inserted or changed by you, but not tuples. Therefore, tuples apply to situations where your data is fixed and does not need to be changed. From a memory point of view, there is a great advantage to using tuples that Python can clearly know how much memory needs to be allocated to tuples (the same frozensets also has this benefit). Python also provides enumeration and construction methods to create a tuple:>>> my_tuple = (1,2,3,4) (1,2,3,4) >>> >>> a = tuple ([1,2,3,4]) >>> type (a)

Day01-day04 Summary-Python data types and their usage

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.