python3下:
input(“what’s your name:”)
python2.7下:
raw_input(“what’s your name:”)
python2.7下
if ():
print a
elif *:
print b
else:
print c
!/usr/bin/env/ python
lucky_num=19
guess_count=0
while guess_count <3:
print (“guess count:”,guess_count)
input_number=int(input(“Input your guess number:”))
if input_number>lucky_num:
print(“the real number is smaller.”)
elif input_number<lucky_num:
print(“the real number is bigger..”)
else:
print(“Bingo!”)
break
guess_count+=1
else:
print(“too many retrys!”)
#!/usr/bin/env/ python
lucky_num=19
guess_count=0
for i in range(3):
input_number=int(input("Input your guess number:"))
if input_number>lucky_num:
print("the real number is smaller.")
elif input_number<lucky_num:
print("the real number is bigger..")
else:
print("Bingo!")
break
else:
print("too many retrys!")
字符串是%s,整数是%d,浮点数是%f
'''的作用
#!/usr/bin/env/ python
Name=input("input your name:").strip()
Age=input("input your age:")
Job=input("input your job:")
Msg='''
Information of %s:
Name:%s
Age:%s
Job:%s
''' %(Name,Name,Age,Job)
print(Msg)
创建列表
name_list=['fan','one','haha']
或
name_list=list(['fan','one','haha'])
基本操作:
例子
#!/usr/bin/env/ python
a=[1,2,3,'a','b','c',2]
b=[11,12,13]
print (a)
print (b)
print(a[0:3])
print(a[0:3:2])
print(a[2:5])
print(a[-3:-1])
print(a[-3:])
a.append(4)
print(a)
aa=a.count(2)
print(aa)
a.index(2)
a.insert(0,0)
print(a)
a.extend(b)
print(a)
#b.sort()
a.remove('a')
print(a)
a.pop()
print(a)
a.reverse()
print(a)
输出如下:
[1, 2, 3, 'a', 'b', 'c', 2]
[11, 12, 13]
[1, 2, 3]
[1, 3]
[3, 'a', 'b']
['b', 'c']
['b', 'c', 2]
[1, 2, 3, 'a', 'b', 'c', 2, 4]
2
[0, 1, 2, 3, 'a', 'b', 'c', 2, 4]
[0, 1, 2, 3, 'a', 'b', 'c', 2, 4, 11, 12, 13]
[0, 1, 2, 3, 'b', 'c', 2, 4, 11, 12, 13]
[0, 1, 2, 3, 'b', 'c', 2, 4, 11, 12]
[12, 11, 4, 2, 'c', 'b', 3, 2, 1, 0]
Process finished with exit code 0
创建元组,用小括号
t=(1,2,3,4)
元组只有index()和count()2个方法
person={
"name":'fan',
"age":18,
"gender":"男",
}
print(person.keys()) #输出所有的key,并保存为列表
print(person.values()) #输出所有的值,并保存为列表
for ele in person: #输出所有的key
print (ele)
for k,v in person.items(): #输出所有的key和value,无序,一般只在for循环中使用,将元素赋值给k和v
print(k)
print(v)
==、!=、<>python3中已废弃、>、<、
+、-、*、/、%取模,即余数、**幂、//取整除
=、+=、-=、*=、/=、%=、**=、//=
& 与运算
| 或运算
^
~
<<
in
not in
例子
>>> a=[1,2,3]
>>> type(a)
<class 'list'>
>>> 1 in a
True
>>> 3 in a
True
>>> 4 in a
False
is
is not
例子
>>> a=[1,2,3]
>>> type(a)
<class 'list'>
>>> type(a) is list
True
>>> type(a) is tuple
False
file_object=file("文件路径","模式"),Python3里废弃
file_object=open("文件路径","模式")
w+ 打开一个文件用于读写,如果该文件存在则将其覆盖;如果不存在,创建新文件
每次只读取一行数据
for line in obj:
print line
obj.write('内容')
obj.close( )