Python's basic syntax, covering data types, looping judgments, lists, maps, set, and more

Source: Internet
Author: User
Tags ord

#the statement at the beginning is a comment

When the statement ends with a colon ":", the indented statement is treated as a block of code. Generally indent 4 spaces

The Python program is case-sensitive, and if the case is written incorrectly, the program will error.

Data types for Python

    • Integral type
    • Floating point Type
    • String
    • Boolean value
    • Null value

Variable

This block of variables needs to be well explained. Python is a dynamic language, its variables do not require a specified type, and Java is a static language, and to use a variable, you must specify the type for the variable.

In this case, the Python variable is simple, like this:

A = 3

x = "Hello"

And so on are variables.

A Python string

Because Python was born earlier than the Unicode standard, the earliest Python only supported ASCII encoding, and ordinary strings were ‘ABC‘ ASCII-encoded inside python. Python provides the Ord () and Chr () functions to convert letters and corresponding numbers to each other:

>>> ord(‘A‘)65>>> chr(65)‘A‘

Python later added support for Unicode, expressed in Unicode as a string u‘...‘ , for example:

>>> print u‘中文‘中文>>> u‘中‘u‘\u4e2d‘

Because the Python source code is also a text file, so when your source code contains Chinese, it is important to specify that you save it as UTF-8 encoding when you save it. When the Python interpreter reads the source code, in order for it to be read by UTF-8 encoding, we usually write these two lines at the beginning of the file:

#!/usr/bin/env python# -*- coding: utf-8 -*-

The first line of comments is to tell the Linux/os x system that this is a python executable and the Windows system ignores this comment;

The second line of comments is to tell the Python interpreter to read the source code according to the UTF-8 encoding, otherwise the Chinese output you write in the source code may be garbled.

Formatting of strings

In Python, the format used is consistent with the C language, and is implemented as an % example:

>>> ‘Hello, %s‘ % ‘world‘‘Hello, world‘>>> ‘Hi, %s, you have $%d.‘ % (‘Michael‘, 1000000)‘Hi, Michael, you have $1000000.‘

As you may have guessed, the % operator is used to format the string. Inside the string, the representation is replaced by a string, which %s %d is replaced with an integer, there are several %? placeholders, followed by a number of variables or values, the order to correspond well. If there is only one %? , the parentheses can be omitted.

Common placeholders are:

%d Integer
%f Floating point number
%s String
%x hexadecimal integer

Another way to output string concatenation is to use the Format method.

Name = "Kobayashi"

Age = 25

Sex = "male"

Print (' My name is {0}, is a {1} born, this year {2} years old '. Format (name,sex,age))

Python input and output

Output:

Print ()

Input:

Name = Raw_input ()

List types for Python

1 #Encoding:utf-82 3 #There are two kinds of data collection types built into the Pythton, one is list, and the other is a tuple4 5 #List is an ordered set, you can query, add, delete, modify the list6 7 #A tuple is a tuple that has a sequence table. Unlike list, the contents of a tuple cannot be modified, so it has no method to add, modify, or delete. 9  Ten  One #1. List A  -MyList = ['a','b', 123,'ABC'] -  the Print(myList)  -  + #query operation for 1.1 list -  + Print(Mylist[0])#Get the element of list by index, get the first element A  at Print(Mylist[-1])#get the last element in a list -  - Print(Len (myList))#get the length of a list -  -   -  in #1.2 The Add operation of the list -  toMylist.append ('D')#append an element at the end of the list +  -Mylist.insert (2,'Insert Element')#add an element at the specified position in the list the  *   $ Panax Notoginseng #1.3 The delete operation of the list -  theMylist.pop ()#Delete the element at the end of the list +  AMylist.pop (2)#deletes the element at the specified position in the list the  +   -  $ #1.4 List's modification operation $  -Mylist[0] ="AAA" #modifies the value of a specified position in a list -  the   - Wuyi #1.5 multi-dimensional arrays the  -List_tmp = ['1','2'] Wu  -Mylist.append (LIST_TMP)#You can insert another list in a list About  $ Print(Mylist[4][1])#you can get the elements of the inner class table by specifying the following table -  -   -  A #2. Tuple +  the #What is the meaning of immutable tuple? Because the tuple is immutable, the code is more secure. If possible, you can use a tuple instead of a list as much as possible.  -  $Mytuple = ('a','b', 123,'ABC') the  the   the  the #Query operations for 2.1 tuple -  in Print(mytuple[0]) the  the Print(Mytuple[-1])#a tuple gets an element that operates like a list About  the   the  the #2.2 A tuple's trap +  - #When you define a tuple, the elements of the tuple must be determined at the time of definition. the Bayit = ()#to define an empty tuple the  thet = (1)#to define a tuple with only 1 elements, if you define it this way: the result is 1. -  - #The definition is not a tuple, is 1 this number! This is because parentheses () can represent both tuples and parentheses in mathematical formulas, which creates ambiguity. the  the ## As a result , Python specifies that, in this case, the parentheses are calculated and the result is naturally 1.  the  the #therefore, only 1 elements of a tuple definition must be added with a comma, to eliminate ambiguity: -  thet = (1,)#this defines the result as (1,) the  the #Python will also add a comma when displaying a tuple of only 1 elements, lest you misunderstand the parentheses in the mathematical sense. 

Python's judgment loop

#the Python loop. One is a for loop, one is a while loop#For Loop, read out the list elementnames= ["AA","BB","cc","DD"] forNameinchnames:Print(name)#while loop, calculates the sum of the elements in the listarr= Range (101) n=0sum=0 whileN <Len (arr): Sum+=Arr[n] n+=1Print(sum)#Python's judgment. To achieve a good judgment of the differencescore= Int (raw_input ())#coercion of type conversions, Raw_input reads always in the form of a stringif(Score >=90 andScore <=100):    Print("Excellent")elif(score>=70 andScore<90):    Print("Good")elif(score>=60 andScore<70):    Print("General")elif(score>=0 andScore <60):    Print("inferior lattice")Else:Print("Please enter the correct score! ")

Python's dict and set

Python built-in dictionary: dict support, Dict full name dictionary, in other languages also known as map, using key-value (Key-value) storage, with a very fast search speed.

It is important to use dict correctly, and the first thing to keep in mind is that the Dict key must be an immutable object .

Dict is unordered, equivalent to the HashMap in Java

1Mydict = {"AA": 92,"BB": 85,"cc": 56,"DD": 64}2 3 #Dict's Search4 5  forKinchmydict:6 7     Print("%s got%d points"%(K,mydict.get (k)))8 9 #Modification of DictTen  Onemydict["AA"] = 100 A  - Print(mydict["AA"]) -  the #additions and deletions of dict -  -mydict["ee"] = 88#additions to Python -  +Mydict.pop ("ee")#Delete -  + Print(Mydict.get ("ee"))#return None

Set is similar to Dict and is a set of keys, but does not store value. Because key cannot be duplicated, there is no duplicate key in set.

Equivalent to HashSet in Java

1 myset = ([1,2,3,4])23for in# traversal 4 5     Print (k) 6 7 # Append 8 9 # removed from

Python's basic syntax, covering data types, looping judgments, lists, maps, set, and more

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.