I'm a freshman of Python, and now meet a problem I can't understand. How to recall an input outside of a for loop?
Please some master give me an answer using the following example. Tks!
n=int(input('Please input a number: ')
for i in range(2,n):
if n%i==0:
print('It is not a prime number!', end=' ')
break
else:
print('%d is a prime number!' % n)
Just put another loop around your code. e.g.
while True:
n=int(input('Please input a number: '))
for i in range(2,n):
if n%i==0:
print('It is not a prime number!', end=' ')
else:
print('%d is a prime number!' % n)
break
Is this what you are looking for?
while True:
n=int(input('Please input a number: ')
flag = True
for i in range(2,n):
if n%i==0:
flag = False
break
if flag == True:
print('%d is a prime number!' % n)
break
else:
print('It is not a prime number!', end=' ')
Related
I can't figure out how to execute a condition that check if the user inputs are equal before checking if it is a prime number. My goal is to ask a user to input two prime numbers. And in the 2nd while loop, I want to make sure that the 2nd number is not equal to the first number in order to be checked if it is a prime number
value_P=[]
value_Q=[]
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
while True:
try:
P = int(input("Enter a prime number(P): "))
if is_prime(P):
value_P.append(P)
print("P =", value_P)
break;
else:
print(value_P, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
#2nd while loop
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
You can check if the value of Q is inside the P list using an if statement in the 2nd while loop.
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
#here the code made sure it's prime, next statement checks if the "Q" input was already previously used as the "P" input. If it is, the loop breaks.
if Q in value_P:
break
else:
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
I have started learning python and I am stuck in this code
num=int(input("Enter the number"))
for i in range(2, num):
if num%i==0:
print("Not a prime number")
break
print("Prime Number")
When I enter the number which are not prime, then I am getting output as not a prime number but when I am entering the number that is prime I am getting the output as
Prime number
Prime number
Prime number
Prime number
Prime number
You should only print it once, for example like this:
num = int(input("Enter the number"))
for i in range(2, num):
if num % i == 0:
print("Not a prime number")
break
else:
print("Prime Number")
The loop should check for all numbers and only then print not prime for example like this.
num=int(input("Enter the number"))
for i in range(2, num):
if num%i == 0:
print("Not a prime number")
break
if i > num/2:
print("Prime Number")
break
I would suggest you debug by including print statements that would help a beginner.
check this out :
num=int(input("Enter the number"))
for i in range(2, num//2):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")`
The last statement should be managed carefully in this code. Due to this it print in loop and take care of the tabs you shift.
I'm attempting to make a short program that will return the factorial of a number, which works fine. The only problem I am having is getting the program to end if the user inputs a non-integer value.
num = input("input your number to be factorialised here!: ")
try:
num1 = int(num)
except ValueError:
print("That's not a number!")
if num1 < 0:
print("You can't factorialise a negative number")
elif num1 == 0:
print("the factorial of 0 is 1")
else:
for i in range(1,num1+1):
ans = ans * i
print("the factorial of", num, "is", ans)
Solution
There are better ways of doing this but given your code structure you can use else. See the docs.
num = input("input your number to be factorialised here!: ")
try:
num1 = int(num)
except ValueError:
print("That's not a number!")
else:
if num1 < 0:
print("You can't factorialise a negative number")
elif num1 == 0:
print("the factorial of 0 is 1")
else:
ans = 1
for i in range(1,num1+1):
ans = ans * i
print("the factorial of", num, "is", ans)
The else clause only executes if no exceptions are thrown.
Suggestions
So as not to give away answers to your homework, here are a couple suggestions that you should take a look at to clean up your code:
Can you use range more efficiently? Hint: you can iterate over decreasing numbers by setting the step to a negative integer.
Can you find a way to get rid of the check num1 == 0?
The OP is actually asking how to terminate the current script execution prematurely. The straightforward way to implement your idea is to use sys.exit() like
try:
num1 = int(num)
except ValueError:
sys.exit()
For more details, see this thread.
One part of my program displays n amount of prime numbers depending on the user input but no matter what i input it only prints "1"
def listPrimeNumbers():
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
print("\n"*10)
for i in range(1, amountOfNumbers):
prime = True
for i in range(2,i):
if (num%i==0):
prime = False
if prime:
print(i)
print("\n"*10)
print("Type '0' to try again and '1' to go to the main menu")
print("\n"*10)
choice = int(input("Choice ---> "))
if choice == 0:
print("\n"*100)
listPrimeNumbers()
elif choice == 1:
print("\n"*100)
main()
Change your 'for' loop to this:
for num in range(1, amountOfNumbers):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print(num)
num wasn't defined anywhere in your code, I think this is what you meant.
How are you calling your code? As is, I couldn't run it. I managed to run it by adding a call to function listPrimeNumbers() at the bottom.
Anyway, assuming the code you've posted is your entire code, this is the version that worked for me:
import sys
def listPrimeNumbers():
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
print("\n"*10)
for num in range(1, amountOfNumbers):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print(num)
print("\n"*10)
print("Type '0' to try again and '1' to go to the main menu")
print("\n"*10)
choice = int(input("Choice ---> "))
if choice == 0:
print("\n"*100)
listPrimeNumbers()
elif choice == 1:
print("\n"*100)
print 'Bye'
sys.exit(0)
listPrimeNumbers()
If I understand correctly the question, you have a logic flaw in the code since, even with the correction Alex suggested (which works), you just print all the numbers that are prime up to the value the user input and not, as seems to be the question, the quantity the user imput.
For example, given your question, if the user input 10, I understant that you should print the first 10 prime numbers (1,2,3,5,7,11,13,17,19,23) and not the primes up to 10 (1,2,3,5,7)
If my assumption is right, the code should be something like:
import math
def listPrimeNumbers(n):
l = int(math.sqrt(n))+1
if n == 1:
return True
for x in range(2, l):
if (n%x==0):
return False
return True
print("List Prime Numbers")
print("------------------")
print("Enter how many prime numbers you want displayed")
print("Type in '0' to go back to the Main Menu")
print("\n"*10)
amountOfNumbers = int(input("Amount of Numbers --> "))
counter = 0
n = 0
while (counter < amountOfNumbers):
n += 1
if listPrimeNumbers(n) == True:
counter += 1
print(n)
I omitted the part to reiterate the process, so you need to re-run the program to give another try
I'm trying to figure out how to print the final line of code for this - whether it's a prime number or not. I can't seem to get it to print with the code I have. Any help would be appreciated. Thanks!!
number = int(input("Enter a positive number to test: "))
while number <= 0:
print ("Sorry, only positive numbers. Try again.")
number = int(input("Enter a positive number to test: "))
test = 2
number1 = number - 1
for x in range (0, number1):
trial = number % test
if trial != 0:
print (test, "is NOT a divisor of", number, "...")
break
print (number, "is a prime number!")
else:
print (test, "is a divisor of", number, "...")
break
print (number, "is not a prime number!")
test = test + 1
The break statement ends the execution of the branch. The following print statement is never reached.
To get the correct functionaility use a boolean value and perform the check at the end:
is_prime = True
for x in range (2, number):
trial = number % x
if trial != 0:
print (x, "is NOT a divisor of", number, "...")
else:
is_prime = False
print (x, "is a divisor of", number, "...")
if is_prime:
print (number, "is a prime number!")
else:
print (number, "is not a prime number!")
You also do not need to use a variable test. Use the x from your range directly.
Have a look at the Python reference for the keyword for more information.
Syntax:
if expression:
statement(s)
else:
statement(s)
It executes all statements with break so print will be never happen...