Small Basic Challenge – Week 9: Easy
Write a Text Window program that asks the user for a width and height.
The program will then draw a rectangle with these dimensions using asterisks (*)Example:
What is the width? 10
What is the height? 5
Here is your rectangle:
**********
**********
**********
**********
**********
Comincia visualizzando una riga di asterischi di lunghezza n
1 2 3 |
for i in range(n): print("*", end="") print() |
Un rettangolo di asterischi come height righe di width caratteri
1 2 3 4 5 6 7 8 |
width =int(input("What is the width? ")) height=int(input("What is the height? ")) print("Here is your rectangle:") for r in range(height): for c in range(width): print("*"', end="") print() |
Funzione
La parte del codice che disegna diventa una funzione
1 2 3 4 5 6 7 8 9 10 |
def rectangle(w, h): print("Here is your rectangle:") for r in range(h): for c in range(w): print("*", end="") print() width =int(input("What is the width? ")) height=int(input("What is the height? ")) rectangle(width, height) |
Più difficile: disegna solo il contorno del rettangolo (una cornice).
Osserva
- La prima e l’ultima riga sono piene: il codice è lo stesso…
- Le righe intermedie sono vuote
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
def rectangle2(w, h): print("Here is your rectangle:") for c in range(w): print("*", end="") print() for r in range(h-2): print("*", end="") for c in range(w-2): print(" ", end="") print("*", end="") print() for c in range(w): print("*", end="") print() width =int(input("What is the width? ")) height=int(input("What is the height? ")) rectangle2(width, height) |
Disegna
- una riga piena
- height-2 volte una riga vuota
- una riga piena
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def full(n): for i in range(n): print("*", end="") print() def empty(n): print("*",end="") for i in range(n-2): print(" ", end="") print("*", end="") print() def rectangle3(w, h): print("Here is your rectangle:") full(w) for i in range(h-2): empty(w) full(w) width =int(input("What is the width? ")) height=int(input("What is the height? ")) rectangle3(width, height) |