Quick Start

Kesa...大约 5 分钟

Indentation

Indentation refers to the spaces at the beginning of a code line.

Python uses indentation to indicate a block of code.

if 1 < 2:
    print("1 less than 2")

Variable

In Python, variables are created when you assign a value to it:

x = 5
y = "hello"

Name

Rules for Python variables:

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)
  • A variable name cannot be any of the Python keywordsopen in new window.

Multi words names

# Camel Case
varName = 1
# Pascal Case
VarName = 1
# Snake Case
var_name = 1

Assignment

# Many values to multiple variables
x, y = 1, 2
# One value to multiple variables
x = y = 1
# Unpack collection
fruits = ["apple", "banana", "cherry"]
x, y, z = fruits

Casting

If you want to specify the data type of a variable, this can be done with casting:

x = str(3) # "3"
y = int(3) # 3
z = float(3) # 3.0

Case-sensitive

Variable names are case-sensitive.

a = 4
A = 5 # A will not overwrite a

Global variables

Variables that are created outside of a function are known as global variables.

x = "hello"

def f():
    print(x)
    
f()

Use global keyword to change/create a global variable inside a function.

x = "hello"

def f():
    global x
    x = "world"

f()
print(x) // world

Comment

A comment starts with a #.

# This is a comment
print("hell")

Data type

Text Type:str
Numeric Types:int, float, complex
Sequence Types:list, tuple, range
Mapping Type:dict
Set Types:set, frozenset
Boolean Type:bool
Binary Types:bytes, bytearray, memoryview
None Type:NoneType

Get the type

Use type() function to get the data type of a variable:

x = 5
y = "Alice"
print(type(x)) # int
print(type(y)) # str

Number

There are three numeric types in Python:

  • int
  • float
  • complex
x = 1 # int
y = 2.0 # float
z = 1j # complex

String

Strings in python are surrounded by either single quotes or double quotes.

x = "hello"
y = 'world'

Use three quotes to assign a multiline string to a string.

a = """
A
B
C
"""

Iterate string

for c in "apple":
    print(c)

String length

Use len() to get the length of string.

a = "hello"
print(len(a))

Check string

To check if a certain phrase or character is present in a string by using the keyword in:

s = "Hello world"
print("wo" in s) # True
print("wa" not in s) # True

Slicing

b = "hello"
print(b[1:3]) # [1, 3), el
print(b[:2]) # [0, 2), he
print(b[3:]) # [3, 5), lo
print(b[-3: -1]) # ll  

Format

The format() method takes the passed arguments, format them, and places them in the string where the placeholders {} are:

age = 16
s = "Alice is {}"
print(s.format(age))

s1, s2 = "A", "B"
txt = "{1} and {0}"
print(txt.format(s1, s2)) # B and A

Escape characters

CodeResult
'Single Quote
\Backslash
\nNew Line
\rCarriage Return
\tTab
\bBackspace
\fForm Feed
\oooOctal value
\xhhHex value

Boolean

Boolean represents one of two values: True or False.

Evaluate values

The bool() function allows you to evaluate any value:

  • Any string is True, except empty strings.
  • Any number is True, except 0.
  • Any list, tuple, set, and dictionary are True, except empty ones.

Operator

Arithmetic

OperatorNameExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
**Exponentiationx ** y
//Floor divisionx // y

Comparison

OperatorNameExample
==Equalx == y
!=Not equalx != y
>Greater thanx > y
<Less thanx < y
>=Greater than or equal tox >= y
<=Less than or equal tox <= y

Logical

OperatorDescriptionExample
andReturns True if both statements are truex < 5 and x < 10
orReturns True if one of the statements is truex < 5 or x < 4
notReverse the result, returns False if the result is truenot(x < 5 and x < 10)

Identity

OperatorDescriptionExample
isReturns True if both variables are the same objectx is y
is notReturns True if both variables are not the same objectx is not y

Membership

OperatorDescriptionExample
inReturns True if a sequence with the specified value is present in the objectx in y
not inReturns True if a sequence with the specified value is not present in the objectx not in y

Bitwise

OperatorNameDescriptionExample
&ANDSets each bit to 1 if both bits are 1x & y
|ORSets each bit to 1 if one of two bits is 1x | y
^XORSets each bit to 1 if only one of two bits is 1x ^ y
~NOTInverts all the bits~x
<<Zero fill left shiftShift left by pushing zeros in from the right and let the leftmost bits fall offx << 2
>>Signed right shiftShift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall offx >> 2

List

List are used to store multiple items in a single variable.

# Create list
nums = [1, 2, 3]
# Get length 
len(nums) # 3
# List can contain different tpyes
nums = [1, True, "A"]
# Crreat list by using list()
nums = list((1, 2, 3))
# Access item in list
nums[0] # 1
nums[-1] # 3
# Return new list by giving range
nums1 = nums[1:2] # [1, 2), [2]

Check if item exists

Use in to check if item exists:

nums = [1, 2, 3]
print(2 in nums) # True

Insert item

nums = [1, 2, 3]
nums.insert(1, 4) # [1, 4, 2, 3]

Append item

nums = [1, 2, 3]
nums.append(4) # [1, 2, 3, 4]

Extend list

nums = [1, 2, 3]
nums2 = [4, 5]
nums.extend(nums2) # [1, 2, 3, 4, 5]

Iterate list

nums = [1, 2, 3]

# Use in keyword
for n in nums:
    print(n)

# iterate through index
for i in range(len(nums)):
    print(nums[i])
    
# List comprehension
[print(n) for n in nums]

List comprehension

newlist = [expression for item in iterable if condition == True]
newlist = [x for x in fruits if x != "apple"]

Set

Sets are used to store multiple items in a single variable.

Items in the set are unordered, unchangeable, and do not allow duplicate values.

numSet = {1, 2, 3}
# create set by using set()
numset = set((1, 2, 3))

Access item

You cannot access items in a set by index.

nums = {1, 2, 3}
for n in nums:
    print(x)
    
# Check if item exists
4 in nums # False

Dictionary

Dictionary is used to store data values in key:value pairs.

m = {
    "A": 1,
    "B": 2,
    "C": 3
} 

# Get dictionary item
print(m["A"]) # 1
print(m.get("A")) # 1
# Get length of dictionary
print(len(m)) # 3
# Get all keys
print(m.keys())
# Get all values
print(m.values)
# Get all entries
print(m.items())
# Check if key exists
print("A" in m) # True

# Add items
m["D"] = 4
m.update({"E": 5}) 

# Delte items
m.pop("A")
del m["B"]
m.clear() # empty dict
del m # delete dict

if-else

if cond:
    # code
elif cond:
    # code
else:
    # code

Loop

while

while cond:
    # code
else:
    # code

for

nums = [1, 2, 3]
for n in nums:
    print(n)
else:
    # code
    
# pass
for x in range(6):
    pass

Function

# create functions
def functionName(paramter_list):
    # code
    
functionName(parameters)   

# arbitrary arguments
def f(*param):
    # code
    
# arbitrary keyword args
def f(**param):
    print("My naem is " + param["name"])
    
f(name = "Alice")

# default parameter value
def f(name = "A"):
    print("I am " + name)

Lambda

A lambda function is a small anonymous function.

A lambda function can take any number of arguments, but can only have one expression.

lambda args: exp
x = lambda a: a + 1
print(x(5)) # 6

Class

__init_

__init__ function is always executed when the class is being initiated.

class Person:
    def __int__(self, name, age):
        self.name = name
        self.age = age

p1 = Person("Alice", 16)
print(p1.name) # Alice

__str__

The __str_ function controls what should be returned when the class object is represented as a string.

class Person:
    def __init__(slef, name, age):
        self.name = name
        self.age = age
       
    def __str__(self):
        return self.name + " " + str(self.age)

p1 = Person("Alice", 16)

Methods

class Person:
    def __init__(self, name, age):
        # ...
        
    def method1(self):
        print("My name is " + self.name)
        
       
p = Person("Alice", 16)
p.method1()

Inheritance

class Person:
    # ...

class Student(Person):
    # ...

Module

Create a module

# mymod.py
def greeting(name):
    print("hello " + name)

# main.py
import mymod as mm

mm.greeting("Alice")

Import only parts from a module.

from mymod import greeting
# ...

PIP

PIP is a package manager for Python packages.

# install 
$ pip install pkg_name
# uninstall 
$ pip uninstall pkg_name
# list
$ pip list

Try-except

The try block lets you test a block of code for errors.

The except block lets you handle the error.

The else block lets you execute code when there is no error.

The finally block lets you execute code, regardless of the result of the try- and except blocks.

try:
    # code
except NamedError:
    # hanle error
except:
    # ...
else:
    # no error
finally:
    # ... 

Throw exception

x = -1

if x < 0:
    raise Exception("...")

Reference

  1. https://www.w3schools.com/python/default.aspopen in new window
上次编辑于:
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.2