Python full stack development, Day1, python development day1

Source: Internet
Author: User
Tags add numbers

Python full stack development, Day1, python development day1
1. Python Introduction

Birth and Application of python
The founder of python is Guido van rosum ). During the Christmas day of June 1989, Guido fansoum (Chinese name: Uncle Turtle) was determined to develop a new script interpreter in order to pass the time in Amsterdam, as an inheritance of the ABC language.

 

Currently, Python is mainly used in the following fields:

 

Ii. Computer Basics

Cpu:

  It is equivalent to a human brain, a computing and control center.
Velocity aircraft
Memory:Temporarily

Time Storage, providing CPU data.
High speed trains. High Cost: Power Failure disappears.
Hard Disk:

It is equivalent to a computer database that stores a large amount of data, files, and audio files.
Speed. Low Cost
Operating System:

Executors control all links. Windows, linux, mac...

 

Why python is popular
1. A large number of third-party Libraries
2. Diango

 

Iii. python history

Python is an excellent and widely used language that advocates elegance, clarity, and simplicity.
Python 2x and 3x were born in the same year. 2x was in October, and 3 was in December.
Python 2x: the source code is messy, there are many repeated codes, and the code is redundant.
Python 3x: source code specification, elegant, clear, and simple

Iv. Differences between python 2x and python 3x

1. The print method is different.
Python 3x print ('content ')
Python 2x print () or print 'content'

2. Different encoding methods
Python 3x default encoding: UTF-8
Python 2x default encoding: ascii only contains English letters, special characters, and numbers
Chinese is not supported
Solution:
Add in the header

# -*- coding: utf-8 -*-

3. Different inputs
Python 2x: raw_input ()
Python 3x: input ()

V. Classification of development languages

Explanatory type:When the program runs, one line of code is interpreted as binary and then run.
Advantages: Fast troubleshooting, high development efficiency, cross-platform
Disadvantage: relatively low execution efficiency
Typical: python,

Compilation type:Compile all the code into binary at a time and then run it.
Disadvantages: Slow troubleshooting, low development efficiency, and no cross-platform (operating system ).
Advantage: High execution efficiency
Typical: C

Python type

CPython default interpreter, converted to bytecode, and then converted to C language 010101...
IPython
PyPy converts all data into binary data at a time, resulting in high execution efficiency.
Jython compiles Python code into Java bytecode for execution
IronPython

 

Although the interpreter is different, the rules for writing python code are unified.

6. Run the first python Program

If you want windows to have two python environments at the same time, Python2.7 and Python3.5

Install python2.7 first

1. Download the installation package
Https://www.python.org/downloads/
2. Installation
Default installation path: C: \ python27

Select Add environment variable

 

Install python3.5 again

Select custom installation and check "add environment variable ".

The installation path is set to C: \ Python35.

Go to the C: \ Python27 directory.

Change python.exeto python2.exe.

Open windows Command Line Mode

The input python2 is version 2.7.

Input python version 3.5

Create a new test. py file with the following content:

Print ('hello, the World ')

Use command line

The path to my code is E: \ python_script \ day1.

Go to the directory and run the code

Execute with python2

Execution error

Because the default python2x encoding is ascii, Chinese characters are not supported.

Add

#-*-Coding: UTF-8 -*-

Run the command again.

 

If a problem occurs when python is executed after python is installed
You can uninstall and reinstall all python versions to ensure that the environment variables are deleted and the file suffix is displayed.

VII. Variables

Variable:Temporarily store the intermediate results of the program running in the memory for subsequent Code calls.

 

Rule for variable definition:

1. variables must be any combination of numbers, letters, and underscores.
2. The variable cannot start with a number.
3. Variables cannot be keywords in python. (No need to back up)
['And', 'as', 'assert ', 'Break', 'class', 'contine', 'def', 'del ', 'elif ', 'else', 'Got t', 'exec ', 'Finally', 'for ', 'from', 'global', 'if', 'import', 'in ', 'Is ', 'lambda', 'not ',' or ', 'pass', 'print', 'raise ', 'Return', 'try', 'while ', 'with', 'yield ']
4. variables must be descriptive.
5. The variable cannot be Chinese.
6. The variable cannot be too long.
7. official recommendations:

# Hump body AgeOfOldboy = 56 NumberOfStudents = 100 # underline age_of_oldboy = 56number_of_students = 80

 

It is generally recommended to use 2nd types, that is, the underline.

The following examples determine whether the variable name is valid.

W _ = 22e_a _ = 'too white 'e $ = 'fdsa'-_ = '15' 2G = 33 _ = 'old village Captain'

3, 4, and 5 rows of variables are invalid. Others are valid.

 

Assignment calculation
Calculate the right of the equal sign and assign the calculated value to the left

Python is an interpreted language, and the code is executed in one line.
The subsequent variables will overwrite the previous ones.

age1 = 12age2 = age1age3 = age2age2 = 6print(age1,age2,age3)

Execution output

12 6 12

View a chart

Age1 ~ Value 3, which is stored in the memory. When age2 is 6, the point of age2 value changes. The value is 6.

 

7. Constants
Constant refers to the constant amount, such as pai 141592653..., or the amount that will not be changed during the running of the program.
By default, all uppercase variables are called constants.

CITY_LIST = 'beijing'

 

11. Notes
Why are there comments?
Help you remember the previous code or help others understand your code
Not too many, just fine

Single line comment: # commented content
Multi-line comment: ''' commented content ''' or "commented content """

# Define a variable name1 = "taibai" ''' · Bi Moss deep lock long road Qing Dynasty: Wang Guowei Bi Moss deep lock long road. It is a moth error. Self-developed to destroy the bone to sell. What's more, it's really red. Keep yourself, but make it clear. Ken likes Zhu Yan. From now on. And from the flowers sitting in the mirror. '''

 

8. Initial Basic Data Types

Int (integer)

On a 32-bit machine, the number of digits of an integer is 32 bits and the value range is-2 ** 31 ~ 2 ** 31-1, I .e.-2147483648 ~ 2147483647

In a 64-bit system, the number of digits of an integer is 64-bit, and the value range is-2 ** 63 ~ 2 ** 63-1, that is,-9223372036854775808 ~ 9223372036854775807

Long (long integer)

Different from the C language, the Length Integer of Python does not specify the Bit Width. That is, Python does not limit the size of the Length Integer. However, due to limited machine memory, the length integer value we use cannot be infinitely large.

Note: Since Python2.2, if an integer overflows, Python will automatically convert the integer data to a long integer. Therefore, without the letter L after the long integer data, it will not cause serious consequences.
Note: In Python3, the long type is no longer available, and all are int long integers.

String type (str)

In Python, all characters with quotation marks are considered as strings!

msg = "My name is xiao,I'm 22 years old!"num = '12'

This will cause errors

msg = "My name is xiao,I"m 22 "years old!"

Double quotation marks (double quotation marks). Only two quotation marks are displayed, from left to right.


Generally three quotation marks are used in the case of multiple rows, with a line number character.
A row rarely uses three quotation marks

Shi = ''' Ma Han stepped into the mud, heading for tens of thousands of hoof. The ground is in the snow, and the fire is everywhere. The city is also full of nostalgia. That knows the old park month, also to iron Kansai. '''Print (shi)

Execution output

Ma Han stepped into the mud and shoes tens of thousands of trotters.
The ground is in the snow, and the fire is everywhere.
The city is also full of nostalgia.
That knows the old park month, also to iron Kansai.

 

Three single quotes with no value assignment are used for comments.

For example, the above Tang Poems "yu mei Bi Moss deep lock long road"


Strings can only be added and multiplied.

Add

N1 = 'Her name is 'n2 = 'nangong ziling 'n3 = n1 + n2print (n3)

Execution output

Her name is Nangong ziling.

 

Multiply

N1 = 'I love you! 'Print (n1 * 3)

Execution output

I love you! I love you! I love you!

9. boolean value (True, False)

The boolean type is simple. It has two values: True (True) and False (False). It is mainly determined by the recording logic.

print(1 > 2)

Execution output

False

 

Returns false.
Boolean values are not enclosed in quotation marks.

print(1 > 2 and 3 < 4 or 4 > 5)

Execution output

False

If the Boolean value is false, false is returned.

9. View data types

Use the type () method

n1 = 'nan'n2 = Falsen3 = 'False'print(type(n1))print(type(n2))print(type(n3))

Execution output

<Class 'str'>
<Class 'bool '>
<Class 'str'>

 

10. User Interaction input

All input data types are strings.

Name = input ('enter YOUR name: ') age = input ('enter your age:') holobby = input ('enter your hobbies :') s = 'My name is '+ name +' \ n my age is '+ age +' \ n my hobby is '+ hobbyprint (s)

Execution result

11. if statement

First Structure

If condition: Result

Example

if 3 > 2:    print(666)

Execution output

666

 

Second Structure

If condition: Result else: Result

Example

if 3 > 2:    print(666)else:    print(333)

Execution output

666

 

Third Structure

If condition 1: result 1 elif condition 2: result 2 elif Condition 3: result 3

Example

Choice = input ('Enter the number you guessed: ') if choice = '2': print ('invite you to dinner') elif choice = '6 ': print ('Week-free jobs') elif choice = '3': print ('play together ')

Execution output

 

4th types of Structures

If condition 1: result 1 elif condition 2: result 2 elif Condition 3: result 3 else: Result 4

Example

Choice = input ('Enter the number you guessed: ') if choice = '2': print ('invite you to dinner') elif choice = '6 ': print ('Week-free jobs') elif choice = '3': print ('play together ') else: print ('input error ')

Execution output

 

= Compare
= Value assignment

 

5th types of Structures

If condition: Result else: Result

As long as the requirement exists, if

Example

Age = int (input ('Guess my age: ') if True: if age = 18: print ('Congratulations, you guessed it') else: print ('This cannot be seen... ') else: print ('input error ')

Execution output

 

Strings cannot be compared in size and can only be compared to equal

Int ---> str (12) is converted to a string and str () is used ()
Str ---> int (12) can be converted to a number only when it is a string consisting of digits.

 

12. while Loop

Used to execute repeated code

While True: print ('itch ') print ('coolly') print ('decent') print ('social shake ')

Execution output

Itch
Liangliang
Decent
Social shake

...

 

While True indicates an infinite loop.

 

Another example

print(222)while True:    print(111)    print(333)print(444)

Execution output

222

111
333

111
333

....

 

444 will never be executed

 

Conditions for jumping out of the loop:
1. Change Conditions
2. breck

 

Flag


Print from 1 to 100

# Flag = True # Initial Value count = 1 while flag: # print the initial value for the first time. Print the auto-increment print (count) # loop once, auto-increment 1 count = count + 1 # When the value is 100, the loop ends if count = 100: # print 100 print (count) flag = False

Execution output

1

2

3

...

100

 

2nd writing methods

# Initial Value count = 1 while count <101: # print the initial value for the first time. Print the auto-increment print (count) # loop once, auto-increment 1 count = count + 1

Execution output, with the same effect as above

 

Breck: End Loop

 

while True:    print(111)    print(222)    break    print(333)

Execution output

111

222


In case of breck, terminate the loop and the following code is not executed

 

Continue: end this loop and continue the next loop.
Continue is equivalent to bottoming out

while True:    print(111)    print(222)    continue    print(333)

Execution output

111

222

....

 

333 will never be executed. Why? In the case of continue, the following code is not executed, and the next loop continues to be executed. Because the loop cannot be terminated, the last line of code will never be executed.

 

Use breck to print 1 to 100

# Initial Value count = 1 while True: # print the initial value for the first time. Print the auto-increment print (count) # loop once, auto-increment 1 count = count + 1 if count = 101: break execution output 1 to 100

Execution outputs 1 to 100

13. Related exercise questions

1. Use a while loop to input 1 2 3 4 5 6 8 9 10

2. Calculate the sum of all numbers from 1

3. Output all odd numbers in 1-100

4. Output all the even numbers in 1-100

5. Calculate the sum of all numbers of 1-2 + 3-4 + 5... 99.

6. User Login (three chances to try again)

 

Exercise analysis:

1. Use a while loop to input 1 2 3 4 5 6 8 9 10

Observed questions, found 1 ~ 10, missing a number 7

The idea is as follows:

1. Output 1 ~ 10

# Initial Value count = 0 while count <10: count = count + 1 print (count)

Execution output 1 ~ 10

2. In case of 7, do not execute print ().

If breck is used directly, the loop is terminated. At this time, we need to use continue.

The final code is as follows:

# Initial Value count = 0 while count <10: # auto-increment 1 count = count + 1 # When the value is 7, terminate the loop and continue the next loop if count = 7: continue print (count)

Execution output

1
2
3
4
5
6
8
9
10

 

2. Calculate the sum of all numbers from 1

The idea is as follows:

1. Output 1 ~ 100

# Initial Value count = 0 while count <100: # auto-increment 1 count = count + 1 print (count)

2. Define a sum variable the_sum. Each time you want to push forward and add numbers, just like eating a bean game.

# Initial Value count = 0 # total initial value the_sum = 0 while count <100: # auto increment 1 count = count + 1 the_sum = the_sum + count print (the_sum)

Execution output

1
3
6

...

5050

 

In the above code, I printed the result of each addition.

0 + 1 + 2 + 3 +... + 100

The calculation process is from left to right, 0 + 1 = 1, then 1 + 2 = 3, and 3 + 3 = 6 ....

Explain the Code Execution Process

The first time count = 0, the_sum = 0, execute to 7th rows, count = 1, then the_sum result 1, so output 1

The second count = 1 (because the whlie loop iterates). When the number of rows is 7th, count = 2 (1 + 1 = 2), the result of the_sum is 3. The value of the_sum for the first time is 1, so here it is 1 + 2 = 3

The third time, count = 2, when the execution reaches 7th rows, count = 3, the result of the_sum is 6 (3 + 3 = 6)

So the final result is 4950 + 100 = 5050

 

3. Output all odd numbers in 1-100

First, we will introduce how to evaluate the odd and even numbers.

Divide by numbers and 2, and get the remainder %
Equal to 1 is an odd number
0 is an even number.

 

Similar to question 2nd

1. Output 1 ~ 100

# Initial Value count = 0 while count <100: # auto-increment 1 count = count + 1 print (count)

Execution output 1 ~ 100

2. Use count and 2 to divide the remainder. If it is 1, the number is output; otherwise, no output is made.

# Initial Value count = 0 while count <100: # auto-increment 1 count = count + 1 # obtain the remainder, and 2 divide yushu = count % 2
#1 indicates an odd number if yushu = 1: print (count)

Execution output

1
3
5

...

99

 

4. Output all the even numbers in 1-100

The method is similar to question 3rd. Modify the remainder part.

# Initial Value count = 0 while count <100: # auto-increment 1 count = count + 1 # obtain the remainder, and 2 divide yushu = count % 2 # is 0 indicates an even number if yushu = 0: print (count)

Execution output

2
4
6

...

100

 

5. Calculate the sum of all numbers of 1-2 + 3-4 + 5... 99.

From this formula, we can find the rule.

Subtraction is performed for even numbers.

An addition is an odd number.

 

Ideas:

Based on the second question, the second is the sum of 1 to 100.

1. First paste the code for question 2nd

2. Make a slight change on this basis. The final code is as follows:

# Initial Value count = 0 # Calculate the initial value of the final_value = 0 while count <99: # auto-increment 1 count = count + 1 # obtain the remainder, and 2's division yushu = count % 2 #1 indicates an odd number if yushu = 1: # perform addition operation final_value = final_value + count print (final_value) # Even else: # perform the subtraction operation final_value = final_value-count print (final_value)

Execution output

1
-1
2

...

50

The final result is 50.

 

Note: The last digit here is 99, not 100, so it is while count <99

The above code prints the result of each calculation.

0 + 1-2 + 3-4... + 99

The calculation process is from left to right, 0 + 1 = 1, then 1-2 =-1, then-1 + 3 = 2 ....

Explain the Code Execution Process

Count = 0 for the first time, final_value = 0, and count = 1 for the execution to the 7th rows. Perform the remainder calculation, and the result is 1.

If is equal to 1, the result is true, so it is an odd number. Calculate the equation final_value + count, that is, 0 + 1 = 1,Output 1

The second time count = 1, final_value = 1, run to 7th rows, count = 2. Perform the remainder calculation and the result is 0.

If is equal to 1, the result is not true, so it is an even number. Calculate the equation final_value-count, that is, 1-2 =-1,Output-1

The third time count = 2, final_value =-1, run to the 7th row, count = 3. Perform the remainder calculation, and the result is 1.

If is equal to 1, the result is true, so it is an odd number. Calculate the equation final_value + count, that is,-1 + 3 = 2,Output 2

Therefore, the final result is-49 + 99 = 50.

 

6. User Login (three chances to try again)
Ideas

1. Perform simple login verification first

Username = input ('enter username: ') password = input ('enter password:') if username = "xiao" and password = '2016 ': print ('OK') else: print ('login failed more than three times, please try again later! ')

2. Use the while loop to execute the input box and try to log on infinitely.

While True: username = input ('enter your username: ') password = input ('enter your password:') if username = "xiao" and password = '000000 ': print ('OK') else: print ('login failed more than three times, please try again later! ')

3. Make a variable to record the number of Logon failures. The initial value is 0. If logon fails, the number of Logon failures is increased by 1. 3 times, directly end the program.

# Logins = 0 while True:
# Determine the number of logins if logins = 3: print ('logon failed more than three times. Please try again later! ') Break username = input ('enter your username:') password = input ('enter your password :')
# Determine the user name and password if username = "xiao" and password = '000000': print ('OK') else:
# Add 1 logins + = 1 print ('logon failed! ')

Execution output

 

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.