0

I'm making a program that prints all the prime numbers from a number that the user enters. Everything is working but I'm just having trouble printing the numbers.

def math(user):
  for num in range (user + 1):
    if num > 1:
      for i in range(2,num):
        if (num % i) == 0:
          break
      else:
        print('The Primes from 2 to ', user, 'are: ',num)


def main():
  user = ('Enter the maximum value to check primes up to: ')
  math(user)

When I enter 10 it prints:

Enter the maximum value to check primes up to: 10
The Primes from 2 to  10 are:  2
The Primes from 2 to  10 are:  3
The Primes from 2 to  10 are:  5
The Primes from 2 to  10 are:  7

I just want to have:

Enter the maximum value to check primes up to: 10
The Primes from 2 to  10 are:  2, 3, 5, 7

I think I have to add a list but I'm not sure where.

Michael M.
  • 10,486
  • 9
  • 18
  • 34

1 Answers1

0

I do not think the [duplicate] answer will help much OP until they first get to the proper logical steps to reach the [duplicate] question.

A bit like suggested, you could print the beginning of your answer first (or store as a string) and then calculate your list of result and concatenate the whole things at the end for printing. If you store a string, you could add to it each found result, and print at the end. But the problem is managing the number of comma, as I guess you want one less comma than result values.

The pythonic solution to the 'comma problem' is the str.join() function. The notation is unusual, just remember the string you are 'working with' is your 'separator' string, in our case the comma (followed by a space for good measure). Like this:

', '.join(iterables_of_strings)

The usual way to use it is to store all your result (in str form) in a iterable, typically a list, like this:

def math(user):
  result = []
  for num in range (user + 1):
    if num > 1:
      for i in range(2,num):
        if (num % i) == 0:
          break
      else:
        result.append(str(num))

and to format all elements of your list at the end with the join function:

  print('The Primes from 2 to ', user, 'are: ', ', '.join(result) )