程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] python3 basic syntax_ Java programmer self reference

編輯:Python

1. elegant Python

Take the last character of the string :

Python3 yes

 str[-1]

Java yes

str.charAt(str.length() - 1)

Drop the last character :

Python3 yes

str[:-1]

Java yes

str.substring(0, str.length() -1)

2. Python Summary of basic grammar

2.1 Basic variables

# Variable , No type , nothing ;
myVar = 1
myStr = "ab"
myStr2 = myStr * 2 # myStr2 become "abab"
# String concatenation and newline need to be indented
print("AAA and " +
    "BBB" +
    "CCC")
# perhaps
print("""
What's in it
And special characters
<>[email protected]#": It will output as is
Yeah!
""")
# if-else sentence
if ( name =="Tom" ):
    print("Yes")
elif ():
    print()
else:
    print()
# function
def myFunction():
    """ Show simple greetings """
    print("Hello!")
myFunction()

2.2 list 、 Tuples 、 Dictionaries

#---------- list --------------
# Value
myList[0]
myList[-2] # The next to last element
# Insert
list.append()
list.insert(0,newval)
# Delete
list.pop()
list.remove(val)
del list[3]
# The biggest and the smallest
min(list),max(list), sum(list)
# Generate list [1,4,9,16....]
squares = [values**2 for values in range(1,11)]
# List of analytical
range(1,3) # Left closed right away 1,2
numList[0:3] # 0,1,2 No return numList[3]
list[:4] , list[2:]
# Copy list
newList = origalList[:]
# Determine whether the list is empty
if myList:
    xxxx
# Check if it's in the list
'apple' in friut
'desk' not in friut
#for Loops are an effective way to traverse lists , But in for The list should not be modified in the loop , Otherwise, it will lead to Python It is difficult to track the elements .
# You should use while Loop through the list elements .
---------- Tuples ---------------
# Tuples Tuple, An unalterable list , parentheses
myTuple = (200,50)
print myTuple[0]   # Output 200
# Tuple variable list
list(myTuple)
--------==== Dictionaries =---------
dic = {'color' : 'green', 'num' : 5}
print( dic['color'] )
# Add key value pair
# The key must be immutable , You can use numbers , A string or tuple acts as , But you can't use lists
dic['newKey'] = 'newValue'
# add to to update
dic1 = {'color' : 'red', 'num':5}
dic2 = {'length' : '3'}
dic1.update(dic2)
#dic1 It becomes {'color' : 'red', 'num':5, 'length' : '3'}
# If it is a duplicate key value , Is to overwrite the update
# Delete key value pair
del dic['color']
dic.pop('color')
# Multiline key value pairs
mutiline = {
    'first' : 'Tom',
    'sec' : 'Jay',
}
# The last comma can be reserved , It is convenient to add elements next time
# Traverse
for k,v in myDic:
    print()
for k in myDic.keys():
    print()
for v in myDic.values():
    print()
if 'AAA' not in myDic.keys():
    print()
# Sort traversal
for name in sorted(myDic.keys()):
    print()
# Do not repeat output value
for myVal in set(myDic.values()):
    print(myVal)

2.3 loop

#------for in --------
for v in range(1,11):
# do sth...
#------ while --------
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)

2.4 function

#------------ function ------------------
def describe_pet(pet_name, animal_type='dog'):
    print(animal_type)
    #return animal_type
describe_pet()
# Typesetting , You can enter the left bracket in the function definition and press enter ,
# And press twice on the next line Tab key , Thus, the formal parameter list can be distinguished from the function body which is indented only one layer .
def function_name(
        parameter_0, parameter_1, parameter_2,
        parameter_3, parameter_4, parameter_5):
    function body...
# Keyword arguments
describe_pet(animal_type='hamster', pet_name='harry')
describe_pet(pet_name='harry', animal_type='hamster')
# Function parameters are passed in List copy , Prevent the list from being modified
function_name(list_name[:])
# Not fixed parameters , Encapsulate arguments as tuples
def make_pizza(*toppings):
""" Print all the ingredients that the customer ordered """
    print(toppings)
    make_pizza('pepperoni')
    make_pizza('mushrooms', 'green peppers', 'extra cheese')
# Use any number of keyword arguments
def build_profile(first, last, **user_info):
""" Create a dictionary , It contains everything we know about users """
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
    profile[key] = value
    return profile
user_profile = build_profile('albert', 'einstein',
                                   location='princeton',
                                   field='physics')
print(user_profile)

2.5  modular

#----------- modular ----------------
import myPyFile
myPyFile.myFun()
from myPyFile import myFun1, myFun2
myFun1()
myFun2()
from myPyFile import myFun1 as func
func()
import myPyFile as p
p.myFun()

2.6 class

#-----------------【 Class structure 】----------------------
class Dog():
    """ This is the file description """
    def __init__(self, name, age):
        """ Initialization property name and age"""
        self.name = name
        self.age = age
    
     def sit(self):
        """ Simulated squat """
        print(self.name.title() + " is now sitting.")
#----------------------------------------------------
    # The first letter of a class is capitalized , Hump nomenclature
# Be careful :class Dog() Inside () Parentheses can be left blank , When you do not inherit an object , Parentheses may be omitted
    # Method __init__() Is required and the first parameter must be self
    # Use self. Is instance variable
# Don't use self. It's a static variable
# __ Double underlined prefix decorates , Are private variables and private methods
    
#--------------------【 Inherit 】----------------------
class ElectricCar(Car):
    def __init__(self, make, model, year):
        super().__init()__(make, model, year)
        self.newAttr = 0
    
    def myNewFun():
        print("New Fun.")
#----------------------------------------------------
    # The function with the same name will override the function of the parent class
from car import Car
from car import Car, ElectricCar
import Car
    # First, import the standard library , And then import the module written by yourself 

 2.7 File read and write

#----------- file -------------
# Output file content
with open('filepath\my.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
# keyword with Close the file after you no longer need to access it .
# In this program , Notice that we call open() , But not called close() ;
# You can also call open() and close() To open and close files , but
# In doing so , If the program exists bug, Lead to close() Statement not executed , The file will not be closed .
# It seems insignificant , However, failure to properly close the file may result in data loss or damage . If you adjust too early in the program
# use close() , You will find that the file is closed when you need to use it ( cannot access ), This will lead to more mistakes .
# It's not always easy to determine the right time to close a file , But by using the structure shown earlier , can
# Give Way Python To make sure : You just open the file , And use it when you need it ,Python It will automatically turn it off when appropriate .
# because read() An empty string is returned when the end of the file is reached , When the empty string is displayed, it is a blank line .
# Need to use rstrip() Delete extra blank lines
# Read line by line
with open('filepath\my.txt') as file_object:
    for line in file_object:
    print(line.rstrip())
# Because in this document , There is an invisible line break at the end of each line , and print A newline character is added to the statement ,
# So there are two newlines at the end of each line : One from the file , The other came from print sentence .
# To eliminate these extra blank lines , Can be found in print Use in statement rstrip() 
# Copy the file to the list
filename = 'pi_digits.txt'
with open(filename) as file_object:
    lines = file_object.readlines()
for line in lines:
    print(line.rstrip())
#----------- Read multiple files ----------
filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
for filename in filenames:
    count_words(filename)
#---------- Writing documents ----------
# You need to add line breaks manually
filename = 'programming.txt'
with open(filename, 'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("I love creating new games.\n")

2.8  abnormal

try:
    answer = int(first_number) / int(second_number)
    print(  )
except ZeroDivisionError:
    print("Error: divide by zero!")
else:
    print( answer )

2.9  Store the data

# Save the data as json Files are stored on the hard disk
# Read from the hard disk json The content of the document
import json
numbers = [2,3,5,7]
filename = 'numbers.json'
with open(filename, 'w') as f_obj:
    json.dump(numbers, f_obj)
-----
import json
filename = 'numbers.json'
with open(filename) as f_obj:
    numbers = json.load(f_obj)
    print(numbers)

3 Code case

# Transfer list elements to a new list
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
while unconfirmed_users:
    current_user = unconfirmed_users.pop()
    print("Verifying user: " + current_user.title())
    confirmed_users.append(current_user)
# Deletes the specified element from the list
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
    pets.remove('cat')
print(pets)
# Python Interpret a non empty string as True
def get_formatted_name(first_name, last_name, middle_name=''):
    """ Return clean name """
    if middle_name:
         full_name = first_name + ' ' + middle_name + ' ' + last_name
    else:
        full_name = first_name + ' ' + last_name
    return full_name.title()
    musician = get_formatted_name('jimi', 'hendrix')
    print(musician)
    musician = get_formatted_name('john', 'hooker', 'lee')
    print(musician)
# Not fixed parameters , Encapsulate arguments as tuples
def make_pizza(*toppings):
""" Print all the ingredients that the customer ordered """
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

4. strange main

if __name__ == "__main__" How to understand ?

As long as you create a module ( One .py file ), This module has a built-in property name Generate , The name The value of depends on how the module is applied . Talk is talk , If you run the module directly , that __name__ == "__main__"; If you import A module , So module name The value of is usually the module filename .

This line tells you Python Interpreter , This script is the main entry of the program .

Reference resources :Python Medium if __name__ == "__main__" What exactly does it mean ?_ Big cousin's blog -CSDN Blog about Python For beginners , When you look at other people's code, you often see if __name__ == "__main__", At this time, my heart began to roast :“ It's definitely a fake , I don't write this sentence , The code doesn't run well ! When I first came across this line of code , I think so in my heart ! Make complaints about make complaints about Tucao , There must be a reason for existence . Now let's see what this code means , Because this sentence can help you to Python The understanding of modules goes to a higher level . Understand by example that as long as you create a ...https://blog.csdn.net/weixin_35684521/article/details/81396434


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved