Example&exercise:conditions代码
注意事项 :注意缩进,和原来的代码对齐,tab和空格不能混用
>>> a=[24,16,54]
>>> b=[]
>>> if a[0] < a[1] and a[0]< a[2]:
... b.append(a[0])
... if a[1] < a[2]:
... b.append(a[1])
... b.append(a[2])
... else:
... b.append(a[2])
... b.append(a[1])
>>> #example of for and range
... #default start of range is 0
... #default step of range is 1
... print(i)
... l=i**2
... print(l)
清屏操作:
import os
os.system( 'cls' )
由此也可见,想要执行任何一条系统命令,都只需要执行os.system( 'COMMAND' )就行了.
由于缩进总出错,不好编辑,不用anaconda prompt编辑器,用Py’Charm了
找到第一个能被17整除的数,300-350
#search the firstnumber which can be divided by 17 in [300,350]
for i in range(300,351):
if i%17==0:
print(i)
break
else:
continue
求1-100偶数的和
a=0 for i in range(1,101): if i%2==0: a+=i; print(a)
定义函数
def MaxOfTwo(x1,x2): if x1>=x2: return x2 else: return x1 a=1 b=2 c=MaxOfTwo(a,b) print(c)
关于文件的操作
![]()
创建txt文本
file=open('newfile.txt','w') file.write('Ian created for .\n') file.write('how about you!') file.close()
逐行读入txt文件,以字符串的方式
file=open('newfile.txt','r') for line in file: print(file.readline())
print(file.readlines()) file.close()
以全部读入的方式:
file=open('newfile.txt','r') for line in file: print(line) file.close()
文件加入内容:
file=open('newfile.txt','a') file.write('\n I am back again.\n') file.close()