Function keeps doing the same thing - python

This program suppose to find 1000 prime numbers and pack them into a list
Here's the code:
num = raw_input('enter a starting point')
primes = [2]
num = int(num)
def prime_count(num):
if num % 2 == 0: #supposed to check if the number is divided by 2 evenly
num = num +1 #if it is, then add 1 to that number and check again
return num
elif num % num == 0:
primes.append(num) #supposed to add that prime to a list
num = num + 1 #add 1 and check again
return num
while len(primes) <= 999:
prime_count(num)
So what actually happens when I run it:
it asks me raw_input and then goes to various things depending on what I choose as input:
If I choose a prime, let's say 3, it runs and adds 999 of 3s to the list instead of adding it just one time and going on to try 4
If I choose a non-prime, let's say 4, it just breaks, after that I can't even print out a list
What am i doing wrong?
UPDATE:
I fixed it, but when i run it with this i'm getting an error (TypeError: unsupported operand type(s) for %: 'NoneType' and 'int')
number = raw_input('enter a starting point')
primes = [2]
number = int(number)
def prime_count(x):
if x % 2 == 0: #supposed to check if the number is divided by 2 evenly
number = x +1 #if it is, then add 1 to that number and check again
return number
else:
for i in range(3, x-1):
if x % i == 0:
primes.append(x) #supposed to add that prime to a list
number = x + 1 #add 1 and check again
return number
while len(primes) <= 999:
number = prime_count(number)

You're never using the return value from prime_count. Try this:
while len(primes) <= 999:
num = prime_count(num)
You've set your self up for confusion by using the name num as both a parameter (also a local variable) inside of prime_count, and also as a global variable. Even though they have the same name, they are different variables, due to Python's rules for the scope of variables.
Also, prime_count is (probably unintentionally) leveraging the fact that primes is a global variable. Since you're not assigning to it, but rather just calling a method (append), the code will work without using the global keyword.
However, your algorithm isn't even correct. if num % num == 0 says "if a number divided by itself has a remainder of zero" which will always be true. This program will find a lot of "primes" that aren't primes.
Real Python programs do very little in the global scope; your current code is just asking for confusion. I suggest you start with this template, and also do some reading of existing Python code.
def add_three(a_param):
a_local_var = 3 # This is *different* than the one in main!
# Changes to this variable will *not* affect
# identically-named variables in other functions
return a_local_var + a_param
def main():
a_local_var = 2
result = add_three(a_local_var)
print result # prints 5
if __name__ == '__main__':
main()

Related

alternative to if else python

Ok i wrote this in python then rewrote because i don't like if else statements.
the first version worked perfectly. my second one failed and ended up taking more lines than my first version. my question is, am i just stupid? is there a better way to do this or should i just accept the need for if else statement?
sorry for the code dump, i am going mad
first attempt
#number we are starting with
num = 1
#what we are going to apply equation loop to
result = num
#how many times goes through equation loop before reaching 1
count = 0
# list of numbers used in equation loop
num_in_loop = [result]
#end equation loop function.
running = True
# equation loop
def eqation_loop(running, num_in_loop, count, num, result):
while running == True:
if (result % 2) == 0:
result = result /2
count +=1
num_in_loop.append(result)
elif result == 1.0:
print(num, "took", count ," loops to get to 1: numbers in loop = ", num_in_loop, file=open('3x+1/result.txt','a'))
num +=1
print(num)
result = num
num_in_loop = [result]
count = 0
elif num == 100:
running = False
elif (result % 2) != 0:
result = result * 3 + 1
count +=1
num_in_loop.append(result)
eqation_loop(running, num_in_loop, count, num, result)
second attempt:
#number we are starting with
num = 1
#what we are going to apply equation loop to
result = num
#how many times goes through equation loop before reaching 1
count = 0
# list of numbers used in equation loop
num_in_loop = [result]
limit = int(input("range you want to try: " ))
def update_var(num_in_loop,result,count):
count +=1
num_in_loop.append(result)
return equation_loop(limit,num, result)
def reset_var(num_in_loop, count, limit,num, result):
print(num, "took", count ," loops to get to 1: numbers in loop = ", num_in_loop, file=open('3x+1/test.txt','a'))
num +=1
result = num
num_in_loop = [result]
count = 0
return equation_loop(limit,num, result)
def equation_loop(limit,num, result):
if num == limit:
return
elif result == 1:
return reset_var(num_in_loop, count, limit,num, result)
elif (result % 2) == 0:
result = result /2
return update_var(num_in_loop,result,count)
elif (result % 2) != 0:
result = result *3 +1
return update_var(num_in_loop,result,count)
equation_loop(limit,num, result)
You can't write this without any if/else statements (okay maybe if you really know what you're doing you technically can by severely abusing while, but you shouldn't), but here's a simplified-down version that hopefully contains some useful examples of how to make your code easier to write (and read!):
def equation_loop(num: int) -> list[int]:
"""
Repeatedly applies the magic equation trying to
reach 1.0, starting with num. Returns all the results.
"""
nums = [num]
while True:
if num == 1:
return nums
if num % 2:
num = num * 3 + 1
else:
num = num // 2
nums.append(num)
for num in range(1, 100):
results = equation_loop(num)
print(f"{num} took {len(results)} loops to get to 1: {results}")
A key thing here is that you don't need so many variables! A single loop only needs its starting point (num) and only needs to return the list of results (from which you can get the count, since it'll be the length of the list). Reducing the number of redundant variables eliminates a lot of unnecessary lines of code that are just copying state back and forth. Passing a value like running = True is unnecessary when it will always be True until it's time to end the loop -- instead just use while True: and return or break when you're done.
The big takeaway is that if you have two variables that always have the same value (or even two values that are always related in exactly the same way, like a list and its length), you probably just need one of them.
You can also simplify the code by separating the two nested loops -- for a given num you want to loop until the number reaches 1, so that's one loop. You also want to loop over all the nums up to 99 (it took me a while to even figure out that that's what the code was doing; I had to run it and look at the output to see that some of those extra pieces of state were serving to implement nested loops inside a single loop). Doing those in two different loops makes it easy, and you can put one of them in a nice neat function (I used your equation_loop name for that, although it does less work than your original version does) that takes the starting num and returns the list of results for that starting point. That simple function can then be called in an even simpler for loop that iterates through the nums and prints the results for each one.
Note that I kept everything as ints by using int division (//) -- testing floats for exact equality is often dangerous because floating point numbers aren't exactly precise! Your equation is always operating with integer values (because you only divide by two if it's an even number) so it makes more sense to use int division and not even worry about floating point values.

About a function on Python

I'm a absolute beginner, and when I made a function to count the number of even ints on a given list, it didn't went as expected, and I can't see where I'm doing it wrong.
nums = [2,2,4,4,5,6,7,8,9]
def count_even(nums):
for number in nums:
num = 0
if number % 2 == 0:
num += number
return num
else:
continue
The output is:
count_even(nums)
2
It stops on nums[1] for some obscure reason.
Or it just prints the first "2" and adds it, and I don't know how to fix it, yet.
You have three problems here.
You're setting num = 0 every time through the loop, instead of just once at the start. So you're only going to get the very last count that you do.
You're doing num += number, instead of num += 1, so instead of counting the even numbers, you're adding them.
You're doing a return num as soon as the first even number is found, instead of only at the end of the function, after the loop. (And that also means that if there are no even numbers, instead of returning 0, you return None).
While we're at it, you don't need else: continue, because continuing is already what happens by default when you fall off the end of a loop.
Anyway, this means it's not stopping at nums[1], it's stopping at nums[0]—but it's adding 2 instead of 1 there, which makes things confusing. (It's always fun when bugs interact like that. Even more fun when they happen to exactly cancel out for your test case, like if you did nums = [6,2,4,4,5,6,7,8,9] and got back 6 and thought everything was working…)
So:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += 1
return num
Your function stops on nums[1] because the return keyword exits the function and returns num (which is set to 0 + number). If you want to print out the sum of all the even numbers in nums you could move the return statement to the end and take the num = 0 expression out of the for loop (because it will reset to 0 after each iteration), like this:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += number
else:
continue
return num
Also, your else statement is redundant here, so you could simply remove it, leaving you with the following:
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += number
return num
And you could simplify that further to:
def count_even(nums):
evens = [number for number in nums if number % 2 == 0]
return sum(evens)
Another solution:
def count_even(nums):
return len([i for i in nums if i % 2 == 0])
There are a couple of problems in your code:
Your num needs be defined outside the loop, so you can count every even number found. If you define it inside the loop, it resets to 0 every iteration.
When you find an even number, you increment it towards the counter num. You need to instead increment num by 1.
You return immediately when a even number is found, this means the function exits on the first even number. You instead want to return the total num at the end.
You have an unnecessary continue in the else block. If a uneven number is found, simply ignore it.
Which these suggestions, you could implement your code like this:
nums = [2,2,4,4,5,6,7,8,9]
def count_even(nums):
num = 0
for number in nums:
if number % 2 == 0:
num += 1
return num
print(count_even(nums))
# 6

Python 3. How do you assign a variable in a function to use in the outer scope of the function?

I am extremely new to programming. I have been working on a project where the user is asked to import a number, which goes through a mathematical series. The output is then put into a function to find the factors of the number. From there I am trying to find the factors that are prime numbers?
This is what i have so far.
enter code here####################################
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)
#####################################
# Factors
#function name nfactors
def nfactors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
fact = nfactors(num)
print(fact)
#####################################
print('The prime numbers are:')
if fact > 1:
# check for factors
for i in range(2,fact):
if (fact % i) == 0:
break
else:
print(fact)
I know this is bad programming but I am trying to learn through doing this project. How can I then take the factors I received as the output of the function and find which factors are prime numbers. I cannot figure out how to name a variable inside the function and use that outside the function, I don't know if this is even possible. If you need any clarifications please let me know. Thanks for any help.
def nfactors(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
for i in range(1, x + 1):
if x % i == 0:
print(i)
return i
fact = nfactors(num)
Use the return keyword to return the value of i or whatever it is you would like to use outside of the function!
I seriously hope that you are trying to find the factors of n instead of num as finding the factors of num for a mere number n=12 is a great deal and it'll take several minutes or even hours even with my optimized code.
Anyway assuming you want to find it for n and not num the below code should do your job.
In case you really want to find factors for num, this code will work fine for that too but it'll take too much time. Just change factors = factors(n) to factors = factors(num).
from math import sqrt
#Block 1 (Correct)
n = int(input("Enter the n value"))
num = sum(10**x for x in range(n))
print("S",n,"is", num)
#---------------------------------------------------
def factors_(x):
# This function takes a number and prints the factors
print("The factors of",x,"are:")
list_of_factors = []
for i in range(1, x + 1):
if x % i == 0:
list_of_factors.append(i)
return(list_of_factors) #This returns a list of factors of a given number x
factors = factors_(n) #I am assuming you want to find the prime factors of n instead of num
print(factors)
#------------------------------------------------------------------------------------
def is_prime(num): #This function returns True(1) if the number is prime else Flase(0)
if num == 2:return 1
if num%2 == 0:return 0
i = 3
while i < int(round(sqrt(num)) + 1):
if num % i == 0:return 0
i += 2
return 1
#---------------------------------------------------------------------------------------
prime_factors = []
for i in factors:
if is_prime(i):
prime_factors.append(i)
print("The prime factors of the numbers are:")
print(prime_factors)

Collatz sequence - Have I done it right?

I am now learning how to program in python and the book I am learning from gave me the practice project to build this sequence and place it in a loop until the value is 1.
My code looks like this:
print('Enter a number')
number = input()
num = number
def collatz(number):
global num
if int(num) % 2 == 0:
num = int(num) // 2
print(str(num))
elif int(num) % 2 == 1:
num = 3 * int(num) + 1
print(str(num))
while num != 1:
number = num
collatz(number)
It works, but I am not sure if I've done it in the way I should've.
My issue was that I was using number both as a global variable and a parameter and when I first write the code every 'num' was called 'number', when first testing it it would enter an endless loop and repeat the first if or elif all over again. I figured that the problem is that it doesn't refer to the global variable but creates a local one, so I've tried to declare at the beginning to use the global one, as you can see, however it didn't let me as global variable and parameter can't be the same, so I've created the 'num' variable and assigned it to the if block, but now it looks like that the number parameter doesn't really interfere with my code.
The fact that it works makes me happy, however I would like to confirm this is right.
There are a few things I'd suggest you fix.
No need for a separate print for input. Also might as well cast it to int now.
number = int(input('Enter a number'))
Get rid of the global and use return. Also get rid of your casting in your function.
See:
def collatz(n): # parameter is an int
if n % 2 == 0:
n = n // 2
elif n % 2 == 1:
n = 3 * n + 1
print(n) # single print
return n
So combined:
def collatz(n):
if n % 2 == 0:
n = n // 2
elif n % 2 == 1:
n = 3 * n + 1
print(n)
return n
number = int(input('Enter a number'))
while number != 1:
number = collatz(number)

Python Code to Find x Prime Numbers w/ For Loop?

I am trying to put together a simple program which could work out n prime numbers. I would like to do this by using a nested for loop, where one would go through the numbers, and another would divide that number by all of the numbers up to it to see if it would be divisible by anything.
The problem I am having is that in the main for loop, I need to start it at 2, seeing as 1 would mess up the system and I don't want it to be considered a prime. For the loop to have a starting number however, it also needs an ending number which is difficult in this instance as it is hard to generate the largest prime that will be needed prior to the loop working.
Here's the program that I am using right now. Where I have marked X is where I need to somehow put an ending number for the For Loop. I guess it would be much simpler if I let the For Loop be completely open, and simply take out anything that '1' would produce in the loop itself, but this feels like cheating and I want to do it right.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in range(2,X):
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
Thanks for your help!
You can step through an unlimited amount of numbers using a generator object.
Insert the following somewhere near the top of your code:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
What this does is it creates a function for constructing generator objects that "pause" whenever they reach the yield statement to "yield" whatever value is specified by the yield command, and then continue to execute from the next line beneath the yield statement.
Python's own range function is itself an example of a generator, and is roughly equivalent to (ignoring the step argument and other peculiarities)
def range(start, end):
i = start
while i < end:
yield i
i += 1
So your program would then look like this:
def infinite_number_generator(initial_value=2):
""" Generates an infinite amount of numbers """
i = initial_value
while True:
yield i
i += 1
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
for i in infinite_number_generator():
check = 0
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
print (i)
if i == limit:
break
I should also point out that the code you provided is buggy - it will never stop printing because there's no checking whether you've found your limit number of primes yet or not.
This should do what you want.
check = 0
limit = int(input("Enter the amount of Prime Numbers"))
counter = 0
i = 2
while counter < limit:
check = 0
if i > 1:
for j in range(2,i):
if (i % j) == 0:
check = 1
if check == 0:
counter += 1
print (i)
i += 1
In your code you start i with 2 and always increment by 1, so the i will always remain greater than 1, therefore the test if i > 1 is useless.
For efficiency you can stop the check at the square of i or i/2 (no divisors in [i/2 + 1, i[ ).
you can update your code as follow:
n = int(input("Enter the amount of Prime Numbers: "))
FoundPrimes = 0
i = 2
while FoundPrimes < n:
isPrime = True
for j in range(2,1 + i//2):
if (i % j) == 0:
isPrime = False
if isPrime:
FoundPrimes += 1
print(i, end = '\t')
i += 1

Categories