python-01

For loop

  1. Print 4 rows 4 columns rectangle
1
2
3
4
5
l = 4
for i in range(4):
for j in range(4):
print('*', end="")
print(' ')
  1. Print traiangle

    1
    2
    3
    4
    row = int(input('Type a number'))
    for i in range(1, row+1):
    print((row - i) * " ", end="") # 打印空格
    print(i * "* ") # 打印星号
  1. Print upside-down triangle

    1
    2
    3
    4
    l = 4
    for i in range(1, l + 1):
    print((i - 1) * " ", end="") # 打印空格
    print((4 - i + 1) * "* ") # 打印星号
  2. Diamond

1
2
3
4
5
6
7
row = int(input('Type a number'))
for i in range(1, row+1):
print((row - i) * " ", end="") # 打印空格
print(i * "* ") # 打印星号
for i in range(1, row + 1):
print(i * " ", end="") # 打印空格
print((row - i) * "* ") # 打印星号

While loop

  1. Number guessing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import random

flag = False
random_num = random.randint(1, 100)
while not flag:
guess = int(input('Please type a number you want to guess\n'))
print(random_num)
if guess < random_num:
print('Your number is too small')
elif guess > random_num:
print('Your number is too big')
else:
print('perfect')
flag = True
  1. 正序乘法表

    1
    2
    3
    4
    5
    6
    7
    8
    i = 1
    while i <= 9:
    j = 1
    while j <= i:
    print('%d*%d = %2d\t' % (i, j, i * j), end='')
    j += 1
    i += 1
    print()
  2. 逆序乘法表

    1
    2
    3
    4
    5
    6
    7
    8
    i = 9
    while i >= 1:
    j = 1
    while j <= i:
    print('%d*%d = %2d\t'%(j, i, i * j), end='')
    j += 1
    i -= 1
    print()
    1. triangle

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      row = 1
      while row <= 5:
      j = 1
      while j <= 5 - row:
      print(' ', end='')
      j += 1
      k = 1
      while k <= 2 * row - 1:
      print('*', end='')
      k += 1
      print()
      row += 1
  1. pramid
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
*
**
***
****
*****
'''
i = 1
while i <= 5:
j = 1
while j <= i:
print('*', end='')
j += 1
i += 1
print()

  1. Rectangular Spotted Graph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
i = 1
while i <= 5:
j = 1
while j <= 5:
if i == j:
print('X', end='')
elif j == 5 - i + 1:
print('X', end='')
else:
print('*', end='')
j += 1
i += 1
print()

"""
x00000x
0x00x00
000x000
00x0x00
0x000x0
x00000x
"""

Function

  1. Pass info from
1
2
3
4
5
6
def greet_user(username):
print("hello, " + username.title() + "!")


greet_user(input())