Catalog
  1. 1. Print(“hello world”)
  2. 2. Grammer
  3. 3. Syntax
  4. 4. Semantics
    1. 4.1. Variable, Names, and Objects
      1. 4.1.1. Object
      2. 4.1.2. Type
      3. 4.1.3. Variable
  5. 5. Variable and Value
  6. 6. Assign New Value, Mutable
  7. 7. Data Type
    1. 7.1. Integers
      1. 7.1.1. How Big Is an int?
    2. 7.2. Float
      1. 7.2.1. Tip:You may use type(variable) to get the type of an variable. For example, type(1) will return int.
      2. 7.2.2. Math Functions
    3. 7.3. Boolean
    4. 7.4. Strings
      1. 7.4.1. Type Conversions
      2. 7.4.2. Combine & Duplicate
      3. 7.4.3. Extract &Slice
      4. 7.4.4. Split & Join
      5. 7.4.5. Substitue
      6. 7.4.6. Layout
      7. 7.4.7. Other useful tools
      8. 7.4.8. in and out~~
      9. 7.4.9. New Style in Python 3.6
      10. 7.4.10. python基础瞎写着玩
      11. 7.4.11. 字符串处理
        1. 7.4.11.1. 切片
    5. 7.5. 小白容易踩的坑
Python First Day

anaconda中python版本的切换,我这里因为要用到3.6版本,当前版本为3.7
avator

conda creativate –name newpy36 python=3.6 # 安装python3.6
安装对应python的虚拟环境的时候会自动安装一些依赖库,输入y
安装完成后通过activate 进行激活
activate newpy36
通过deactivate 进行脱出
deactivate

Print(“hello world”)

1
print("Hello World! 你好,世界! Hola mundo!");

Hello World! 你好,世界! Hola mundo!

1
2
print("Hello World!")
print("Hello Again")

Hello World!
Hello Again

1
2
3
4
print("This is the 3rd line, \n",
"and this is also the 3rd line.")
This is the 3rd line,
and this is also the 3rd line.

1
2
print("This is the 3rd line, \
and this is also the 3rd line.")

This is the 3rd line, and this is also the 3rd line.

Grammer

Expression -> Expression Operator Expression

Expression -> Number

Operator -> +, - , * , /

Number -> 0,1,2,3,4

1
2
print(4-5)
-1
1
print(8 + )

File ““, line 1
print(8 + )
^
SyntaxError: invalid syntax

刘翔能跑多快?110米跨栏,13秒, 速度= 100米/13秒

1
110/12.97

8.481110254433307

Syntax

PEP8
naming
public int numberOfCars = 34; # Java
const numberOfCars = 34; # JavaScript

1
number_of_cars = 34 # Python
1
2
3
4
5
# there is no { } and there is no ;
x = 6
if x < 7:
print(x)

6

1
2
if x < 7:
print("x is smaller than 7")

x is smaller than 7

Semantics

1
2
3
4
5
x = 8
if x < 7:
print("x is smaller than 7")
​ print("x is bigger than 7")

Variable, Names, and Objects

In Python, everything is implemented as an object.

Object

We will come back to what an object is later when we talk about Object Oriented Programming. For now, you may just think an object as a box that contains a piece of data.

Type

Type defines what operations can be done on an object (data). For example, we know that numbers can be added together.

Variable

Variable and Value

变量 和 值

1
2
3
4
5
speed_of_liuxiang=110/12.97
distance= 1000
time = distance/speed_of_liuxiang
print(time)
print(time/60)

117.9090909090909
1.965151515151515

Assign New Value, Mutable

This is how we define variables in Python.
In Python, variables are just names. Assignment does not copy a value; it just attaches a name to the object that contains the data. The name is a reference to a thing rather than the thing itself. Think of a name as a sticky note.

1
2
3
4
speed_of_joshua=110/10
time = distance/speed_of_joshua
print(time)

90.9090909090909

1
2
3
time = time-10
print(time)
80.9090909090909

Data Type

In this notebook, you will learn the concept of Variabels, Names and Object. And also 4 built-in data types in Python:

  • Integer (int)
  • Float (float)
  • Boolean (bool)
  • String (str)

Integers

1
123

123

1
05

File ““, line 1
05
^
SyntaxError: invalid token

1
123,456,789

(123, 456, 789)

###Integer Operations
Tips:
You may use print(variable) to print the value of variables in Python3, no matter what type of vairbale it is. Also, print(var1, var2) will print out the value of var1 and var2, separated by a white space.
In REPL, the result of the last operations will be printed out automatically

1
1 + 2

3

1
2
3
a = 5
a += 2
a

7

1
2
3
a = 5
a = a - 3
a

1
9 // 5

1

1
9 % 5

4
优先权

1
2 + 3 * 4

14

How Big Is an int?

In Python2, the size of an int was limited to 32 bits, which is enough to store an integer from -2,147,483,648 to 2,147,483,647. A long can store 64 bits. Integers larger than the range will cause Integer Overflow.

In case you wonder where does this range come from. Computers store numbers in its binary format, 32 bits means we have 32 binary bits to store a number. That’s why we can only store 232 different integers. Since we want to store both positive numbers and negative numbers at the same time, each side will get 231 numbers, which is 2,147,483,648.

In Python3, an int can handle any integer no matter how large it is without causing overflow.

1
2
a = 10**20
a

100000000000000000000

1
a*a

10000000000000000000000000000000000000000

1
10

10

1
0b10

2

1
0o10

8

1
0x10

16

Float

1
2
  a = 98.5
type(a)

float

Tip:You may use type(variable) to get the type of an variable. For example, type(1) will return int.

You an also use scientific notations:

1
9.8125e2

981.25

Math Functions

Python also provides a lot of useful math functions, included in math package. To use them, you’ll have to import math first.

It’s ok if you don’t understand what is a package or what does import mean here. We will cover this later when we talk about Modules and Packages.

1
2
3
import math
print(math.pi)
print(math.e)

3.141592653589793
2.718281828459045

1
2
3
print(math.floor(98.6))
print(math.ceil(98.6))
#向下取整,向上取整

98
99

1
2
print(math.pow(2, 3)) #Tip: math.pow always return a float.
print(2**3)

8.0
8

1
math.sqrt(25)

5.0

Boolean

1
type(1 < 2)

bool

1
(2 < 1) or (1 < 2)

true

1
not (2 < 1)

true

1
2
a = (2 < 1) and (1 < 2)
a

false

1
type(a)

false

1
2
a = (2 == 1)
a

false

1
2
a = (2 != 1)
a

true

Strings

Strings are our first example of Python sequence. It is a sequence of characters.

1
2
s = 'this is a string'
type(s)

str

1
2
"this is also a string"
"I'm a string"

“this is also a string”
“I’m a string”

1
2
3
4
# He said:"I'm a string"
# escape
s = "He said: \"I'm a string\""
print(s)

He said: “I’m a string”

1
2
long_s = "You can put a long string that \ntakes up multiple lines here"
print(long_s)

You can put a long string that
takes up multiple lines here

1
2
3
4
5
s = '''
This is the first line
This is the second line
'''
print(s)

This is the first line
This is the second line

Type Conversions

1
2
3
a = str(98.6)
a
type(a)

str

1
str(True)

‘True’

1
float('98.6')

98.6

1
int('-123')

-123

If you mix different numeric types, Ptyhon will try to do the conversion for you. However, you cannot mix string with numbers, unless the operation make sense (string combination & duplicate).

1
1 + 2.0

3.0

1
True + 3

4

1
3.88+"28"


TypeError Traceback (most recent call last)

in ()
—-> 1 3.88+”28”

TypeError: unsupported operand type(s) for +: ‘float’ and ‘str’

1
2
3
4
print(int(3.88) + int("28"))  
print(int(-2.95) + int("28"))
print(float(3) + float("28"))
print(str(3.88) + str(28))

31
26
31.0
3.8828

Combine & Duplicate

1
2
3
4
template = "My name is"
name = "Joshua"
greeting = template + " " + name + "."
print(greeting)

My name is Joshua.

1
2
laugh = 3 * "Ha "
print(laugh)

Ha Ha Ha

Extract &Slice

1
2
3
letters = "abcdefghijklmnopqrstuvwxyz"
letters[0 ]
'a'
1
2
3
4
5
6
7
8
9
letters = "我爱北京天安门"

letters[25]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-199-3d4ad1959dec> in <module>()
----> 1 letters[25]

IndexError: string index out of range
1
2
letters[-5]
'北'
  • You can extract a substring from a string by using slice. Format: [start:end:step]

[:] extracts the all string
[start:] from start to the end
[:end] from the beginning to the end - 1 offset
[start:end] from start to end - 1
[start:end:step] from start to end - 1, skipping characters by step
[:] extracts the all string

1
letters[:]

‘我爱北京天安门’
[start:] from start to the end

1
letters[2:]

‘北京天安门’

1
letters[-3:]

‘天安门’
[:end] from the beginning to the end - 1 offset

1
letters[:5]

‘我爱北京天’

1
letters[:100]

‘我爱北京天安门’
[start:end] from start to end - 1

1
letters[2:5]

‘北京天’

1
letters[-6:-2]

‘爱北京天’

1
letters[-2:-6]

‘’
[start:end:step] from start to end - 1, skipping characters by step

1
2
#步长(间隔)
letters[1:5:2]

‘爱京’

1
letters[::7]

‘我’

1
letters[::-1]

‘门安天京北爱我’

### Get Length

1
len(letters)

7

Split & Join

1
2
3
#以逗号切分
lan = "python ruby c c++ swift"
lan.split()

[‘python’, ‘ruby’, ‘c’, ‘c++’, ‘swift’]

1
2
todos = "download python, install, download ide, learn"
todos.split(', ')

[‘download python’, ‘install’, ‘download ide’, ‘learn’]

1
'###'.join(['download python', 'install', 'download ide', 'learn'])

‘download python###install###download ide###learn’

Substitue

#居中居左排版

1
2
s = 'I like C. I like C++. I like Python'
s.replace('like', 'hate')

‘I hate C. I hate C++. I hate Python’

1
s.replace('like', 'hate', 1)

‘I hate C. I like C++. I like Python’

Layout

1
2
align = 'Learn how to align'
align.center(30)

‘ Learn how to align ‘

1
align.ljust(30)

‘Learn how to align ‘

1
align.rjust(30)

‘ Learn how to align’

1
2
3
4
#chars -- 移除字符串头尾指定的字符序列。
#str.strip([chars]);
ralign = align.rjust(30)
ralign.strip()

‘Learn how to align’

Other useful tools

1
2
py_desc = "Python description: Python is a programming language that lets you work quickly and integrate systems more effectively."
py_desc.startswith('Python')

True

1
py_desc.endswith('effectively.')

True

1
2
py_desc.find('language') #找到language的起始位置

44

1
py_desc.isalnum()

False

1
py_desc.count("Python") # 出现次数

2

1
py_desc.strip('.')

‘Python description: Python is a programming language that lets you work quickly and integrate systems more effectively’

1
py_desc.upper()

‘PYTHON DESCRIPTION: PYTHON IS A PROGRAMMING LANGUAGE THAT LETS YOU WORK QUICKLY AND INTEGRATE SYSTEMS MORE EFFECTIVELY.’

1
py_desc.title()

‘Python Description: Python Is A Programming Language That Lets You Work Quickly And Integrate Systems More Effectively.’

in and out~~

1
2
3
4
5
### Read user input ###
age = input("How old are you?")
height = input("How tall are you?")
weight = input("How much do you weigh?")
​print("So, you're %s old, %s tall and %s heavy." % (age, height, weight))

How old are you?10
How tall are you?20
How much do you weigh?30
So, you’re 10 old, 20 tall and 30 heavy.

1
2
3
4
5
### Read user input ###
age = input("How old are you?\n")
height = input("How tall are you?\n")
weight = input("How much do you weigh?\n")
​print("So, you're %s yers old, %s meters tall and %s kg heavy." % (age, height, weight))

How old are you?
10
How tall are you?
20
How much do you weigh?
30
So, you’re 10 yers old, 20 meters tall and 30 kg heavy.
字符串格式输出:
https://pyformat.info/#string_pad_align
https://dbader.org/blog/python-string-formatting
https://docs.python.org/3.6/library/string.html

New Style in Python 3.6

1
2
3
4
print('%s %s' % ('one', 'two'))
print('{} {}'.format('one', 'two'))
print('%d %d' % (1, 2))
print('{} {}'.format(1, 2))

one two
one two
1 2
1 2

1
print('{1} {0}'.format('one', 'two'))

two one

1
2
3
a = 5
b = 10
print(f'Five plus ten is {a + b} and not {2 * (a + b)}.')

Five plus ten is 15 and not 30.

1
2
3
name = "Joshua"
question = "hello"
print(f"Hello, {name}! How's it {question}?")

Hello, Joshua! How’s it hello?

python基础瞎写着玩

1
2
3
4
5
# python两个数交换
a = 10
b = 20
a,b = b,a
print("a = {} b = {} ".format(a,b))

a = 20 b = 10

1
import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!

1
534+31

565

1
23 ** 2

529

1
10 ** (1/3)

2.154434690031884

1
2
import math
math.pi

3.141592653589793

1
math.sin(math.pi/2)

1.0

1
math.floor(313.323)

313

1
math.ceil(323.23)

324

1
round(10/3,3)

3.333

1
2
3
apple_cost = 10
pipe_cost = 12
"苹果的价格:{} 辣椒的价格:{}".format(apple_cost,pipe_cost)

‘苹果的价格:10 辣椒的价格:12’

1
2
#id 函数,返回一个身份识别符,可以理解为一个变量的内存地址
line = "hell

2323860958384

字符串处理

切片

1
line[:10]

‘hello ,wel’

1
line[2:10]

‘llo ,wel’

1
line[3]

‘l’

1
line [2:20:2]  # 隔两个一取

‘lo,ecm oh’

1
line[-10:] # 取后十个字符

‘me to here’

1
line[::-1] #步长为-1 翻转字符

‘ereh ot emoclew, olleh’

1
2
3
line.capitalize
line.capitalize?
line.capitalize()

‘Hello ,welcome to here’

1
line.center(100,'-')

‘—————————————hello ,welcome to here—————————————‘

1
line.count('l')

3

1
line.endswith("ere")

True

1
line.startswith("qw")

False

1
line.find("e") #寻找e,返回下标,不存在返回-1

1

1
2
line ="   hello   \t\n "
line.strip()

‘hello’

1
line.replace("l","$$$")

‘ he$$$$$$o \t\n ‘

小白容易踩的坑

excepted an indented block

1.使用IF条件时需要注意缩进,Python中没有分号,通过缩进来表示上下级从属关系。
2.冒号后面需要写上一定内容

  • 笔记来源: wanmen
  • 排版及修改: Bbxren
Author: Bbxren
Link: http://bbxren.site/2020/07/02/Python/pyDay1/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶

Comment