Here is my code so far:
def main():
for var in range (1, 101):
num= IsPrime(var)
if num == 'true':
print(var, end=', ')
The IsPrime function calculates whether or not a function is prime.
I need to print out the prime numbers from 1 to 100 formatted into a single line with commas and spaces in between. for example, output should look like:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97
I tried to run my program, but I always get a trailing comma at the end of 97. I don't know how to remove the comma, and because it is a loop, str.rstrip and [:-1] don't work.
I need to use a loop and I can't use
print('2')
print(', ', var, end='')
for the other prime numbers.
I can't tell if there's an easier way to code this or I'm not aware of a function that can do this correctly.
You can use ', '.
To remove the leading and trailing comma from a string, call the replace() method with the following regular expression as the first parameter - /(^,)|(,$)/g and an empty string as the second.
The idiomatic Python code in my opinion would look something like this:
print(', '.join([str(x) for x in xrange(1, 101) if IsPrime(x) == 'true']))
(Things would be better if IsPrime
actually returned True
or False
instead of a string)
This is functional instead of imperative code.
If you want imperative code, you should print the ', '
before each element excepting the first item of the loop. You can do this with a boolean variable which you set to true after you've seen one item.
You can put all the numbers into a list and then join all the values:
def main():
primes = []
for var in range (1, 101):
if IsPrime(var) == 'true':
primes.append(var)
num = IsPrime(var)
print(', '.join(primes))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With