Home >Backend Development >Python Tutorial >Python learning basics: How to use One

Python learning basics: How to use One

高洛峰
高洛峰Original
2017-03-26 18:21:581727browse

1. Install Python34

Windows

Download the installation package from the Python official website (https://www.python.org/downloads/) and install it.

The default installation path of Python is: C:\Python34

Configure environment variables: [right-click computer]--"[Properties]--"[Advanced system settings]--"[Advanced ]--》[Environment variables]--》[Find the line with the variable name Path in the second content box, double-click] --> [The Python installation directory is appended to the variable value, separated by;]

2. The first Python program

1. Execute in the interactive interface: Directly call the interactive interface that comes with python to run the code (for temporary debugging)

Python learning basics: How to use One

2. Write the program in the file and execute it

(1) Install PyCharm(http://www.jetbrains.com/pycharm/download/)

(2 ) Create a new project and Python File

(3) Write the code

Print("Hello World!")

(4) Run

3. Define variables

Variables in the program Used for storage and recall. A variable is equivalent to a container that stores data and stores the data in memory. (The difference between memory and hard disk: memory is faster than hard disk, memory is temporary storage, and hard disk is permanent storage)

#!/user/bin/env python# 
-*-coding:utf-8 -*-
user_name = "Grace" #申明一个字符串变量
age = 21        #申明一个数字变量

Rules for variable definition:
1. Single quotes, double quotes, and triple quotes are all characters String
2. Variables should have actual meaning and make people understand more clearly
3. Variable names can only be any combination of letters, numbers, and underscores
4. The first character of a variable name cannot be a number
5. Keywords cannot be used to declare variable names

4. Character encoding

Byte: 8 binary bits constitute 1 "Byte", which is storage space the basic unit of measurement. 1 byte can store 1 English letter or half a Chinese character. In other words, 1 Chinese character occupies 2 bytes of storage space.

1KB=1024B 1MB=1024KB 1GB=1024MB 1TB=1024GB

1. ASCII (American Standard Code for Information Interchange, American Standard Information Interchange Code) is a set of computer codes based on Latin letters System, mainly used to display modern English and other Western European languages,
It can only be represented by up to 8 bits (one byte), that is: 2**8 = 256-1, so the ASCII code can only be represented at most 255 symbols.
2. Obviously ASCII code cannot represent all the characters and symbols in the world. Therefore, a new encoding that can represent all characters and symbols is needed, namely: Unicode
Unicode (Unicode, Universal Code code, single code) is a character encoding used on computers. Unicode was created to solve the limitations of traditional character encoding schemes. It sets a unified and unique binary encoding for each character in each language, stipulating that all characters and symbols must be at least 16 bits to represent (2 bytes), that is: 2 **16 = 65536,
Note: What is said here is at least 2 bytes, maybe more
3. UTF-8, which is for Unicode For encoding compression and optimization, he no longer uses at least 2 bytes, but classifies all characters and symbols: the content in the ASCII code is saved in 1 byte, and the European characters are saved in 2 bytes.
East Asian characters are stored in 3 bytes...
The version of Python 2.0 defaults to ascill, and you can specify a character set:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
  
print "你好,世界"
5. Comments

Single line gaze: # Be Comment content
Multi-line comments:'''' Commented content'''' ('''' represents a multi-line string. Multi-line strings are placed directly in Python and will be ignored by Python)
6. Formatting String
1. In Python3, input receives all strings by default

2. %s can pass in a string or an integer type, and %d can only pass in an integer type. %f floating point type

3. Three single quotes (''') can be used for multi-line strings, define variables as multi-line strings, and output multi-line strings

name = input("input your name:")
age = int(input("input your age:")) #convert str to int
job = input("input your job:")
message='''
Information of user %s:
_______________________
name: %s
age:  %f
job:  %s
---------End-----------
''' %(name,name,age,job)
print(message)
7 , expression if... else

Use a login verification to illustrate:

rightName = "tt"
password = "wpl"
 
userName = input("Please enter your name:")
userPassword = input("Please enter your password:")
 
#Python 是一个强制缩进语言,通过缩进来控制从属关系
if userName == rightName and userPassword == password:
    print("Welcome login ...")
else:
    print("your user name or user password is invalid")
Use a program to guess age:

Requirements:
If you keep guessing wrong A total of 8 guesses can be made.
Every time 3 wrong guesses are made, the user will be prompted whether to continue. The user enters Y to continue. Enter any other characters to exit the program.
The program ends if the user guesses correctly.

age = 22
count = 0
for i in range(10):
    print("-->counter",count)
    if count         guess_age = int( input("Please input age:") )
        if guess_age == age:
            print("You are right")
            break
        elif guess_age > age:
            print("Think smaller!")
        else:
            print("Think bigger...")
        count += 1
    else:
        user_answer = input("Do you want countine:")
        if user_answer == "Y":
            count = 0
        else:
            print("bye")
            break
            
该段代码最多进行了10次循环,有两次循环是询问用户是否继续猜,在用户回答为Y时,并没有在该次循环让用户猜年龄。
而是进入下一个循环后才开始猜年龄。

九、模块初识

import sys
print(sys.path)  #打印python的环境变量地址
 
导入sys模块, 调用该模块中的path数据。
注意: 标准库一般放在 <python>\\lib
    第三方库一般放在 <python>\\lib\\site-packages (自己写的python文件放到该目录,编写其它模块时就可以导入该文件,并调用方法与数据)
 
os模块的几个方法:
import os
os.system("dir") #执行系统命令,只打印出命令结果,不会保存(当前路径下的目录)
 
cmd_res = os.popen("dir") #执行命令并把结果保存到一个文件中
print(cmd_res.read()) #读取这个文件并打印出结果
 
os.mkdir("other_dir") #在当前路径下创建一个新目录</python></python>

The above is the detailed content of Python learning basics: How to use One. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn