Python basics,

Source: Internet
Author: User
Tags floor division

Python basics,

 

print()The function can accept multiple strings separated by commas (,) to form a string of output:

>>> print('The quick brown fox', 'jumps over', 'the lazy dog')The quick brown fox jumps over the lazy dog

 

Python syntax is relatively simple and indented;

# print absolute value of an integer:a = 100if a >= 0:    print(a)else:    print(-a)

# Comments are started. Each other line is a statement. When a statement starts with a colon:At the end, the Indented statement is considered as a code block.

The disadvantage of indentation is that the "copy-paste" function is invalid, which is the most pitfall. When you refactor the code, the code pasted in the past must be re-checked to check whether the indentation is correct.

The Python program is case-sensitive. If an error occurs, the program reports an error.

 

Data Type and variable integer, floating point, string

If 'is also a character, it can be enclosed by "". For example, "I'm OK" contains the characters I,', m, space, O, k.

The character string contains both 'and' --- escape characters.\To identify

'I\'m \"OK\"!'

Escape characters\Can escape many characters, such\nLine feed,\tTab, Character\It also needs to be escaped, so\\The character is\

>>> print('I\'m ok.')I'm ok.>>> print('I\'m learning\nPython.')I'm learningPython.>>> print('\\\n\\')\\

Boolean value can be usedand,orAndnotOperation.

A null value is a special value in Python.None.NoneCannot be understood0Because0Is meaningful, andNoneIs a special null value.

 

a = 'ABC'b = aa = 'XYZ'print(b)

Output the variable in the last line.bIs'ABC'Or?'XYZ'? If we understand it in a mathematical sense, we will get it wrong.bAndaSame, it should also be'XYZ'But actuallybThe value is'ABC'。

Runa = 'ABC'The interpreter creates a string.'ABC'And Variablesa, AndaPoint'ABC':

Runb = aThe interpreter creates a variable.b, AndbPointaString'ABC':

Runa = 'XYZ', The interpreter creates the string 'xyz' andaChanged'XYZ',bNot changed:

So, finally print the variablebThe result is naturally'ABC'.

 

In Python, constants are usually represented by variable names in uppercase.

In Python, there are two division methods:

One division is/

>>> 10 / 33.3333333333333335

/The Division calculation result is a floating point number, and the result is also a floating point number even if two integers are exactly divided:

>>> 9 / 33.0

Another division is://, Called floor Division, the Division of two integers is still an integer:

>>> 10 // 33

Python also provides an remainder operation to obtain the remainder of two integers:

>>> 10 % 31
String and encoding

In Python 3, strings are Unicode encoded. That is to say, Python strings support multiple languages.

>>> Print ('str' containing Chinese characters) contains Chinese str

For the encoding of a single character, Python providesord()The function obtains the integer representation of a character,chr()The function converts the encoding to the corresponding characters:

>>> Ord ('A') 65 >>> ord ('中') 20013 >>> chr (66) 'B' >>> chr (25991) 'wen'

ComputingstrThe number of characters in length.len()Function:

>>> Len ('abc') 3 >>> len ('Chinese') 2

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

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

The first line of comment is to tell the Linux/OS X system that this is a Python executable program and will be ignored in Windows;

The second line of comment 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.

 

Use list and tuple

A built-in data type in Python is list:List. List is an ordered set that allows you to add and delete elements at any time.

>>> classmates = ['Michael', 'Bob', 'Tracy']>>> classmates['Michael', 'Bob', 'Tracy']

VariableclassmatesIs a list. Uselen()The function can obtain the number of list elements:

>>> len(classmates)3

Use indexes to access the elements at every position in the list. Remember that the index is from0Starting from,

>>> classmates[0]'Michael'>>> classmates[1]'Bob'>>> classmates[2]'Tracy'>>> classmates[3]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range

The index of the last element islen(classmates) - 1.

To obtain the last element, you can use-1Index to directly obtain the last element:

>>> classmates[-1]'Tracy'

Append an element to the end of the list:

>>> classmates.append('Adam')>>> classmates['Michael', 'Bob', 'Tracy', 'Adam']

You can also insert an element to a specified position, for example, index number1Location:

>>> classmates.insert(1, 'Jack')>>> classmates['Michael', 'Jack', 'Bob', 'Tracy', 'Adam']

Delete the elements at the end of the list.pop()Method:

>>> classmates.pop()'Adam'>>> classmates['Michael', 'Jack', 'Bob', 'Tracy']

Deletes an element at a specified position.pop(i)Method, whereiIs the index location:

>>> classmates.pop(1)'Jack'>>> classmates['Michael', 'Bob', 'Tracy']

 

Another ordered list is called a tuples:Tuple. Tuple and list are very similar, but tuple cannot be modified once initialized. For example, they are also used to list the names of students:

>>> classmates = ('Michael', 'Bob', 'Tracy')

What is the significance of an immutable tuple? Because tuple is immutable, the code is safer. If possible, use tuple instead of list.

When defining a tuple with only one element, a comma must be added.,To eliminate ambiguity (parentheses()It can represent both tuple and parentheses in the mathematical formula, which produces ambiguity ):

>>> t = (1,)>>> t(1,)

Let's look at a "variable" tuple:

>>> t = ('a', 'b', ['A', 'B'])>>> t[2][0] = 'X'>>> t[2][1] = 'Y'>>> t('a', 'b', ['X', 'Y'])

On the surface, the tuple element does change, but it is not the tuple element, but the list element (the third element of tuple is list ).

 

Condition judgment

In a Python programifStatement implementation:

age = 20if age >= 18:    print('your age is', age)    print('adult')
age = 3if age >= 18:    print('your age is', age)    print('adult')else:    print('your age is', age)    print('teenager')

Do not write less colons.:

elifYeselse ifCan have multipleelif, SoifThe complete statement form is:

If <condition judgment 1>: <execution 1> elif <condition Judgment 2>: <execution 2> elif <condition judgment 3 >:< execution 3> else: <execution 4>

ifStatement execution has the following characteristics: it is judged from top to bottom, if it isTrue, Ignore the remainingelifAndelseSo, what the following program prints isteenager:

age = 20if age >= 6:    print('teenager')elif age >= 18:    print('adult')else:    print('kid')

 

Str string to integer: UseInt ()Function

 

Loop

Python has two types of loops:For... inLoop

names = ['Michael', 'Bob', 'Tracy']for name in names:    print(name)

for x in ...A loop is to substitute each element into a variable.xAnd then execute the indent BLOCK statement.

You can usesumVariable accumulation:

sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:    sum = sum + xprint(sum)

If you want to calculate the sum of integers from 1 to 100, it is a little difficult to write from 1 to. Fortunately, Python providesrange()Function to generate an integer sequence.list()Function can be converted to list. For examplerange(5)The generated sequence is an integer less than 5 starting from 0:

>>> list(range(5))[0, 1, 2, 3, 4]

range(101)You can generate an integer sequence between 0 and.

sum = 0for x in range(101):    sum = sum + xprint(sum)

The second type of loop is the while loop. as long as the condition is met, the loop continues. If the condition is not met, the loop exits.

Calculate the sum of all odd numbers within 100:

sum = 0n = 99while n > 0:    sum = sum + n    n = n - 2print(sum)

Variable in the loopnContinue to reduce until it changes-1The while condition is no longer met, and the loop exits.

In the loop,breakStatementYou can exit the loop in advance:

N = 1 while n <= 100: if n> 10: # When n = 11, the condition is met. Run the break statement break # The break statement ends the current loop print (n) n = n + 1 print ('end ')

Print 1 ~ After 10, printEND, The program ends.breakThe function is to end the loop in advance.

 

You can also usecontinueStatement to skip the current loop and start the next loop directly.

Print the odd number between 1-10:

N = 0 while n <10: n = n + 1 if n % 2 = 0: # if n is an even number, execute the continue statement continue # The continue statement will continue the next loop directly, and the subsequent print () statement will not execute print (n)

Printing is no longer 1 ~ 10, but 1, 3, 5, 7, 9.

continueThe role is to end this round of cycle ahead of schedule and start the next round of cycle.

 

Use dict and set

Dict

>>> d = {'Michael': 95, 'Bob': 75, 'Tracy': 85}>>> d['Michael']95

To delete a key, usepop(key)Method. The corresponding value is also deleted from dict:

>>> d.pop('Bob')75>>> d{'Michael': 95, 'Tracy': 85}
Set

Similar to dict, set is also a set of keys, but does not store values.

 

Tutorial: https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431658427513eef3d9dd9f7c48599116735806328e81000

 

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.