Python notes day 1
1.Run python: python name.py
2.Comment:
“””
multiple line
“””
Sublime Text or PyCharm for python ide.
import this#put this in terminal, the zen of python
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!
Python notes day 2
True, False, None
Variable name: number, letter, _, and cannot use number as front.
field instance, protected use , private use _
type() : return <class ‘type’>
chr(): int to unicode’s char
ord(): unicode char to an int
input(): for user input
print(): for output
%d
是整数的占位符,%f
是小数的占位符,%%
表示百分号(因为百分号代表了占位符,所以带占位符的字符串中要表示百分号必须写成%%
),字符串之后的%
后面跟的变量值会替换掉占位符然后输出到终端中运算符 描述 []
[:]
下标,切片 **
指数 ~
+
-
按位取反, 正负号 *
/
%
//
乘,除,模,整除 +
-
加,减 >>
<<
右移,左移 &
按位与 ^
`` <=
<
>
>=
小于等于,小于,大于,大于等于 ==
!=
等于,不等于 is
is not
身份运算符 in
not in
成员运算符 not
or
and
逻辑运算符 and, or , not
在使用
print
函数输出时,也可以对字符串内容进行格式化处理,上面print
函数中的字符串%1.f
是一个占位符,稍后会由一个float
类型的变量值替换掉它。同理,如果字符串中有%d
,后面可以用一个int
类型的变量值替换掉它,而%s
会被字符串的值替换掉。除了这种格式化字符串的方式外,还可以用下面的方式来格式化字符串,其中{f:.1f}
和{c:.1f}
可以先看成是{f}
和{c}
,表示输出时会用变量f
和变量c
的值替换掉这两个占位符,后面的:.1f
表示这是一个浮点数,小数点后保留1位有效数字。print(f'{f:.1f}华氏度 = {c:.1f}摄氏度')
1
2
3
13. ```python
print('面积: %.2f' % area)python print格式化输出。
- 打印字符串
1
print ("His name is %s"%("Aviad"))
效果:
2.打印整数
1
print ("He is %d years old"%(25))
效果:
3.打印浮点数
1
print ("His height is %f m"%(1.83))
效果:
4.打印浮点数(指定保留小数点位数)
1
print ("His height is %.2f m"%(1.83))
效果:
5.指定占位符宽度
1
print ("Name:%10s Age:%8d Height:%8.2f"%("Aviad",25,1.83))
效果:
6.指定占位符宽度(左对齐)
1
print ("Name:%-10s Age:%-8d Height:%-8.2f"%("Aviad",25,1.83))
效果:
7.指定占位符(只能用0当占位符?)
1
print ("Name:%-10s Age:%08d Height:%08.2f"%("Aviad",25,1.83))
效果:
8.科学计数法
1
format(0.0015,'.2e')
效果:
Python notes day 3
1.if, elif, else
Python notes day 4
- for in 循环: for x in range(a, b, c):# a是初始值,b是最终,到b-1, c是iterate的长度。
- while循环,配上break,continue
Python notes day 5
CRAPS game:
非常好玩的游戏, 在桌面新建.py结尾的文件或用idle直接打开即可
注意: python2可能不支持中文
1 | from random import randint |