I am making a quick program that will ask the user for a number and then output all the prime numbers up to that number:
n=int(input("Enter a number: "))
a=2
if n<=1:
n=int(input("Enter another number: "))
while a<n:
for i in range(2,n):
if a%i==0:
break
else:
print (a)
break
a=a+1
The problem I am having is that it won't print out 2. For example, if I use 20 as my n value, it will print:
Enter a number: 20
3
5
7
9
11
13
15
17
19
You have two mistakes:
The else is incorrectly indented, so it sits with the if not the for (you want to print if all values below a aren't factors of a, not on the first one that isn't); and
Your inner range goes up to n, not a (so always includes a, and a % a == 0).
This will work:
for a in range(2, n):
for i in range(2, a):
if a % i == 0:
break
else:
print(a)
Note I have used a for loop to replace the outer while, which is generally better when you already know where to stop. You can make the code more efficient by checking up to the square root of a, and leaving out even numbers other than 2, but I will leave those optimisations to you.
You can start the loop from 1.
Your loop will start from 1, hence you will get 2 in output.
Related
I'm a complete novice at python and am trying to list the first n positive numbers, where n is an inputted value. E.g. when n=5, I want to output 5, 4, 3, 2 and 1.
This is my code which doesn't work:
n= int(input("Please enter a number: "))
i=0
while i<n:
print(n)
n=n-1
i=i+1
I know I can answer the question with this code:
n= int(input("Please enter a number: "))
i=n
while i>0:
print(i)
i=i-1
but would like to understand why what I tried at the beginning is not working.
You are decrementing the number and incrementing the counter at the same time.
For example:
n
i
i<n
5
0
True
4
1
True
3
2
True
2
3
False
The loop exits once False is encountered. To solve this you need to only increment i and use print(n-i), keep the i<n comparison, and remove the 'n=n-1' line
n= int(input("Please enter a number: "))
i=0
while i<n:
print(n-i)
i=i+1
Because, you are decreasing n and increasing i, so at some point the while condition will not satisfy anymore, it has got nothing to do with python.
The output shows a different result. Yes, the factorials of those numbers are right but the numbers outputted aren't right.
Here's the code:
input:
n = int(input("Enter a number: "))
s = 0
fact = 1
a = 1
for i in range(len(str(n))):
r = n % 10
s += r
n //= 10
while a <= s:
fact *= a
a += 1
print('The factorial of', s, 'is', fact)
Output:
Enter a number: 123
The factorial of 3 is 6
The factorial of 5 is 120
The factorial of 6 is 720
You're confusing yourself by doing it all in one logic block. The logic for finding a factorial is easy, as is the logic for parsing through strings character by character. However, it is easy to get lost in trying to keep the program "simple," as you have.
Programming is taking your problem, designing a solution, breaking that solution down into as many simple, repeatable individual logic steps as possible, and then telling the computer how to do every simple step you need, and what order they need to be done in to accomplish your goal.
Your program has 3 functions.
The first is taking in input data.
input("Give number. Now.")
The second is finding individual numbers in that input.
for character in input("Give number. Now."):
try:
int(character)
except:
pass
The third is calculating factorials for the number from step 2. I won't give an example of this.
Here is a working program, that is, in my opinion, much more readable and easier to look at than yours and others here. Edit: it also prevents a non numerical character from halting execution, as well as using only basic Python logic.
def factorialize(int_in):
int_out = int_in
int_multiplier = int_in - 1
while int_multiplier >= 1:
int_out = int_out * int_multiplier
int_multiplier -= 1
return int_out
def factorialize_multinumber_string(str_in):
for value in str_in:
print(value)
try:
print("The factorial of {} is {}".format(value, factorialize(int(value))))
except:
pass
factorialize_multinumber_string(input("Please enter a series of single digits."))
You can use map function to get every single digit from number:
n = int(input("Enter a number: "))
digits = map(int, str(n))
for i in digits:
fact = 1
a = 1
while a <= i:
fact *= a
a += 1
print('The factorial of', i, 'is', fact)
Ok, apart from the fact that you print the wrong variable, there's a bigger error. You are assuming that your digits are ever increasing, like in 123. Try your code with 321... (this is true of Karol's answer as well). And you need to handle digit zero, too
What you need is to restart the calculation of the factorial from scratch for every digit. For example:
n = '2063'
for ch in reversed(n):
x = int(ch)
if x == 0:
print(f'fact of {x} is 1')
else:
fact = 1
for k in range(2,x+1):
fact *= k
print(f'fact of {x} is {fact}')
help me please.
Write a function: User enters natural numbers A and B (A <B). The function prints all prime numbers separated by a space on the segment [A, B]
This is my code but it doesn't work, wrong output, I don't understand why?
def prime_numbers(a, b):
for i in range(a, b + 1):
dividers = 0
for j in range (2, i):
if i % j == 0:
dividers += 1
if dividers == 1:
return i
a = int (input ("Enter first number: ")
b = int (input ("Enter second number: ")
print (prime_numbers (a, b))
When this code is e.g. ran with a=5 and b=11 I expect the output to be 5 7 11. Instead the output is 6.
Problems with Logic
The function you wrote is meant to calculate how many dividers are in the numbers from a-b, which is different than what the prompt is asking.
You're on the right track with the loops and the % (mod) if statement, but you're off by a bit. In order to calculate the number of prime numbers, there are through a-b, you're going to have to do something different because right now I think your code is calculating the number of divisors there are for numbers a-b.
Problems with Code
When you use the keyword return, you return a value for the entire function and considering you're calculating for multiple prime numbers, I don't think that'd work out well.
Also, I'd be sure to watch out for proper tabbing, your tabbing is inconsistent, and sometimes you've used spaces, sometimes you've used tabs. Python doesn't use brackets (languages such as C, C++, Java, JavaScript aren't reliant on tabs) and is reliant on consistent spacing/tabbing.
Don't forget to close the brackets for the int() function, which is meant to convert a string to an integer.
I think what you meant to do is this:
def prime_numbers(a, b):
primes = [] # Make a list of primes
for i in range(a, b + 1): # Iterate from a-b
if is_prime(i): # Check if the number is a prime or not
primes.append(i) # If it is a prime, then add it to the list
return primes # Return the prime list
def is_prime(v): # Function to check for prime numbers
for x in range(2, v): # Iterate from 2 to the input value
if v % x == 0: # Check if v is divisible by x
return False # If it is divisible by x, return False becaues it's not a prime number
return True # Haven't found any divisors for the number, so return True.
a = int (input ("Enter first number: "))
b = int (input ("Enter second number: "))
print (prime_numbers (a, b))
I'd suggest you use websites such as YouTube and W3Schools to get a better understanding of how to code and remember, GOOGLE IS YOUR FRIEND.
Edit: My apologies, the tabbing issue was caused due to my IDE (Sublime), but it's still a good thing to keep in mind when working with Python.
p=[]
l=[]
v="run"
a=int(input("enter num or end: "))
while v!="end":
l.append(int(a))
a=input("enter num or end: ")
v=a
for a in l:
f=0
for j in range(2,a//2):
if a%j == 0:
f=1
break
if f==0:
p.append(a)
here I am inputting numbers and if its a prime number then I am putting it to list 'p' and at last output p.
i cant understand why 1st if statement not working when I am providing an even number like in picture below 4 is inputed so it should have changed value of f to 1 so that it doesn't get into list 'p' but its not. i am very new to python so there is possibility of silly mistakes.
on left code, on right output
The issue is that range(2, 4//2) is an empty range, since 4//2 = 2, and range(2, 2) includes every integer less than 2, starting with 2 - which is to say, no integers.
You will not have this issue with test numbers greater than 4, since in those cases you will always have at least 2 in the range of potential factors that you're testing.
It is because for 4 your statement:
for j in range(2, n//2):
becomes for j in range(2,2). if you have the same start and end in a range it does nothing. So it does not do the a % j and does not change f. In any case, if you are trying to check whether it is a prime number the range should be (2, int(n**0.5))
Have a little problem. I'm writing a simple program that takes an input of numbers (for example, 1567) and it adds the odd numbers together as well as lists them in the output. Here is my code:
import math
def oddsum(n):
y=n%10
if(y==0):
return
if(y%2!=0):
oddsum(int(n/10))
print (str(y),end="")
print (" ",end="")
else:
oddsum(int(n/10))
def main():
n=int(input("Enter a value : "))
print("The odd numbers are ",end="")
oddsum(n)
s = 0
while n!=0:
y=n%10
if(y%2!=0):
s += y
n //= 10
print("The sum would be ",end=' ')
print("=",s)
return
main()
It outputs just fine, in the example it will print 1 5 and 7 as the odd numbers. However, when it calculates the sum, it just says "7" instead of 13 like it should be. I can't really understand the logic behind what I'm doing wrong. If anyone could help me out a bit I'd appreciate it :)
I understand it's an issue with the "s += y" as it's just adding the 7 basically, but I'm not sure how to grab the 3 numbers of the output and add them together.
As #Anthony mentions, your code forever stays at 156 since it is an even num.
I would suggest you directly use the string input and loop through each element.
n = input("Enter a value : ") #'1567'
sum_of_input = sum(int(i) for i in n if int(i)%2) #1+5+7=13
[print(i, end="") for i in n if int(i)%2] #prints '157'
Note that int(i)%2 will return 1 if it is odd.
1567 % 10 will return 7. You might want to add the numbers you printed in oddsum to a list, and use the sum function on that list to return the right answer.
The immediate issue is that n only changes if the remainder is odd. eg 1,567 will correctly grab 7 and then n=156. 156 is even, so s fails to increment and n fails to divide by 10, instead sitting forever at 156.
More broadly, why aren't you taking advantage of your function? You're already looping through to figure out if a number is odd. You could add a global parameter (or just keep passing it down) to increment it.
And on a even more efficient scale, you don't need recursion to do this. You could take advantage of python's abilities to do lists. Convert your number (1567) into a string ('1567') and then loop through the string characters:
total = 0
for c in '1567':
c_int = int(c)
if c_int%2!= 0:
total += c_int
print(c)
print(total)