I need a bit of help in finishing this code. I am stuck trying to figure out what's wrong with my code. I don't know how to loop back from the top using while loop. It also wont print the last bit. I got the prime numbers settled but I don't know how the looping back works. May you help me?
while True:
num=int(input("Enter a number:"))
no="n"
yes="y"
if num >=1:
for i in range(2, num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
x=str(input("If you want to continue press y, n if not:"))
if x==yes:
print()
#this part I don't know how to loop back to the start
elif x==no:
print("Okay")
#and also the loop won't stop and print the text up there^^^ when I choose n
put the if in the while loop only, and break out of the while loop if no
while True:
...
x=str(input("If you want to continue press y, n if not:"))
if x=="no":
print("Okay")
break
If you want this to repeat infinitely, your code structure might look like this:
while True: # The outer while loop, only ends when the player says "n"
while True:
# This is where you get the prime nums, paste the code for that here
if x == "n":
break # This method will only stop the loop if the input is "no", else it keeps looping forever
Or, more simply, you can do this in just one loop. The structure would be like this:
while True:
# Get if the num is prime, paste the code for that
if x == "n":
break
Possible solution if the following:
def is_prime(num):
if num <= 1:
return False
if num % 2 == 0:
return num == 2
d = 3
while d * d <= num and num % d != 0:
d += 2
return d * d > num
while True:
num=int(input("Enter a number: "))
if is_prime(num):
print(f'{num} is a prime number')
else:
print(f'{num} is not a prime number')
x = str(input("If you want to continue enter Y, or N if not: ")).lower()
if x == 'y':
print("let's start over...\n")
elif x == 'n':
print("Okay, see you")
break
Returns:
You can use code like this. In my opinion function more usefull for check prime numbers.
def is_prime(x):
for d in range(2, int(x**0.5)+1):
if x % d == 0:
return False
return x > 1
no, yes = "n", "y"
x = yes
while x == yes:
num=int(input("Enter a number:"))
if is_prime(num):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
x = input("If you want to continue press y, n if not:")
print("Okay")
Related
I want to find the prime numbers up to the given number but my loop only runs once and my output is only 2 and 3, where did I went wrong?
def primer_check(n):
prime_state = True
for i in range(2,n+1):
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)
you have to set prime_state to True everytime when you start a new loop.here is the code.you are almost correct .Hope it helps :)
def primer_check(n):
for i in range(2,n+1):
prime_state = True
if i == 2:
print(2)
continue
for j in range(2,i):
if i % j == 0:
prime_state = False
break
if prime_state: print(i)
n = int(input("Enter a number to see the prime numbers up to that number : "))
primer_check(n)
I'm trying to solve the scenario with these conditions:
Ask the user to enter a number
Count up from 1 to the number that the user has entered, displaying each number on its own line if it is an odd number. If it is an even number, do not display the number.
If the user enters a number that is 0 or less, display error
My codes are as follows and I can't seem to satisfy the <= 0 print("error) condition:
num=int(input("Enter number: "))
for x in range(num):
if x % 2 == 0:
continue
print(x)
elif x<=0:
print("error")
Your solution will be :
num=int(input("Enter number: "))
if num <= 0:
print("Error")
else:
for i in range(1, num + 1):
if i % 2 == 0:
continue
print(i)
You need to print the error before looping from 1 to num because if the value is less the 0 then the loop won't run. I hope you understand.
You have to check the condition num <= 0 as soon as the user enters the number:
num = int(input("Enter number: "))
if num <= 0:
print("error")
else:
for x in range(num):
if x % 2 == 0:
continue
print(x)
I'm relatively new to Python and trying to build a function to check primes because I thought it would be a good starter project, but my code returns everything as a prime, so it's obviously gone wrong. I get this is an inefficient way to do it, but I want to understand how to do it the long way first. Here's my code so far:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if n % i == 0:
break
print("This number is not prime.")
else:
i = i - 1
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()
Mathematically speaking you could check only all the int between 0 and sqrt(n) to judge a number is prime or not as for the logic, you are missing negative number handling plus other things please see my following code:
def prime(n):
n = abs(n)
if n<4: return True
i = int(sqrt(n))
while i > 1:
if n % i == 0: return False
i -= 1
return True
plus you should add this to your import
from math import sqrt
Here is your program with a couple changes:
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 1:
if n % i == 0:
print("This number is not prime.")
return
i = i - 1
print("This number is prime.")
return
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print "Thank you for using the prime program."
Main()
First, i is now compared until i > 1 rather than 0 as every number is divisible by 1 and hence all numbers would be prime if the original condition was used.
Secondly, the break statement is substituted with return. Although break would work, the program would need more modifications in that case because the message for a prime number would always be printed at the end (along with not a prime message). Also, the return statement was moved after the print to actually get a print. More importantly, the message that a number is a prime was moved outside the while - otherwise the message would be printed on every iteration.
I also removed the else and the i is decremented right in the while loop which is to me a more readable alternative.
Finally, your last statement was, I assume, supposed to be an output, which it is now. I also added a space to the user prompting message so that the number displays more nicely.
It's not easy to explain the logic flaw, but you can see the following code
def Prime(n):
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n - 1
while i > 0:
if i == 1 or n == 2 or n == 3:
print("This number is prime.")
break
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
def Main():
n = int(input("What is the number you'd like to check? "))
Prime(n)
print("Thank you for using the prime program.")
Main()
Ok, first off, your code will never print "This number is not prime." because you've put a break statement right before it. You would want to reverse those two lines such that it becomes:
print("This number is not prime.")
break
Also, the line i = n - 1 should be changed to i = n so that you check the starting number as well, and not just the numbers lesser than it. So if you try the code now, you'll notice that you're printing whether every number that you check is prime or not, not just the input value. To remedy this using your code structure, use a flag. For example:
def Prime(n):
flag = true
if n == 1 or n == 2 or n == 3:
print("This number is prime.")
else:
i = n
while i > 0:
if n % i == 0:
print("This number is not prime.")
break
else:
i = i - 1
if flag == true:
print("This number is prime.")
The flag check should be outside the loop.
Question:
A program that take a positive integer n as input and returns True if n is a prime number, otherwise returns False.
My Answer:
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
print(True)
when I enter a prime number it works but when I enter a non prime number it doesn't work.
Example:
>>>
Enter a number: 12
False
False
False
False
True
>>>
please help!
You can break and use else:
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(False)
break
else:
print(True)
True will only be printed if the loop completes fully i.e no n % i was equal to 0.
Your code always prints True at the end, and prints a number of Falses before that. Instead, you should have a variable (isPrime?) that gets initialized to True and gets set to False when you find it is divisible by something. Then print that variable at the end.
You're just printing each intermediate value, if you use return in a function it works fine
def prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
>>> prime(5)
True
>>> prime(12)
False
You could use the for-else clause here. Also, you don't need to go beyond the square root of n:
import math
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
print "False"
break
else:
print "True"
There's a lot of different ways to fix your code, but all of them hinge on the fact that you should be breaking out of that loop if you find a divisor (ie if n%i == 0)
Usually, you'd have a boolean value storing whether or not you've found a divisor, but python lets you do the following
n = int(input("Enter a number: "))
for i in range(2,n):
if n%i == 0:
print(False)
break
else:
#else statement only happens if you don't break out of the loop
print(True)
Check out the algorithm here:
http://www.programiz.com/python-programming/examples/prime-number
# Python program to check if the input number is prime or not
# take input from the user
num = int(input("Enter a number: "))
# prime numbers are greater than 1
if num > 1:
# check for factors
for i in range(2,num):
if (num % i) == 0:
print(num,"is not a prime number")
print(i,"times",num//i,"is",num)
break
else:
print(num,"is a prime number")
# if input number is less than
# or equal to 1, it is not prime
else:
print(num,"is not a prime number")
If you encounter an i which gives modulo zero with n, then you have to print False and then do nothing. For this you can use a flag variable which takes care of this condition. If no such i is encountered, flag remains 1 and True is printed.
n = int(input("Enter a number: "))
flag = 1
for i in range(2,n):
if n%i == 0:
print(False)
flag = 0
break
if flag:
print(True)
check this one, it should make clear why the else statement is indented 'non conventionally':
num = int(input('Enter the maximum value: '))
for number in range(3, num+1):
#not_prime = False
for factor in range(2, number):
if number%factor == 0:
#not_prime = True
break
#if not_prime:
#continue
else:
print(number)
All of the above things are correct but I want to add thing that you should check for the condition of 1. if someone puts 1 as an integer you will have to return False. 1 is not prime
def prime_num(num):
if num <= 0:
return "the number is not primary"
for i in range(2, num - 1):
if num % i == 0:
return "The number is not primary, it can be divided: " + str(i)
return "The number: " + str(num) + " is primary"
This is one of the many ways to solve it:
def is_prime(num):
if (num == 2):
return True
elif any(x for x in range(2, num - 1) if (num % x == 0)):
return False
else:
return True
I am trying to create a number guessing game with multiple numbers. The computer generates 4 random numbers between 1 and 9 and then the user has 10 chances to guess the correct numbers. I need the feedback to display as YYYY for 4 correct numbers guessed, YNNY for first and last number guessed etc. (you get the point). the code below keeps coming back saying IndexError: list index out of range.
from random import randint
guessesTaken = 0
randomNumber = []
for x in range(4):
tempNumber = randint(1, 9)
randomNumber.append(tempNumber)
Guess = []
Guess.append(list(input("Guess Number: ")))
print(randomNumber)
print(Guess)
if randomNumber[0] == Guess[0]:
print("Y")
elif randomNumber[1] == Guess[1]:
print("Y")
elif randomNumber[2] == Guess[2]:
print("Y")
elif randomNumber[3] == Guess[3]:
print("Y")
elif randomNumber[0] != Guess[0]:
print("N")
elif randomNumber[1] != Guess[1]:
print("N")
elif randomNumber[2] != Guess[2]:
print("N")
elif randomNumber[3] != Guess[3]:
print("N")
You need four guesses to match for random numbers, you can also shorted your code using a list comp:
from random import randint
guessesTaken = 0
randomNumber = []
Guess = []
for x in range(4):
tempNumber = str(randint(1, 9)) # compare string to string
randomNumber.append(tempNumber)
Guess.append(input("Guess Number: "))
print("".join(["Y" if a==b else "N" for a,b in zip(Guess,randomNumber)]))
You can also use enumerate to check elements at matching indexes:
print("".join(["Y" if randomNumber[ind]==ele else "N" for ind, ele in enumerate(Guess)]))
To give the user guesses in a loop:
from random import randint
guessesTaken = 0
randomNumber = [str(randint(1, 9)) for _ in range(4)] # create list of random nums
while guessesTaken < 10:
guesses = list(raw_input("Guess Number: ")) # create list of four digits
check = "".join(["Y" if a==b else "N" for a,b in zip(guesses,randomNumber)])
if check == "YYYY": # if check has four Y's we have a correct guess
print("Congratulations, you are correct")
break
else:
guessesTaken += 1 # else increment guess count and ask again
print(check)
Right now you're only asking the user for one guess, and appending the guess to the Guess list. So the Guess list has one element, but you're using Guess[1], Guess[2], etc., which of course results in the IndexError
I'll rearrange your code a bit, so it doesn't stray too far from what you've done.
from random import randint
guessesTaken = 0
randomNumbers = []
Guess = [] # Combine your guesses with your loop
for x in range(4):
tempNumber = randint(1, 9)
randomNumbers.append(tempNumber)
# This should be done four times too
# In Python 2, instead of this:
# Guess.append(input("Guess Number: "))
# do this:
Guess.append(int(raw_input("Guess Number: "))) # raw_input and pass to int
# in python 3, raw_input becomes input, so do this instead:
# Guess.append(int(input("Guess Number: ")))
print(randomNumbers)
print(Guess)
You can combine these in a loop to avoid the repetitive code:
if randomNumbers[0] == Guess[0]:
print("Y")
else:
print("N")
if randomNumbers[1] == Guess[1]:
print("Y")
else:
print("N")
if randomNumbers[2] == Guess[2]:
print("Y")
else:
print("N")
if randomNumbers[3] == Guess[3]:
print("Y")
else:
print("N")
Perhaps, to print your desired result e.g. YNNY, like this:
result = []
for index in range(4):
if randomNumbers[index] == Guess[index]:
result.append("Y")
else:
result.append("N")
print(''.join(result))
If you want terser code use Python's ternary operation:
result = []
for index in range(4):
result.append("Y" if randomNumbers[index] == Guess[index] else "N")
print(''.join(result))
Or use the fact that True == 1 and False == 0 as indexes:
result = []
for index in range(4):
result.append("NY"[randomNumbers[index] == Guess[index]])
print(''.join(result))