Python 入门基础
Unicode
ASCII 用8个位表示文字 ,最高位一定是零,低七位表示数值Unicode是由16个位组成的(65535) 最高位也是0x0000~0xfffhelp(str)查看所有str函数
字符串的格式化表达式:
生成一定格式的字符串格式字符串中以 % 开头的为占位符,占位符的位置将参数值替换语法:格式字符串 % 参数值格式字符串 % (参数值1,参数值2,...)占位符和其的类型码:%s 字符串 使用shr(obj)转为字符串%r 字符串 使用repr(obj)转为字符串%c 整数转为字符串,使用chr(i)函数%d 10进制整数%o 8进制整数%x 16进制整数(字符a-f)%X 16进制整数(字符A-F)%e 浮点数(e)如 2.9e+10%E 浮点数(E)如2.9E+10%f %F 浮点数10进制形式%g %G 进制进形式浮点数或指浮点数自动转换%% 等同于一个 % 字符占位符与类型码之间的格式语法:
%[- + 0 宽度.精度]类型码- 左对齐+ 右对齐0 左右空白位置补0宽度:整个数据输出的宽度
精度:保留小数点后多少位,默认6位"%10d" %123 #" 123""%+10d"%123 #" +123""%-10d"%123 #"123 ""%10s"%"abc" #" abc""%010d"%123 #"0000000123" "%f"%3.14159625358 # "3.141593""%7.2f"%3.14159265358#" 3.14"循环语句:
while:根据一定的条件,重复执行一些相同或相似的内容先判断真值表达式是否成立在执行执行完内容继续返回真值表达式判断是否成立 直到真值表达式为false时 判断是否有else有则执行else的内容没有则循环结束注意事项:要控制真值表达式的值来防止死循环通常用真值表达式内的循环变量来控制真值表达式的值通常在循环语句块内改变循环变量来控制循环次数和变量走向while的嵌套:while语句和其他语句一样,可以嵌套放入任何复合语句当中break:用于循环语句(while、for)中用来终止当前循环(跳出循环)当break语句执行后此循环以后的语句将不再执行break终止循环时 else语句块将不再执行break语句通常和if组合使用break只能终止当前作用域 如循环嵌套时,不会跳出外循环break只能在循环语句(while、for)内使用死循环:死循环是指循环条件一直成立的循环死循环通常用break语句来终止循环死循环的else语句块永远不会执行练习:
1.输入一行字符串,将字符串中Unicode编码值最大的一个字符打印出来(不允许用max函数)提示:while内可以嵌套if答案:
print("Answer to question 1:", "\n") s = input("plaese input at will string:")i = 0top = s[0]while i < len(s): if ord(top) < ord(s[i]): top = s[i] i += 1print("you input string in top1:", top, ord(top))
2.打印 从零开始的浮点数,每个数增加0.5,
打印出10以内的这样的数:0.00.51.00.52.0...10答案:
print("Answer to question 2:", "\n")
i = 0while i < 10: i += 0.5 print(i)
3.打印输出1~20在同一行内 结束后换行
答案:
s = 0while s < 20: s += 1 print(s, end = " ")else: print()
4.打印输出1~20在同一行内 打印10行
i = 0while i < 10: s = 0 while s < 20: s += 1 print(s, end = " ") else: print() i += 1
5.当输入一些数字,输入负数时结束输入
当完成输入完后,打印输入的数时多少答案:
s = 0while True: a = int(input("plaese input at will integer:")) s += a if a < 0: breakprint(s)
6.Sn = 1/2+1/4+1/8....+1/(2**n)
求当n等同于100时Sn的值是多少答案:
Sn = 1i = 0while i < 100: i += 1 Sn += 1 / 2 ** iprint(Sn)
7.输入一个整数打印出矩形 若输入1则输出1个#
例如:
输入1:#
输入2:
####输入6:
####### ## ## ## ## #######答案:
s = int(input("plaese input at will integer:"))if s > 1: print("#" * s) i = 2 while i < s: i += 1 print("#" + " " * (s - 2) + "#") print("#" * s)else: print("#")
8.用while语句实现打印三角形,输入一个整数表示三角形
的宽度和高度,打印出相应的三角形如:1)**********2)**** *** ** *3) * ** *******4)**********答案:
a = int(input("plaese input at will ingeger:"))i = 0b = ac = ad = awhile i < a: i += 1 print("*" * i)print()i = 0while i < d: print((a - d) * " " + "*" * d) d -= 1print()i = 0while i < c: i += 1 print((c - i) * " " + "*" * i)print()i = 0while i < b: print("*" * b) b -= 1
a = int(input("plaese input at will ingeger:"))i = 0d = awhile i < a: while i < d: print((a - d) * " " + "*" * d) d -= 1 print("*" * (i + 1)) i += 1print()