First knowledge of Python

Source: Internet
Author: User

First, what is Python?

Python is an object-oriented, interpretive type of computer language, it is characterized by simple syntax, elegant, easy to learn. In 1989 births, Guido (Uncle Tortoise) developed. The python here is not meant to be python, but the turtle uncle likes a TV series called "Monty Python Flying Circus", so it is named after Python (the foreigner is so willful).

Ii. explanatory language and compiled language

Compiled language is the first to translate the written program into a computer language and then execute, is called a compile everywhere, such as C, C + + is a compiled language, the language is characterized by the speed of operation, but need to pre-compile the program can be.

Interpreted language is the program at the time of operation, through an interpreter, the code sentence by translation into a computer language and then run, that is, you write the code directly can run, such as Python, Shell, Ruby, Java, Perl and so on are interpreted language, Of course, such a language because of the principle is not the same, the execution speed is not compiled language fast.

Three, python with the key points:

1. Output. First Program Hello world!

The first written program does not mundane to output Hello world! as a usual To write the first program, the print function to achieve:

Print (' Hello world! ')

2. Variables

A variable is a store of things that can be invoked by subsequent programs. The definition of variables in Python is simple, an equal sign does not need to specify the data type, the direct definition is good, it is worth mentioning that the python variable is stored in memory address, that is, where the value exists in memory, if the variable is assigned to another variable, The new variable is stored by the memory address of the variable value that the previous variable knows about, not the previous variable pointed to.

Rules for defining variables:

(1). Variable names can only be any combination of letters, numbers, or underscores
(2). The first character of a variable name cannot be a number
(3). The following keywords cannot be declared as variable names

[' and ', ' as ', ' assert ', ' break ', ' class ', ' Continue ', ' def ' , ' del ', ' elif ', ' Else ', ' except ', ' exec ', ' finally ' ,  "for"   ' from ' ,  ' global ' ,  ' if ' ,  ' import ' ,  ",  ' is ' ' Lambda ' ,  ' not ' ,  ' or ' ,  ' pass ' ,  ' print ' ,  ' raise ' ,  ' return ' ,  ' Try ', ' while ', ' with ', ' yield ']

Single quotes, double quotes, and three quotation marks in 3.python

When you define variables in Python, the strings are enclosed in quotation marks, with no difference between single and double quotes, and with nothing.

(1). There are double quotes inside, with single quotes outside, with double quotes inside the outside with single quotes
(2). Use three quotation marks if there are double quotes in single quotes
(3). Three single quotes with bulk annotation function

4. Input, output

How does python receive user input, using the input function, the code is as follows:

                                      Name=input (' Please enter your name: ') #把接受到的值赋给name变量
Print (name) #输出接收到的输入

Input at the time of receiving inputs, you can see the value you entered, if you enter the password do not want others to see your password, you need to use a standard library getpass, directly using the Getpass.getpass method can be entered in the time, will not display the input content, the code is as follows:

                                            Import Getpass
passwd = Getpass.getpass (' Please enter your password: ')
Print (passwd)

5. Conditional judgment

The conditional judgment in Python uses if else to judge, multi-branch words using if elif ... else. In Python, a block of code is represented by indentation. The code examples are as follows:

score = Int (input (' Please enter your score: '))  # receives input because input receives a string, so the INT function is required to force the type to be converted to an integer type
If score = =: # If the score equals 100 points
Print (' Full score, Bang Bang! ‘)
Elif score >= and score <: # If the score is greater than or equal to 90 points less than 100 points
Print (' A little bit less than a perfect score, keep trying! ‘)
Elif Score > Score <: # If the score is greater than 60 points less than 90 points
Print (' Barely passed! ‘)
else: # If the score is less than 60 points
Print (' That's the effort! ‘)

6. Cycle

There are two types of loops in Python, while and for. The difference between the two loops is that the while loop, before the first judgment, if the condition is met, then the loop, for loop must have an iterative object, in order to loop, for example, there is an array, it is worth mentioning that in other languages, for loop need to first define a counter variable, Then add it from 0 until the counter reaches your preset value, then stops the loop, and when the data is taken, it is taken from 0 by the subscript of the array.

The For loop in Python is simple, looping through an element in an iterative object, how many elements you have in the object, how many times you want to loop, say an array list,list = [' A ', ' B ', ' C '], in other languages to get the values in the list, You have to use the loop to take off the index to get the data, you have to write list[x],list[x],list[x] this way, in Python there is no need for a direct loop to take the list inside the value, the loop there are two more important keywords, Continue and break,continue mean, jump out of this loop and proceed to the next loop, which means Stop the loop, meaning that the code under continue and break is not executed, in the following format:

#if判断时候, both true and false, that is, true and false.
#记住一句话, not 0 is true, non-empty is true

 #while Cyclecount = 0 while Count<: #如果count小于10的话, execute the following code, if it is not less than 3, go to else print (count) if count= =5: break#如果count等于5的话, just end the loop count+ =1 #这个意思是每次循环完, the value of Count is added one, if not added, the condition has been true, the cycle of death, has been constantly circulating else:#这个else是可以不写的, which means that if the condition is not met, the output hint Print(' condition not satisfied, jump out of Loop ') #for Cycle names = [' Marry ',' Lily ',' Lilei '] for name in names: if name = = ' Lily ': contiune #如果名字等于lily的话, do not execute continue the following code, and then cycle the next Print(name) else:#for也有个else, but this is generally no one writes it, meaning if the normal cycle is donePrint(' over ')

7.Let ' s play! A little game of guessing numbers

Since we have learned the conditions of judgment and circulation, then use it to practice exercises, write a small game, guess the number of games, the request is so, produce a random number, 1-100, receive user input, if guessed right, the game is over, guess big, hint guess big, small hint guess small. Generate random number module using Random.randint (1,101), is a standard package, the import can use, the code is as follows:

import Random sub_str=random. Randint(1,101) A random number of #生成1-100 while 1:#while的意思就是, let it always be true, that is, a dead loop, the following break to stop the loop num=int(input(' plase enter a num, 1-100: ')) if num>and num<1: between #判断输入的数字是否在1-100 Print(' num error,plase enter 1-100. ') )Continueelse: if num= =sub_str: #如果猜对了, end loop Print(' you win. Game over,the num is%d '%sub_str)#不懂这个的请看下面的第十四, string formatted output Breakelif num < sub_str:#如果猜小了, just jump out of this loop and tip your little guess. Print(' The num is small,plase enter other num. ') Continueelse:#就三种情况, big, small equals, the front two kinds is equal and light rain, then else is greater than, if guess big, jump out of this cycle, hint guess big Print(' The num is too big,plase enter other num. ') Continue

8. Formatted output

What is formatted output, that is, your output is formatted into a look, such as login welcome information, are welcome to Login,marry. Each user login is welcome, but each user's user name is the same, you can not write a line of code for a user, which requires the use of formatted output

A. The first is the "+" connection, the output of the string and the variable directly connected to it;

B. The second is to use placeholders, placeholders are commonly used there are three,%s,%d and%f,%s is the following value is a string,%d is the following value must be an integer,%f followed by a decimal;

C. The third is the use of {} and the Fromat method, which three, the official recommendation is to use the Format method, not recommended to use the first, the first with a plus, will be in memory to open up a number of memory space, and the latter two is to open only a piece of memory space, using the following:

Name = input (' Please enter your name: ')
Sex = input (' Please enter your gender: ')
Print (' welcome you ' +name) #第一种用 + connection
Print (' welcome you ', name) #第二种用, connect
Print (' Welcome you to%s '%name) #一个变量的时候使用占位符
Print (' Welcome to%s ', your gender is%s '% (name,sex)) #多个变量的时候使用占位符
%d for the following variable is an integer
%f represents the decimal%.2f followed by a few decimals, rounding


age = Int (input (' Please enter an integer: '))
Grade = Float (input ("Please enter your score:"))
Print (' Input integer is%d, the score entered is%.2f '% (Age,grade))
Print (' Your score is%.2f '%grade)
Print (' Your age is {Your_age}, your score is '
' {your_grade} '. Format (Your_age=age,your_grade=grade))
Using placeholders is simpler if the parameters are relatively small
If the parameters are more than the case, the format is more intuitive with. Format

 

9. Partial Knowledge supplements

(1). Single-line comment, using #

(2). Comment Shortcut: ctrl+/

(3). Ctrl + D Quick Copy Line
(4). The value received by the. Input () function is all string types, and if you want to compare it with the int type, you must use INT () to convert the string to the int type for comparison.

(5). Type View variable types

(6). Print (1/2) Division

Print (1//2) #地板除, is automatic rounding, will not be rounded, directly erase the decimal part

Note: In Python2, this operation print (1/2), the result is not correct, because in the python2 int and int type operations will be automatically rounded, there is no problem in the Python3

First knowledge of Python

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.