1、打印99乘法口诀表
#!/usr/bin/env python #-*- coding:utf-8 -*- def main(): for i in range(1,10): for j in range(1,i+1): print('{}*{}={:<3}'.format(j,i,(j*i)),end=' ') print(' ') if __name__ == '__main__': main()
2、for循环嵌套打印金字塔
实现正向打印和反向打印 #!/usr/bin/env python #-*- coding:utf-8 -*- import argparse class Pyramid: def __init__(self,row,dire): self.row = row self.dire = dire def run(self): str_base = "*" str_none = " " if self.dire.lower() == 'p': for i in range(1,self.row+1): str_obj = (self.row-i)*str_none + (2*i-1)*str_base + (self.row-i)*str_none print(str_obj) elif self.dire.lower() == 'n': for j in range(1,self.row+1): str_obj = (j-1)*str_none + (2*self.row-2*j+1)*str_base + (j-1)*str_none print(str_obj) if __name__ == '__main__': parser = argparse.ArgumentParser(description = 'Print the pyramid!') parser.add_argument('--row', action='store', dest='row', type=int, required=True, help='The row number to print pyramid') parser.add_argument('--dire', action='store', dest='dire', choices=['p','P','n','N'], required=True, help='Choose positive(p) or negative(n)') args = parser.parse_args() p = Pyramid(args.row,args.dire) p.run()
3、使用for+range实现用户登录失败3次退出程序
#!/usr/bin/env python #-*- coding:utf-8 -*- def main(): user_dict = {'egon':'vip66','tank':'ccc123'} for i in range(3): name_of_user = input('请输入用户名:').strip() passwd_of_user = input('请输入密码:').strip() if name_of_user in user_dict.keys() and passwd_of_user == user_dict.get(name_of_user): print('登录成功!') break else: print('用户名或密码输错3次!退出') if __name__ == '__main__': main()
4、字符串操作
#!/usr/bin/env python #-*- coding:utf-8 -*- def main(): name = ' aleX' print(name.strip()) print(name.startswith('al')) print(name.endswith('X')) print(name.replace('l','p')) print(name.split('l')) print(name.lower()) print(name.upper()) print(name[1]) print(name[0:3:1]) print(name[-2:]) print(name.find('e')) print(name[:-1]) if __name__ == '__main__': main()
[root@Kingstar day07]# python practice_4.py aleX False True apeX [' a', 'eX'] alex ALEX a al eX 3 ale