-4

I'm new to programming and am stuck with an exercise. I ask for a number from user and then I want to save all numbers that are lower then the entered one in a list.

Then I need to calculate the factorial of every second number in that list and print it out. How can I do that?

def get_input_number():
 num = int(input("Enter number between 1 and 10: "))
 if num < 1 or num > 10:
     print ("Invalid input.  Try again ")
     get_input_number()
 else:
     return num

get_input_number()

this is all I have but how can I proceed?

Tom
  • 37
  • 4

2 Answers2

0

Try this:

import math
while True:
    num = int(input("Give me a number: "))  # Get the number
    if(1<=num<=10):
        break;
list_num = [x for x in range(1, num + 1)]  # A list with every second number
print([math.factorial(z) for z in list_num[0::2]])  # The factorial of every element in that list.

You should read more on list comprehension.

Bernardo Meurer
  • 2,295
  • 5
  • 31
  • 52
  • I get NameError: name 'math' is not defined – Tom Mar 15 '16 at 13:29
  • But what if I want it to save all numbers below entered number to the list and then take every second number to calculate the factorial. And my problem is the entered number needs to be between 1 - 10. – Tom Mar 15 '16 at 14:07
  • @Robert I added the `while true` to make sure the number is between 1 and 10 and also `list_num` is all the number below the value the user gave now. And `list_num[0::2]` gets every second element. – Bernardo Meurer Mar 15 '16 at 14:12
  • Something missing in maybe print([math.factorial(z) for z in list_num[0::2]) I get error – Tom Mar 15 '16 at 14:21
  • @Robert There, missed a `]` – Bernardo Meurer Mar 15 '16 at 14:22
0

I would recommend you using list comprehension for creating the first list you need, small example:

foo = 20
list = [i for i in xrange(foo, 0, -1)]

which creates the following:

[20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

Then you would need to create a for loop to multiply each number you want and print the result.

TIP!! Note the third parameter in xrange? That's the control parameter, in the example above, when an iteration is complete, the result is i - 1.

Good luck!

patito
  • 530
  • 2
  • 13