1

I am relatively new to programming and especially to Python. I am asked to create a for loop which prints 10 numbers given by the user. I know how to take input and how to create a for loop. What bothers me, is the fact that with my program I rely on the user to insert 10 numbers. How can I make the program control how many numbers are inserted? Here is what I tried:

x = input('Enter 10 numbers: ')
for i in x:
    print(i)
Mert Köklü
  • 2,183
  • 2
  • 16
  • 20
Hristo Georgiev
  • 69
  • 1
  • 3
  • 9
  • There are a bunch of different ways to do this: my preferred option would be to use a for loop. Make a for loop that loops 10 times (`for _ in range(9):`) and each time record your input in a list. I'm not sure what the parameters are for our assignment, but if you need to do validation on the input, look [here](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response). – Christian Dean Dec 01 '19 at 20:41
  • here you go https://stackoverflow.com/q/17647907/5986907 though it's a not a duplicate as such – joel Dec 01 '19 at 20:42

2 Answers2

1

You need to

  • ask 10 times : make a loop of size 10
  • ask user input : use the input function
for i in range(10):
    choice = input(f'Please enter the {i+1}th value :')

If you want to keep them after, use a list

choices = []
for i in range(10):
    choices.append(input(f'Please enter the {i + 1}th value :'))

# Or with list comprehension
choices = [input(f'Please enter the {i + 1}th value :') for i in range(10)]
azro
  • 53,056
  • 7
  • 34
  • 70
1

What if input is row that contains word (numbers) separated by spaces? I offer you to check if there are 10 words and that they are numbers for sure.

import re
def isnumber(text):
   # returns if text is number ()
   return re.match(re.compile("^[\-]?[1-9][0-9]*\.?[0-9]+$"), text)

your_text = input() #your input
splitted_text = your_text.split(' ') #text splitted into items

# raising exception if there are not 10 numbers:
if len(splitted_text) != 10:
    raise ValueError('you inputted {0} numbers; 10 is expected'.format(len(splitted_text)))

# raising exception if there are any words that are not numbers
for word in splitted_text:
    if not(isnumber(word)):
        raise ValueError(word + 'is not a number')

# finally, printing all the numbers
for word in splitted_text:
    print(word)

I borrowed number checking from this answer

mathfux
  • 5,759
  • 1
  • 14
  • 34