While loops in python while condition being at the end - python

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

Related

Program must ask the user for an even integer max six times, if not it ends

The program ask the user for an even integer. If he asks for it 6 times, the program ends. If the number is even, it returns it. My code so far:
i = 0
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(num)
else:
num = int(input("Num: "))
i+=1
if i == 6:
break
My program doesn't end after user gives 6 not even numbers, how can i fix this?
You don't need to check for i == 6 yourself, this is done automatically by the for loop.
But you need to break out of the loop when an even number is entered.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print("Success!")
break
else:
print("Failure")
The else: block of a loop is executed if the loop reaches its normal conclusion instead of exiting due to break.
for i in range(6):
num = int(input("Num: "))
if num % 2 == 0:
print(liczba)
break
This will do what you want, without all the extra lines you had.

Why my for loop is not iterating all the values

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.

Validate if input number is prime

Trying to write a program that checks if a number is prime.
Wrote the below code, but do not understand why do I have an output of 2 lines:
num = int(input("Provide number to check if prime: "))
if num <=1:
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
if num %i !=0:
print("Number is prime")
My output is :
Provide number to check if prime: 15
Number is prime
Number is not prime
The sympy.isprime() is a built-in function under the SymPy module and can be utilized for checking of possible prime numbers. It is a direct function and returns True if the number to be checked is prime and False if the number is not prime.
>>> import simpy
>>> sympy.isprime(8)
False
>>> sympy.isprime(11)
True
or else define a function like this
>>> def isPrime(k):
# 1 is not prime number
if k==1:
return False
# 2, 3 are prime
if k==2 or k==3:
return True
# even numbers are not prime
if k%2==0:
return False
# check all numbers till square root of the number ,
# if the division results in remainder 0
# (skip 2 since we dont want to divide by even numbers)
for i in range(3, int(k**0.5)+1, 2):
if k%i==0:
return False
return True
>>> print(isPrime(13))
True
>>> print(isPrime(18))
False
As the first thing, you should remember that 1 isn't a prime number by definition, even if it can't be divided by any other number:
if (num == 1):
print("The number is NOT prime")
else:
for i in range(2, num):
if (num%i == 0): # If the number has a divisor
print("The number is NOT prime")
break
else: # If the for loop ends without reaching any break
print("The number IS prime")
The else branch of a for loop is reached when the loop ends without reaching any break AND the loop executes at least one time.
To better understand my answer, I would suggest to read this.
The error with your solution is caused by the loop printing that the number is prime for each time num%i == 0, so taking num = 6:
6%4 != 0 # The number is prime
6%5 != 0 # The number is prime
As Rajarshi Ghosh suggested, you should know that while programming it's a good idea to use imported functions to do this simple operations, in order to avoid long operations for such a simple job.
If you don't want to use an imported function, I would suggest you to read this article where they explained 6 ways of finding if a number is prime without using functions made by others.
You have issues in output, not only for the case of 15, but also for cases smaller than 1. The following code should work. It has two improvements.
It prints the correct output for 15. The key is to move the else block to align with the for loop.
It prints the correct output for any number smaller than 1, which is not prime. The key is to use the while-break method to get user enter right number until it is bigger than 1.
num = int(input("Provide number to check if prime: "))
while num <=1: #you need to use while loop
print("Invalid choice, try again")
num = int(input("Provide number to check if prime: "))
if num > 1: #only evaluate number is prime or not if it is greater than 1
for i in range(2,num):
if num% i ==0:
print("Number is not prime")
break
else: #to move the `else` block to align with the `for` loop.
print("Number is prime")
break #add a break here
Output:
What is a while loop?
A while loop tests the input condition. Every time the loop finishes, the condition is reevaluated (only evaluate number is prime or not if it is greater than 1). As long as the the number entered is <=1, the loop keeps executing (keep asking users for input).
If you want to just check whether a number is prime or not just do the following:
num = int(input("Provide number to check if prime: "))
flagNotPrime = False
if num > 1:
for i in range(2, num):
if (num % i) == 0:
flagNotPrime = True
break
if flagNotPrime:
print("Number is not prime")
else:
print("Number is prime")
Firstly, numbers that are <= 1 are not prime numbers. Therefore, the above code only proceeds if the num is greater than 1.
Secondly, the code checks if num is exactly divisible by any number from 2 to num - 1. If there is a factor in that range, the number is not prime, so the flag is set to True and the loop is broken using break.
Lastly, outside the loop, if the flag is True then num is not prime.

I used while loop, until the random number that python throws matched the input, why it doesn't work? [duplicate]

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')

what do i write to fill the space of the line 4 code such that it prints true if n is a prime since it returns true no matter what

i mathematically find it difficult to compose a code to fill the line 4 in the below code
is_prime = True
for i in range(2,n):
if n%i == 0:
print("impossible")
print(is_prime)
i have been typing print(string) i.e
print("this is not possible")
in the blank and it output
true
what is the correct code to write. i want to believe it is a mathematics expression thing.i don't know the code to write after if.
If n is a prime number, then n%i == 0 will always be false in your loop. That's why the print in the 4th line is never called (you said it yourself, it's impossible). The true you are getting is from the print on the last line: you never update the value of is_prime, so it will always print True.
On the other hand, if what you want to know is if n is a prime number, you can do this:
is_prime = True
for i in range(2,n):
if n%i == 0:
is_prime = False
break
print(is_prime)
here i wrote it down for you, getting to mathematics what we know is any number is prime number if it can give a integer when it is divided by one or itself so now we can check if the number is divisible by any number in between
for example if your number is equal to 5 then we check if 5 gives an integer and leaves no remainder when divided by 2,3 and 4, you can program this algorithm as follows
x=8 #any number to check for
answer= "prime"
for i in range(1,x-1):
if(x%(i+1) == 0 ):
answer="non-prime"
print(answer)
The problem is that you are not reassigning is_prime to False when your if condition is passed. After print("impossible) you can simply add is_prime = False and follow that with a break statement to exit the for loop.
print(is_prime) will now return False.
You can also modify range(2, n) to range(2, n//2) (the // operator performs integer divison and leaves no remainder). This is because for any given number, you will only need to check half of numbers from 1 to n, as eventually you will start to encounter repeated numbers.
is_prime = True
for i in range(2, n //2):
if n % i == 0:
print("impossible")
is_prime = False
break
print(is_prime)
Edit print("impossible") to any of the following two approaches:
is_prime = False
or
not any([n%i==0 for i in range(2,n)])
from your code, the print statement is on the outer scope from the if condition. You woud try adding an else block. I have have included an example using your code. Hope it helps.
is_prime = True
n =10
for i in range(2,n):
print(i)
if n%i == 0:
print("impossible")
else:
print(is_prime)

Categories

Resources