search
HomeBackend DevelopmentPython TutorialPython learning basics: How to use One

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
How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

What is NumPy, and why is it important for numerical computing in Python?What is NumPy, and why is it important for numerical computing in Python?May 03, 2025 am 12:03 AM

NumPyisessentialfornumericalcomputinginPythonduetoitsspeed,memoryefficiency,andcomprehensivemathematicalfunctions.1)It'sfastbecauseitperformsoperationsinC.2)NumPyarraysaremorememory-efficientthanPythonlists.3)Itoffersawiderangeofmathematicaloperation

Discuss the concept of 'contiguous memory allocation' and its importance for arrays.Discuss the concept of 'contiguous memory allocation' and its importance for arrays.May 03, 2025 am 12:01 AM

Contiguousmemoryallocationiscrucialforarraysbecauseitallowsforefficientandfastelementaccess.1)Itenablesconstanttimeaccess,O(1),duetodirectaddresscalculation.2)Itimprovescacheefficiencybyallowingmultipleelementfetchespercacheline.3)Itsimplifiesmemorym

How do you slice a Python list?How do you slice a Python list?May 02, 2025 am 12:14 AM

SlicingaPythonlistisdoneusingthesyntaxlist[start:stop:step].Here'showitworks:1)Startistheindexofthefirstelementtoinclude.2)Stopistheindexofthefirstelementtoexclude.3)Stepistheincrementbetweenelements.It'susefulforextractingportionsoflistsandcanuseneg

What are some common operations that can be performed on NumPy arrays?What are some common operations that can be performed on NumPy arrays?May 02, 2025 am 12:09 AM

NumPyallowsforvariousoperationsonarrays:1)Basicarithmeticlikeaddition,subtraction,multiplication,anddivision;2)Advancedoperationssuchasmatrixmultiplication;3)Element-wiseoperationswithoutexplicitloops;4)Arrayindexingandslicingfordatamanipulation;5)Ag

How are arrays used in data analysis with Python?How are arrays used in data analysis with Python?May 02, 2025 am 12:09 AM

ArraysinPython,particularlythroughNumPyandPandas,areessentialfordataanalysis,offeringspeedandefficiency.1)NumPyarraysenableefficienthandlingoflargedatasetsandcomplexoperationslikemovingaverages.2)PandasextendsNumPy'scapabilitieswithDataFramesforstruc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version