Python利用for循环打印星号三角形的案例
简单的for循环打印三角形
1,for循环方法实现星星三角
代码:
for i in range(0,5): for j in range(i+1): if i == 4: print("* ",end="") continue if j == 0 or j == i: print("* ",end="") else: print(" ",end="") print()
2.实心三角:
for i in range(5): print("* " * (i+1))
3.实心正方形
for i in range(5): print("* "*5) print()
4.空心正方形
for i in range(5): print("* "*5) print() for i in range(4): if i == 0: print("* " * 5) if i ==3: print("* " * 5) continue for j in range(5): if j == 0: print("* ",end=" ") if j == 4: print("* ") else: print(" ",end="")
5.金字塔:
for i in range(5): print(" "*(4-i),end="") print(" * "*(i+1))
刚开始学习,博客写得不是很好。
补充知识:python:任意输入3个数,判断能否组成三角形
任意输入3个数,判断能否组成三角形,并输出三角形为等边/等腰/直角/普通三角形.
三角形:两边之和大于第三边
直角三角形:勾股定理
#!/usr/bin/python # -*- coding:utf-8 -*- #输入合法性检查,必须输入正数,不支持科学计数法 def ispositive(numb): try: float(numb) except: return False else: if float(numb) <= 0: return False else: return True #直角三角形判断 def ispythagoras(a,b,c): if a**2 + b**2 == c**2 or a**2 + c**2 == b**2 or b**2 + c**2 == a**2: return True else: return False num1 = input("pls enter 1st number:\n") while not ispositive(num1): num1 = input("That's not a valid number. Try again:\n") num2 = input("pls enter 2nd number:\n") while not ispositive(num2): num2 = input("That's not a valid number. Try again:\n") num3 = input("pls enter 3rd number:\n") while not ispositive(num3): num3 = input("That's not a valid number. Try again:\n") num1 = float(num1) num2 = float(num2) num3 = float(num3) #欢迎点评,引用请注明出处 if num1 + num2 > num3 and num2 + num3 > num1 and num1 + num3 > num2: if num1 == num2 == num3: print("%.2f\n%.2f\n%.2f\n可以组成等边三角形" % (num1,num2,num3)) elif num1 == num2 or num2 == num3 or num1 == num3: if ispythagoras(num1,num2,num3): print('%.2f\n%.2f\n%.2f\n可以组成等腰直角三角形' % (num1,num2,num3)) else: print('%.2f\n%.2f\n%.2f\n可以组成等腰三角形' % (num1,num2,num3)) elif ispythagoras(num1,num2,num3): print('%.2f\n%.2f\n%.2f\n可以组成直角三角形' % (num1,num2,num3)) else: print('%.2f\n%.2f\n%.2f\n可以组成普通三角形' % (num1,num2,num3)) else: print('%.2f\n%.2f\n%.2f\n不能组成三角形' % (num1,num2,num3))
以上这篇Python利用for循环打印星号三角形的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。
赞 (0)