Python快速入门,敲一遍下面的代码,第二天就可以上手砍项目。
print("Hello World! 你好,世界!")
print("i love you")
print("This is the 3rd line, \n",
"and this is also the 3rd line.")
print('''sfadsjlkfjdsa
sdfds
dsf
d
''')
Grammer
print(4-5)
print(8 + )
110/12.97
Syntax
number_of_cars = 34 # Python
# there is no { } and there is no ;
x = 4
if x < 7:
print(x)
if x < 7:
print("x is smaller than 7")
Semantics
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
A variable is a memory location where a programmer can store a value. Example : roll_no, amount, name etc.
VS:Variable and Value
- A variable is a memory location where a programmer can store a value. Example : roll_no, amount, name etc.
- Value is either string, numeric etc. Example : "Sara", 120, 25.36
- Variables are created when first assigned.
- Variables must be assigned before being referenced.
- The value stored in a variable can be accessed or updated later.
- No declaration required
- The type (string, int, float etc.) of the variable is determined by Python
- The interpreter allocates memory on the basis of the data type of a variable.
speed_of_liuxiang=110/12.97
distance= 1000
time = distance/speed_of_liuxiang
print(time)
print(time/60)
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.
peed_of_joshua=110/10
time = distance/speed_of_joshua
print(time)
time = time-10
print(time)
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
123
05 #wrong
x = 123,456,789
type(x)
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 + 2
a = 5
a += 2
a
a = 5
a = a - 3
a
9 // 5
9 % 5
优先权
2 + 3 * 4
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 232232 different integers. Since we want to store both positive numbers and negative numbers at the same time, each side will get 231231 numbers, which is 2,147,483,648.
In Python3, an int
can handle any integer no matter how large it is without causing overflow.
a = 10**100
a
a*a
10
0b10
0o10
0x10
Float
a = 98.5
type(a)
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:
9.8125e2
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.
import math
print(math.pi)
print(math.e)
print(math.floor(98.6))
print(math.ceil(98.6))
print(math.pow(2, 3)) #Tip: math.pow always return a float.
print(2**3)
math.sqrt(25)
Boolean
type(1 < 2)
(2 < 1) or (1 < 2)
not (2 < 1)
a = (2 < 1) and (1 < 2)
a
type(a)
a = (2 == 1)
a
a = (2 != 1)
a
Strings
Strings are our first example of Python sequence. It is a sequence of characters.
s = 'this is a string'
type(s)
s = 'this is a string'
"this is also a string"
"I'm a string"
# He said:"I'm a string"
# escape
s = "He said: \"I'm a string\""
print(s)
s = "ha"
print(s*10)
long_s = "You can put a long string that \ntakes up multiple lines here"
print(long_s)
long_s = 'you can put a long string that \ntakes up multiple lines here'
print(long_s)
s = '''
This is the first line
This is the second line
'''
print(s)
s = '''this is the first line
this is the second line'''
Type Conversions
a = str(98.6)
a
type(a)
str(True)
float('98.6')
int('-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 + 2.0
True + 3
3.88+"28"
print(int(3.88) + int("28"))
print(int(-2.95) + int("28"))
print(float(3) + float("28"))
print(str(3.88) + str(28))
Combine & Duplicate
tempate = 'my name is'
name = 'luogensheng'
greeting = tempate + ' ' + name + '.'
print(greeting)
laugh = 3 * "Ha "
print(laugh)
Extract &Slice
letters = "abcdefghijklmnopqrstuvwxyz"
letters[0]
letters = "我爱北京天安门"
letters[25]
letters[-2]
You can extract a substring from a string by using slice. Format: [start:end:step]
[:]
extracts the all string[start:]
fromstart
to the end[:end]
from the beginning to theend - 1
offset[start:end]
fromstart
toend - 1
[start:end:step]
fromstart
toend - 1
, skipping characters bystep
[:]
extracts the all string
letters = "abcdefghijklmnopqrstuvwxyz"
letters[:]
[start:]
from start
to the end
letters[2:]
letters[-3:]
[:end]
from the beginning to the end - 1
offset
letters[:5]
letters[:100]
[start:end]
from start
to end - 1
letters = "abcdefghijklmnopqrstuvwxyz"
letters[2:5]
letters[-6:-2]
letters[-2:-6]
[start:end:step]
from start
to end - 1
, skipping characters by step
letters = "abcdefghijklmnopqrstuvwxyz"
letters[1:5:2]
letters[::7]
letters[::-1]
Get Length
len(letters)
Split & Combine
lan = "python ruby c c++ swift"
lan.split()
lan = 'python ruby c c++ swift'
' '.join(['python','ruby','c','c++','swift'])
todos = "download python, install, download ide, learn"
todos.split(', ')
'|'.join(['download python', 'install', 'download ide', 'learn'])
Substitue
s = 'I like C. I like C++. I like Python'
s.replace('like', 'hate')
s.replace('like', 'hate', 1)
Layout
align = 'Learn how to align'
align.center(30)
align.ljust(30)
align.rjust(30)
ralign = align.rjust(30)
ralign.strip()
Other useful tools
py_desc = "Python description: Python is a programming language that lets you work quickly and integrate systems more effectively."
py_desc.startswith('Python')
py_desc.endswith('effectively.')
py_desc.find('language')
py_desc[44]
note = 'abcdefghijklmnopqrstuvwxyz'
start_note = note.find("h")
start_link = note.find('h',start_note)
start_link
py_desc.isalnum()
py_desc.count("Python")
py_desc.strip('.')
py_desc.lower()
py_desc.upper()
py_desc.title()
in and out~~
### 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))
### 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))
字符串格式输出:
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
print('%s %s' % ('one', 'two'))
print('{} {}'.format('one', 'two'))
print('%d %d' % (1, 2))
print('{} {}'.format(1, 2))
print('{1} {0} {2}'.format('one', 'two','asd'))
a = 5
b = 10
print(f'Five plus ten is {a + b} and not {2 * (a + b)}.')
name = "luogensheng"
question = "hello"
print(f"Hello, {name}! How's it {question}?")

郭楠译
2020-12-17 6:10:45主题真棒
zizdog
2020-12-09 0:15:46举报博主标题党
纬八路随笔
2020-11-29 21:29:25wo di kan bu ming bai.mei gan yong han zi.wei le bu wai lou,zhi you yong pin yin.
卷土
2020-04-03 11:21:34Thanks
卷土
2020-04-03 11:21:10I use the wordpress
晴和君
2020-03-31 19:54:36I just learn it from practice.
卷土
2020-04-03 11:19:32@晴和君 😆😆
ZAERA
2020-03-05 20:25:11python学习手册,python官方文档还是很不错的
姜辰
2020-01-29 15:47:03这入门都是英语说明了,水准高。
卷土
2020-02-01 12:05:53@姜辰 哈哈,官方的文档呀,全是英文的
ExoRank
2020-01-27 9:03:13Awesome post! Keep up the great work! 🙂
卷土
2020-01-27 11:30:50@ExoRank Thx😆