When I run this code and give input as 25 it should return me its not a prime num,
But when I debug the code the range values are not iterating into if condition, only the first value of the range is passed and if its not == 0 it moves to the else part.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
else:
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Please help me why its working like this , I am new to programming . TIA
As stated in a comment, this is an easy fix. Simply move the else statement's return to outside of the loop.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. use print instead.
I discovered that for whatever reason for loops never run with the final value an easy fix is to just add 1 to the ending value.
Related
There is a problem with odd numbers.
When I run the function on even numbers, the code works.
#recursive demo function1
#Even nums
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
if num == 2:
return num
else:
return evenNum(num-2)
evenNum(5)
output : Canceled future for execute_request message before replies were done
The second if should be changed to elif. When number is odd it prints "Enter a even number" and then compares it to 2. As it is different, it calls the function again.
Here is fixed code
def evenNum(num):
if num % 2 != 0:
print("enter a even number")
elif num == 2:
return num
else:
return evenNum(num-2)
evenNum(5)
Btw. make sure the number is greater than 0.
#recursive function1
#positive Even nums
def evenNum(num):
print(num)
if num % 2 != 0:
return print("enter an even number")
elif num == 2:
pass
else:
return evenNum(abs(num)-2)
evenNum(5)
Thank you for your valuable advice.
I learned some things about return and kern error.
I’m trying to write a program that has while true: at the start and then at the end asks the user if they want to repeat.
While True:
print(“I will list the prime numbers between 0 and N”)
N=input(“up to what number will I list the prime numbers?”)
print (“prime numbers between 0 and”,N,” are:”)
for no in range (2,N)
if no>1:
prime=True
for i in range (2, no):
if (no % i) == 0:
prime=False
break
if prime:
print(no)
print(“would you like to enter a new range?”)
response= input(“Enter yes or press enter key to exit”)
if response == yes:
True
But no matter what is entered it keeps repeating
I tried adding an
else:
break
But it would say break away out of the loop of
I’m not sure what to do
Here's a fixed version, with fixes commented:
while True: # needs to be 'while', not 'While'!
print("I will list the prime numbers between 0 and N") # use regular "", not “”
N = int(input("up to what number will I list the prime numbers?")) # make it an int!
print("prime numbers between 0 and", N, "are:")
for no in range(2, N): # need a : to start the for loop
# no starts at 2, so it will always be >1. No "if" needed.
prime = True
for i in range(2, no):
if no % i == 0:
prime = False
break
if prime:
print(no)
print("would you like to enter a new range?")
response = input("Enter yes or press enter key to exit")
if response != "yes": # need quotes around "yes" to make it a string
break
# loop automatically continues if not broken
The part that's directly pertinent to your original question is at the very end -- what you want to do is break the loop if it's time to stop the program (i.e. if they didn't enter "yes"). If not broken, the loop will continue automatically since it's in a while True:.
This part:
prime = True
for i in range(2, no):
if no % i == 0:
prime = False
break
if prime:
print(no)
can also be written more simply as:
for i in range(2, no):
if no % i == 0:
break
else:
print(no)
The else: block after a for: is executed at the end of the loop, but only if it's not stopped early with a break; you can therefore use it for cases like this where you want to test a bunch of conditions, stop the loop if one of them is true, and do something else otherwise.
This is such a common use case that there's an even simpler way to do it, using the built-in all function:
if all(no % i for i in range(2, no)):
print(no)
Here the all function tests that all elements of the iterable are true (note that no % i is considered "truthy" as long as it doesn't equal zero), and returns True or False accordingly.
Instead of using True as the while condition, use a variable as the condition such as:
while run
If you use True as the while condition True will always be true, so you have to use a variable in order for it to change.
Updated Code
run = True
While run:
print(“I will list the prime numbers between 0 and N”)
N=input(“up to what number will I list the prime numbers?”)
print (“prime numbers between 0 and”,N,” are:”)
for no in range (2,N)
if no>1:
prime=True
for i in range (2, no):
if (no % i) == 0:
prime=False
break
if prime:
print(no)
print(“would you like to enter a new range?”)
response= input(“Enter yes or press enter key to exit”)
if response == yes:
run = True
else
run = False
For an assignment for class, I am needing to create a program that returns if a number is even or odd, while having the main function get user input and displays the output, while another function checks whether the number is even or odd. My python knowledge so far is very basic.
Here is what I've got so far.
def check(number):
if (number % 2) == 0:
return True
else:
return False
def main():
number = int(input("Enter an integer: "))
if check is True:
print("This is an even number.")
elif check is False:
print("This is an odd number.")
__name__ == "__main__"
main()
When I run the code, I get the input prompt, but nothing in return after.
check is a function, so it should be like
if check(number):
print("This is an even number.")
else:
print("This is an odd number.")
Python is very flexible, you don't even need a function.
I would take advantage of f-strings and a ternary:
number = int(input("Enter an integer: "))
print(f'This is an {"odd" if (number % 2) else "even"} number')
Example:
Enter an integer: 2
This is an even number
Enter an integer: 3
This is an odd number
As you are basic this is not the best function for check using bool.
def check(num):
return num % 2 == 0 # return True if even otherwise odd
This code is simple and easily to read rapidly.
This question already has answers here:
Why does assigning to my global variables not work in Python?
(6 answers)
Closed 2 years ago.
I let the user input a 3-digit number, and let python throw a random 3-digit number, try to see when the random number can match the input. However, everytime I run it on cmd, it prints 'Python is too tired', which is a statement I set to prevent it from looping infinitely (I really did so, until I added this limitation of attempt times).
import random
my_num = int(input('Type your 3-digit int number: '))
if my_num >= 100 and my_num < 1000:
attempt = 0
my_lottery = []
my_lottery.append(int(num) for num in str(my_num))
def lottery_throw():
lottery = []
i=0
while i<3:
lottery.append(random.randint(1,9))
i+=1
return(lottery)
def check():
global boo
lottery_throw()
if lottery == my_lottery:
boo = 'true'
else:
boo = 'false'
while attempt < 100000:
check()
attempt += 1
if boo == 'true':
print('you win')
print(attempt)
break
elif attempt >= 100000:
print('python is too tired')
break
else:
print('You must enter a 3-digit number.')
Run it on cmd, everytime I run it, it returns 'Python is too tired'
But the number of possible combinations (9C3) is only 84. It's very unlikely that python really didn't throw a correct number. How can I fix this problem?
Errors
Do not use global variables unless you really need them. As you can see, writting to a global variable doesn't work our of the box
012 is a valid 3 digit number
If you append a list to another list you will get a nested list (list inside another list): [[1, 2, 3]]
Why create a list of each digit when you can create the number itself?
for loops should be used for a fixed number of iterations, while loops when a more complex condition is needed to return from the loop.
return should be used without parenthesis as they are redundant (it is not a function)
True and False are booleans, do not use "true" and "false" (strings) to represent them.
if condition return true else return false (in pseudocode) is the same as return condition
for loops also can have an else clause, which only is executed if no break was found.
Solution
import random
my_num = int(input("Type your 3-digit int number: "))
if 0 <= my_num < 1000:
for attempt in range(1, 100001):
if my_num == random.randint(0, 999):
print(f"You win in {attempt} attempts.")
break
else:
print("Python is too tired.")
else:
print("You must enter a 3-digit number.")
I have no idea what you did, but I wasn't able to fix it.
Here is my version incited:
num = input('Type your 3-digit int number: ')
for i in range(100000):
if (("00"+str(random.randint(0,999)))[-3:]) == num:
print("You win on attempt %i"%i)
did_win = True
break
else:print('python is too tired')
I am trying to create a simple program to apply the statement of the Collatz Conjecture to an integer that the user can enter, I have:
def collatz(n):
print n,
if n % 2 ==0:
n = n / 2
elif n == 0:
Print "Collatz Conjecture true for" , 'n'
else:
n = n *3 + 1
input("\n\nInsert a positive integer:")
def collatz(n)
However it is saying there is a syntax error in the line:
Print "Collatz Conjecture true for" , 'n'
I can't see what mistake ther is in this line.
Also as I haven't been able to test it yet, does this look as though it will work ok?
Python is case sensitive. Use "print" not "Print".
Well, your syntax error is that python is case-sensitive, so you need print rather than Print.
But you've got more problems:
'n' prints the string n. I think what you want is n to print the value of the variable (or if not, then you can just make a single string "... true for n").
Finally (I think), in order to run the function collatz, you don't need the def; that's just for the definition.
More problems:
The stopping condition should be n == 1, not n == 0.
You have to recur or iterate, as is you're only making one step.
Check the input, make sure it really is a positive number.
def collatz_steps(n):
steps=0
if n==1:
return 0
else:
while n!=1:
if n%2==0:
n=n/2
steps+=1
else:
n = 3*n+1
steps+=1
return steps