简体   繁体   中英

A for loop to print dictionary items once without repeating the print function

I am new to Python and Stackoverflow in general, so sorry if my formatting sucks and i'm not good at enlish.But i have a problem with this code.

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
for n in range(1, n + 1):
   if n >= 1:
       for i in range(2, n):
           if (n % i) == 0:
              break
       else:
           print('They are',n,end=' ')

The result of the code when ran comes out looking like this:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 They are 2 They are 3 They are 5 They are 7 They are 11 They are 13 They are 17 They are 19 They are 23 They are 29 They are 31 They are 37

but i want it like this:

Displays prime numbers from 1 to N.
Please enter a value of n:40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

If you're completely determined not to use the print function more than once inside the loop, you could set a flag to determine whether to print the first two words. Like so:

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
first = 'They are '
for n in range(1, n + 1):
   if n >= 1:
       for i in range(2, n):
           if (n % i) == 0:
              break
       else:
           print(first + str(n), end=' ')
           if len(first) > 0:
              first = ''

The following solution may help you

print('Displays prime numbers from 1 to N.')
n = int(input('Please enter a value of n: '))
num = [] # Create empty list
for n in range(1, n + 1):
    if n >= 1:
        for i in range(2, n):
            if (n % i) == 0:
                break
        else:
            num.append(n)
 # Write the print statement outside of the loop and use .join() function and for loop 
#to print each element of the list look like the output you have posted 
#
print('They are'," ".join(str(x) for x in num))

Output:

Displays prime numbers from 1 to N.
Please enter a value of n: 40
They are 1 2 3 5 7 11 13 17 19 23 29 31 37

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM