John
John

Reputation: 13

User input in already given range for Python pattern

I need help. I want to print pattern in already specified range let's say from 4 to 17 and to print the pattern for any user input in that range. Let's say the user wants to enter number 5. The pattern should look like this:

pattern

But I don't know how to limit range. I have used this code

n = int(input('Enter number in range 4 to 17'))
for i in range(4, n+1, 1):
    for j in range(4, i + 1):
        print('*', end='')
    print()
for i in range(n, 4, -1):
    for j in range(4, i):
        print('*', end='')
    print()

Any help would be appreciated.

Upvotes: 1

Views: 810

Answers (3)

Leonardo Pimentel
Leonardo Pimentel

Reputation: 1

To fix your code I would use a "while True" loop until the user enters a value within the desired range.

To ensure this, include inside the loop some conditionals as in the example below.

Also include a notice for the user.

while True:
  n = int(input('Enter number in range 4 to 17'))
  if n >= 4 and n <=17:
    for i in range(n+1):
      for j in range(i):
          print('*', end='')
      print()
    for i in range(n-1,0,-1):
      for j in range(i):
        print('*', end='')
      print()
  break
  else:
    print('Value out range')

Upvotes: 0

mozway
mozway

Reputation: 260600

Regarding the first question, you could start your code with a loop to ask user input until it is correct:

n = 0
while 4 > n > 17:
    n = int(input('Enter number in range 4 to 17'')

# rest of code

Upvotes: 0

xio
xio

Reputation: 640

You can try this method

n = int(input('Enter number in range 4 to 17: '))

if n>4 and n<17:
    for i in range(n+1):
        print("*"*i)
        
    for j in range(n-1,0,-1):
        print("*"*j)

output

Enter number in range 4 to 17: 5

*
**
***
****
*****
****
***
**
*

Upvotes: 1

Related Questions