Beginner creating fizzbuzz function - python

This code is supposed to output fizz if number is divisible by 3, buzz if divisible by 5 and fizzbuzz if divisible by 3 and 5. Although I'm a bit unfamiliar with defining my own function and using the return appropriately. How do I remove the last 16 if the user inputs the number 16?
number = int(input("Enter a number: "))
def fizzbuzz(number):
n = 1
while n <= number:
if n % 3 != 0 and n % 5 != 0:
print(n)
elif n % 3 == 0 and n % 5 == 0:
print("fizzbuzz")
elif n % 3 == 0:
print("fizz")
elif n % 5 == 0:
print("buzz")
n = n + 1
return number
print(fizzbuzz(number))
If number = 16 it outputs
Enter a number: 16
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
16
How do I get I remove the last number 16, as it isn't supposed to be there

print("buzz")
n = n + 1
return number
print(fizzbuzz(number))
Here's your problem. Don't return the number, and don't print the return value of the function.
print("buzz")
n = n + 1
fizzbuzz(number)

Related

How to format file output into specific number of data columns?

I'm just asking a quick question on how to format how numbers are presented in a text file with however many columns I want.
ie.)
1 3 4
2 6 10
3 18 6
As of right now my text file is just writing a new line for ever iteration and I'm having trouble figuring out how to get it to right a new line after 3 iterations of the calculation.
for Number in range(1, 10001):
count = 0
for i in range(2, (Number // 2 + 1)):
if Number % i == 0:
count = count + 1
break
if count == 0 and Number != 1:
file.write(str(Number) + "\n")
You could track the count of numbers written to file, and each multiple of three, write a newline.
output_count = 0
for Number in range(1, 10001):
count = 0
for i in range(2, (Number // 2 + 1)):
if Number % i == 0:
count = count + 1
break
if count == 0 and Number != 1:
file.write(f'{Number} ')
output_count += 1
if output_count % 3 == 0:
file.write("\n")
Code Refactor
It is recommended to refactor the code into functions that tackle pieces of the problem, such as calculating primes versus input/output. For example, in Python 3, you could write the following:
from typing import List
def generate_primes(maximum: int) -> List[int]:
primes = []
for n in range(1, maximum):
count = 0
for i in range(2, (n // 2 + 1)):
if n % i == 0:
count = count + 1
break
if count == 0 and n != 1:
primes.append(n)
return primes
def write_to_file(filename: str, data: List[int], columns: int) -> None:
with open(filename, 'w') as file:
output_count = 0
for n in data:
output_count += 1
if output_count % columns == 0:
file.write(f"{n}\n")
else:
file.write(f"{n} ")
if __name__ == "__main__":
data = generate_primes(10001)
write_to_file("primes.txt", data, columns=3)
Output
2 3 5
7 11 13
17 19 23
29 31 37
41 43 47
53 59 61
67 71 73
79 83 89
...

How do I print out each iteration of the for loop in Python?

I'm trying to print out each iteration but instead it's printing out the last value as many times as the input. How do I fix it?
Code 1:
for i in range (1,n+1):
if n % 3 == 0 and n % 5 != 0:
print("Fizz")
if n % 5 == 0 and n % 3 != 0:
print("Buzz")
if n % 3 == 0 and n % 5 == 0:
print("FizzBuzz")
If I input 15, for example, it prints out "FizzBuzz" 15 times. I want it to print out something like this:
Sample Output:
1, 2, Fizz, 4, ..., Fizzbuzz
All you need are a couple minor modifications:
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 != 0:
print("Fizz")
elif i % 5 == 0 and i % 3 != 0:
print("Buzz")
elif i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
else:
print(i)
You were making the mathematical tests against n, not i.

My output keeps on repeating itself? (Python)

so i'm creating this function that gets a user to input a number greater than 2.
The code should then print all the prime numbers starting from 2 and ending at the number the user inputted.
So here is my code and it works (yay!)
def enterNumber():
number = int(input("Enter a number greater than 2"))
lower = 2
upper = number
for number in range (lower, upper):
if number > 2:
for i in range (2, number):
if (number % i) == 0:
break
else:
if (number % i) != 0:
print(number)
enterNumber()
BUT here is my output if the user inputs 18
"Enter a number greater than 2"
user puts "18"
output: 3
5
5
5
7
7
7
7
7
9
11
11
11
11
11
11
11
11
11
13
13
13
13
13
13
13
13
13
13
13
15
17
17
17
17
17
17
17
17
17
17
17
17
17
17
17
why is my output repeating itself? Any suggestions would be greatly appreciated thanks!
Your problem is here:
for i in range (2, number):
if (number % i) == 0:
break
else:
if (number % i) != 0:
print(number)
The else being inside the loop, says that you're going to print the number every time you find a non-divisor. For instance, for number = 11, you will print 11 for i values 2-10.
You don't know whether the number is a prime until you are done with the loop. Your print has to go after the loop, on a normal exit. An often-forgotten language feature is that a loop can have an else for exactly this purpose.
for i in range (2, number):
if (number % i) == 0:
break
else:
print(number)
Output:
Enter a number greater than 218
3
5
7
11
13
17
A simple solution(there are better ways):
def enterNumber():
number = int(input("Enter a number greater than 2"))
lower = 2
upper = number
for number in range(lower, upper):
prime = True
for i in range(2, number):
if (number % i) == 0:
prime = False
break
if prime:
print(number)
enterNumber()

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

find all prime numbers from given range python

Output should be as follows:
Give the lower bound of the number range: 0
Give the upper bound of the number range: 1
0 cannot be prime.
1 cannot be prime.
Could not find primes from the test range.
Give the lower bound of the number range: 0
Give the upper bound of the number range: 20
0 cannot be prime.
1 cannot be prime.
2 is a prime.
3 is a prime.
4 is not a prime, because 2 * 2 = 4
5 is a prime.
6 is not a prime, because 2 * 3 = 6
7 is a prime.
8 is not a prime, because 2 * 4 = 8
9 is not a prime, because 3 * 3 = 9
10 is not a prime, because 2 * 5 = 10
11 is a prime.
12 is not a prime, because 2 * 6 = 12
13 is a prime.
14 is not a prime, because 2 * 7 = 14
15 is not a prime, because 3 * 5 = 15
16 is not a prime, because 2 * 8 = 16
17 is a prime.
18 is not a prime, because 2 * 9 = 18
19 is a prime.
20 is not a prime, because 2 * 10 = 20
Searched 21 numbers, from which 8 were primes.
The last found prime was 19.
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low,high):
if n<2:
print (n, "cannot be prime.")
for n in range(low,high):
for x in range (2, n):
if n % x == 0: # is n divisible with x? If yes, not a prime
y = n//x*x
print(n, "is not a prime, because", x, "*", n//x, "=", y)
break #this breaks the inner loop, and we continue with the outer!
else:
print(n, "is a prime.")
break
The code is not successfully running
It shows the output:
Give the lower bound of the number range: 0↩
Give the upper bound of the number range: 20↩
0 cannot be prime.↩
1 cannot be prime.↩
3 is a prime.↩
4 is not a prime, because 2 * 2 = 4↩
5 is a prime.↩
6 is not a prime, because 2 * 3 = 6↩
7 is a prime.↩
8 is not a prime, because 2 * 4 = 8↩
9 is a prime.↩
10 is not a prime, because 2 * 5 = 10↩
11 is a prime.↩
12 is not a prime, because 2 * 6 = 12↩
13 is a prime.↩
14 is not a prime, because 2 * 7 = 14↩
15 is a prime.↩
16 is not a prime, because 2 * 8 = 16↩
17 is a prime.↩
18 is not a prime, because 2 * 9 = 18↩
19 is a prime.
You are not checking if n is divisible by all numbers between 2 and n, since you exit the inner for loop after the first iteretion in both cases (when n divisible by x and when it is not).
To fix it, you need to move the else block to the outer loop (so it will run only when you don't exit the loop, meaning n is prime), and only break when n is not prime.
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low,high):
if n<2:
print (n, "cannot be prime.")
for n in range(low,high):
for x in range (2, n):
if n % x == 0: # is n divisible with x? If yes, not a prime
y = n//x*x
print(n, "is not a prime, because", x, "*", n//x, "=", y)
break #this breaks the inner loop, and we continue with the outer!
else:
print(n, "is a prime.")
try to use this one works for 0-20 range
low = input("Give the lower bound of the number range: ")
high = input("Give the upper bound of the number range: ")
low = int(low)
high = int(high)
for n in range(low, high+1):
if n <= 1:
print(n, "cannot be prime")
elif n == 2 or n == 3:
print(n, "is a prime")
elif n % 2 == 0 or n % 3 == 0:
print(n, "is not a prime")
else:
print(n, "is a prime")

Categories