python基础学习笔记:入门、易错点与查缺补漏

Fallibility

  • range(n) is from 0 through n-1
  • A dict and list can be nested in both a dict and a list

Be careful when calling the elemens of nested dict and list

  • A non-empty string would be regarded as True
  • The elements of one list can be various types
  • Defining more than one functions in only one .py file in jupyter lab would generate some unknown errors
  • print() would automatically add a ‘\n’ at the end of every line
  • x=(y=1):ERROR
  • a,b=c,d or a,b=input(),input():RIGHT
test1=["hello" ,"world"]
test2=[1 ,2]
test=[test1 ,test2]

for i in test:
    for j in i:
        print(j)
hello
world
1
2

Frequently-used operations

  • range(a ,b): To generate from a through b-1

range(n): To generate from 0 throuth n-1

  • append()(such as test.append() where test is a dictionary or a list)

  • pop(): test.pop() returns the last element and deletes it

  • title(): test.title() returns the capitalized test

It’s one of the attributes of string ,not list

  • remove(): test.remove(st) removes the st in the test

  • test[a:b]: The elements from the ath through the (b-1)th in the test

test[:n]: The elements from the zeroth through the (n-1)th in the test
Slice

  • str(): Return the string form of something meanwhile the original one has not been changed
  • len(): Return the length of a string
  • There are keywords continue and break which are the same as the ones in c
test=[1 ,2]
test.append('c')
st="abcd"

for i in test:
    print(i)
    
print(st.title())   

test.remove(2)
print(test) # There're some differences between two ways of printing list(dict)
print(len(st))
1
2
c
Abcd
[1, 'c']
4

Hereinafter showing frequently-used operations in dictionary

test={'a':'a1' ,'b':'b1'}#dict

for item in test.items():
    print(item)
for key,value in test.items():
    print(key)
for key in test.keys():
    print(key)
for value in test.values():
    print(value)
    
print(test['a'])    
('a', 'a1')
('b', 'b1')
a
b
a
b
a1
b1
a1
# How to input
# Using input() to input and using int() to convert a string to a num
# Every item inputted would be regarded as a string
test=int(input("hello world"))# The phrase in input() is a comment
print(test)
test > 1
hello world -1
-1
False

Methods of operating functions

#Calling functions and default arguments
def test(a ,b=1):#The default arguments have to be put at the end of arguments list
    print(a+b)
    
a=3
b=4
test(a ,b)#Pay attention to the order_Position arguments
test(b=b ,a=a)#/Can change the order of arguments_Keyword arguments
test(3)#Using default arguments
7
7
4
#Creating a copy of object delivered to function
def test(a ,b):
    while a:
        b.append(a.pop())
    
    for item in a:
        print(item)
    for item in b:
        print(item)
        
a=["hello" ,"world"]
b=[]
test(a ,b)
test(a[:] ,b)
#Using slice to create a copy of a, which would be transmitted into the function
#And the original one wouldn't be changed
#pop:从右往左pop
#append:从左往右append
world
hello
world
hello
a=[]

a.append("a")
a.append("b")
a.append(3)

for item in a:
    print(item)
a
b
3
def test(a):
    while a:
        a.pop()
        
a=[1,2]
test(a)
print(a)

a=[1,2]
test(a[:])
print(a)

# If we dont use slice, transferring the original value into function will change the original value
# if some changes have taken place in the function (传引用)
# Using slice as transferring a copy of the original value that dont change the original value (传值)
[]
[1, 2]
#Delivering unknown-number arguments to functions

def test(*t):
    for item in t:
        print(item)
        
test(1 ,2)
test(1 ,2 ,3)
###############################################
def test1(int_num ,*string):
    for item in string:
        print(str(item)+str(int_num))#concatenate
    
test1(1 ,"test1" ,"test2" ,3)# 3 will be regarded as a char
"""Regarding it as a pointer of a list(列表)"""
###############################################
def test2(first ,second ,**info):
    profile={}
    profile['first']=first
    profile['second']=second
    profile['age']=info['age']
    profile['sex']=info['sex']
    
    print(profile)
    
test2('q' ,'w' ,age=100 ,sex='male')
"""Regarding it as a pointer of a dict(字典)"""

#Unknown-numbered arguments have to be put at the end of the arguments list
1
2
1
2
3
test11
test21
31
{'first': 'q', 'second': 'w', 'age': 100, 'sex': 'male'}





'Regarding it as a pointer of a dict(字典)'

Methods of importing modules

import test # Assume that the test.py has been defined which has some functions
test.test1("hello" ,"world")

import test as t # Use as to specify a alias for a module
t.test1("hello" ,"world")

###########################################
# They are the same as the ways of importing a class from a module
from test import test1 ,test2
test1("hello" ,"world")
from test import test1 as ts ,test2 as ts2 # Use as to specify a alias for a function
ts("hello" ,"world")
from test import * # Use * to import all functions in the module
test1("hello" ,"world")

Class

oop The class in python is similar to the one in c++

  • Python supports OOP, the operations and the notions of which is similart to the one in c++
class Test():
    
    """Conductor"""
    """Can without conductor"""
    """self is a reference of object initialized by the class
       Can regard self as pointer 'this' in c++, which has to be explicitly defined and put before
       all arguments in conductor in python"""
    def __init__(self ,num):
        self.num=num # self.num is a attribute of the class
    def pr(self):
        print(self.num)
        
test=Test(4) # Don't need to transfer the actual parameter of self
test.pr()
4
class Test():
    def __init__(self):
        self.a=10
    def pr(self):
        print(self.a)
        
test=Test()
test.pr()
10

Class.Inherit/Derive and Override

# Declaring superclass must be put before declaring subclass
class Test1():
    def __init__(self ,num1):
        self.num1=num1
    def pr(self):
        print(self.num1)
        
class Test2(Test1): # Derived from Test
    def __init__(self ,num1 ,num2):
        super().__init__(num1)
        self.num2=num2
        # super() helps to connect the superclass and the subclass
        # Can regard super() as a function returning the superclass of the current class
        # When calling super().__init__() ,don't need to transfer self as a actual parameter
        # Need to use super().__init__() to initialize superclass if we use attributes in superclass
        
    def pr(self):
        print(str(self.num2)+"test")
        print(str(self.num1)+"test")
        # Override pr()
        
test=Test2(2 ,3)
# Test2() calls conductor in Test2 ,which calls conductor in superclass Test1
test.pr()
        
3test
2test

File operations

  • Python would automatically decide when to close the file or we can use close() to manually close the file
  • If the file is in the subfolder of the current folder, we can use relative path. Otherwise we have to use absolute path

Never mind if the file is in the currenct folder, that is, the same folder as the program

  • Python would regard any data read from files as strings
# Read from the file
with open('test.txt') as file_object: 
# Python would throw a exception if it is not existed
# with open('folder_name/test.txt') as file_object
# with open('test.txt' ,'r') as file_object
    content=file_object.read()
    print(content.rstrip())
    
    """There would be a blank line being a null string under the outputs
       if without rstrip(), which means that the return value of read() is still a object 
       instead of a simple string"""
    """read() would return a null string when it reaches the end of the file"""
    """rstrip() is used to clear the whitespaces and the '\n's at the end of the string"""
    
    for line in file_object:
        print(line.rstrip())
    """Read file line by line"""
    for char in content:
        print(char.rstrip())
    """Read file char by char"""
# QUESTION:
# After 'content=file_object.read()' ,the block that is reading file line by line has no output
# but just a blank line.
# Is there a pointer in the file which points to the end of the file after 'read()' operation?

    lines=file_object.readlines()
    """readlines() read every line, stored in a list named lines, in file_object
       The '\n' would also be stored in the list"""
    temp=''
    for line in lines:
        temp+=line.strip()
    """rstrip() can delete the blankspaces and the '\n's at the end of the line
       strip() can delete the blankspaces and the '\n's in the line"""
    print(temp)
    
112233
445566
# Write into the file
# Cannot run correctly on the jupyter lab
with open('test.txt' ,'w') as file_object:
# Python would create a new file named 'test.txt' if it is not existed
# and clear all the data if it has been existed
    file_object.write("hello world\n")
"""'w': only write
   'r': only read
   'a': only append
   'r+': read and write"""
    

Exceptions

try:
    print(5/0)
except ZeroDivisionError:
    print("error")
# The name of excetion cannot be user-defined   
# ZeroDivisionError is an object
try:
    print(5/0)
except ZeroDivisionError:
    pass # If an exceprtion occurs, it would be passed and the program would not be interrupted
    
a=int(input("input the first one\n"))
b=int(input("input the second one\n"))

try:
    ans=a/b
except ZeroDivisionError:
    print("error")
else:
    print(ans)
error


input the first one
 3
input the second one
 2


1.5
with open('test.txt') as file_object:
    test=file_object.read()
    words=test.split()
    print(words)
    # split() splits words in accordance to blanks and store them into a list
    
    length=len(words) # Calculate the number of members in the list
    print(length)
    """This method can be used to calculate the number of words in a file like a novel"""
['hello', 'world']
2

JSON

  • JSON is a data exchange format and .json is a unique type of file which can stores the data of python(and a lot of other computer languages)in orignal version instead of string version
  • It can be used in the conditions where we need to store the settings of a project or visual data in files to avoid losing data after closing the terminal
  • It is also convenient to exchange data in original version by .json
import json

test=[1 ,2 ,3 ,4 ,5]

with open('test.json' ,'w') as file_object:
    json.dump(test ,file_object)
    
with open('test.json') as file_object:
    test=json.load(file_object)
    
print(test)    
[1, 2, 3, 4, 5]
# Example of json, file operations and exceptions
import json

try:
    with open('user_name.json') as f_ob:
            username=json.load(f_ob)    
except FileNotFoundError:
    username=input("Name?\n")
    
    with open('user_name.json' ,'w') as f_ob:
        json.dump(username ,f_ob)
else:
    print(username)

# It's a good habit to use try-except-else to examine if there is a exception
# thrown by open() when it is failed to open a file
Jack

TestProgram

Jupyter doesn’t support test now

# The assert methods in 'unittest.TestCase'
""" 
    assertEqual(a ,b):judge if a == b
    assertNotEqual(a ,b)
    assertTrue(x):judge if x == True
    assertFalse(x)
    assertIn(item ,list):judge if item in th list
    assertNotIn(item ,list)
"""
# Other methods in 'unittest.TestCase'
"""
    setUp():to set up some variables or attributes which woule be used in test functions later
    setUp() would be executed ahead of test functions
"""
# Standard format for testing functions
# The essence of testing classes is testing methods
import unittest
from test import test

class TestClass(unittest.TestCase): # Inherit superclass 'unittest.TestCase'
    def test_add_num(self):
# unittest.main() would automatically run every test function beginning with 'test' in the test class        
        sum=test(3 ,4)
        self.assertEqual(sum ,7)
# self.assertEqual() would judge if the return value of test() equals to the second parameter
# in the self.assertEqual()
unittest.main()

""" 
    Notion:
    1. Use a class inheriting unittest.TestCase to store every test functions
    2. Each test function examine one tested function by executing a procedure with the tested function
    3. Examine the results
"""    
# Use setUp()
import unittest
from test import test

class TestClass(unittest.TestCase): # Inherit superclass 'unittest.TestCase'
    def setUp(self):
    	self.a,self.b,self.c=3,4,7
# Must be attributes or cannot be used
    def test_add_num(self):
# unittest.main() would run every test function beginning with 'test' in the test class        
        sum=test(self.a ,self.b)
        self.assertEqual(sum ,self.c)
          
unittest.main()
c='a','b'
d=['3' ,4]
print(c)
print(d)
('a', 'b')
['3', 4]

Some tips

print("hello" ,end=" ")#修改结尾字符 可避免换行
print("world")
hello world
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值