How to fix this - python-3.x

This code is supposed to find all the primes in a given range. But something is very wrong here
import math
def display(num, truth):
if truth:
print(num)
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower, upper, 1):
b = 2
c = True
a = math.sqrt(x)
while b < a:
if x%b != 0:
continue
else:
c = False
break
display(x,c)
print("Done")
I expect that it should output, say between 2 and 6:
Enter lower limit :2
Enter upper limit :6
2
3
5
Done
But the output is (for same range)
Enter lower limit :2
Enter upper limit :6
2
3
4
Note that 'Done' does not appear
And when I try to close the shell Python warns that the program is still running.

I am not sure to understand some of the code you have written.
How About something like this:
import math
lower = int(input("Enter lower limit :"))
upper = int(input("Enter upper limit :"))
for x in range(lower,upper + 1):
# prime numbers are greater than 1
if x > 1:
for i in range(2,x):
if (x % i) == 0:
break
else:
print(x)
print("Done")

Related

Python 3 for beginners Control Flow, While Loops and Break Statements

I bought a book to teach myself programming using Python.I am not taking any online course at the moment. I'm in chapter 2 and having problems with an exercise. I am to write a program that asks for 10 integers and then prints the largest odd number. If no odd number was entered, it should print a message saying so.
x = 0
largest_odd = int()
while(x < 10):
user_input = int(input('Enter an integer '))
if user_input%2 != 0 and user_input > largest_odd:
largest_odd = user_input
elif user_input%2 == 0 and x == 10:
print('no odd numbers')
x += 1
print(f'the largest odd number is {largest_odd}')
I am having a hard time entering all even numbers without printing the last print statement. I understand that the last print statement will print regardless because it is outside of the loop. But I've been on this the past few hours and can't figure out what I should change.
Please help.
If I understood the problem right you could just put a IF statement after the loop:
x = 0
largest_odd = 0
while x < 10:
user_input = int(input('Enter an integer '))
# check if x is odd and bigger than largest_odd
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if not largest_odd:
print('No odd numbers inputed!')
else:
print('The largest odd number is {}'.format(largest_odd))
You're on the right track with using the if-statements. What you need to do is to move the verification for if there were no odd numbers outside of the loop itself, and make an else-statement that prints out the largest if that isn't true:
x = 1
largest_odd = int()
while(x <= 10):
user_input = int(input(f'Enter an integer ({x}/10): '))
if user_input % 2 != 0 and user_input > largest_odd:
largest_odd = user_input
x += 1
if largest_odd == 0:
print('There was no odd numbers.')
else:
print(f'The largest odd number is {largest_odd}')
Because int() will default to 0 if you don't give it an argument, then we can use that as the verification, because 0 is not an even number.
I also changed the values of x changed the while-statement into x <= 10 so that we can make the representation of the input a little bit better.

Sum of all prime numbers

I want the sum of all prime numbers till 2 million. My program logic is correct but it takes too much time with 2 million. How can I make it faster?
num_l=[]
y = int(input("enter till what number do you want the sum"))
for count in range(0,y):
num_l.append(count)
total = 0
for counter in range(0,y):
num = num_l[counter]
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
total = total + num
print(total)
just use a function to check that it is prime or not and if it is then add it to a counter (for total). The code below takes about 20 seconds to find what you want.
One more thing is that your algorithm for testing if a number is prime or not is having a long range of numbers to go through you don't need to test to the last number you just need to go through for a range of square root of the number.
import time
def is_prime(n):
if n == 1:
return False
elif n == 2:
return True
else:
for i in range(2, int(n**0.5)+1): # this range is just enough
if n % i == 0:
return False
return True
counter = 0
start = time.time()
for i in range(1, 2*10**6): # you can change this range for taking it as input
if is_prime(i):
counter += i
print(counter)
print(time.time() - start)

Odd/even range in python3.x

Given an input range (lowest/highest) and choice(odd/even) how can I print the desired output in python? In the below code it doesn't seem to be executing the else condition
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
oddeven = input("Do you want to see odd or even numbers: ")
print(oddeven)
for num in range(low, high):
if (num % 2 == 0):
print(num)
else :
if (num % 2 == 1):
print(num)
I think the easiest solution to implement, would be for you to create two for loops, one for the even case and one for the odd case, so you only have to check once rather than for each iteration of the for loop:
def get_int_input(prompt: str) -> int:
while True:
try:
return int(input(prompt))
except ValueError:
print("Error: Enter an integer, try again...")
low = get_int_input("Enter the lowest number in the range (inclusive): ")
high = get_int_input("Enter the highest number in the range (inclusive): ")
valid_odd_even_responses = {"odd", "even"}
odd_even_response = ""
while odd_even_response not in valid_odd_even_responses:
odd_even_response = input(
"Do you want to see odd or even numbers: ").lower()
if odd_even_response == "odd":
for num in range(low, high + 1):
if num % 2 == 1:
print(num)
else:
for num in range(low, high + 1):
if num % 2 == 0:
print(num)
Example Usage:
Enter the lowest number in the range (inclusive): -1
Enter the highest number in the range (inclusive): 13
Do you want to see odd or even numbers: even
0
2
4
6
8
10
12
Some thoughts:
Check your indentation (look that "else")
"oddeven" is useless
You don't need num % 2 == 0, just num % 2, because, in python, 0 is 'false' already
You don't need the second 'if', because the 'else' is already doing the job bifurcating the flow in your program
If you're learning, try to draw your algorithm with paper and pencil before implementing it
Happy coding!
The first two lines are OK:
low = int(input("Lowest number: "))
high = int(input("Highest number: "))
Here, I add a clarification that tells the user how to answer the question. Your code does not use this variable, that is why you get the wrong output.
even = int(input("Do you want to see odd (0) or even (1) numbers: "))
If the user wants even numbers but low is not even, or the other way around, adjust it:
if (even and low % 2 == 1) or (not even and low % 2 == 0):
low += 1
Step though all odd or even numbers:
print("\n".join(str(x) for x in range(low, high + 1, 2)))

How do I remove the last comma in a range of printed prime numbers in python?

I am a self taught beginner.
I've been trying to solve the following problem in my code for hours:
lower = int(input("Enter the start of the range:"))
upper = int(input("Enter the end of the range:"))
if (lower < 2 or upper < 2 or lower>upper):
print("Wrong value entered.")
else:
print("Prime numbers between", lower, "and", upper, "are" , '' ,end='')
for num in range(lower, upper + 1):
for i in range(2, num):
if(num%i) == 0:
break
else:
print(str(num) +",",end='')
print('\b' +".")
The code works fine when I run it in an online compiler and prints the output neatly like:
The prime numbers between n1 and n2 are m1,m2,m3.
But when I run it my local compiler, it "prints" the backspace without actually moving cursor and replacing the last comma.
What am I doing wrong here?
Here is how I would go about it, using the join function:
lower = int(input("Enter the start of the range:"))
upper = int(input("Enter the end of the range:"))
def is_prime(n):
for i in range(2, n):
if n%i==0:
return False
return True
if lower < 2 or upper < 2 or lower > upper:
print("Wrong value entered.")
else:
primes_between_lower_and_upper = (str(n) for n in range(lower, upper + 1) if is_prime(n))
print(f"""\
Prime numbers between {lower} and {upper} are \
{', '.join(primes_between_lower_and_upper)}.""")

Why this script doesn't run after the first line

tweak = int(input("Input an integer"))
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print(number)
collatz(tweak)
If you are trying to implement a Collatz conjecture script, then your first if is wrong - you should divide the number by 2. Also, your return causes the function to end, so you get only one while loop, doesn't matter what happens inside - so you basically return the number you inputed or that number * 3 + 1.
Here is the correct code with slight modifications:
tweak = int(input("Input an integer"))
def collatz(number):
steps = 0
num = number
while number != 1:
if number % 2 == 0:
number = number / 2
else:
number = int(3 * number + 1)
steps +=1
print("Reached 1 in {} iterations for number {}.".format(steps, num))
collatz(tweak)
You also don't need the elif, because number can only be dividable by 2 or not.
Example outputs:
collatz(22)
collatz(55)
collatz(234)
Reached 1 in 15 iterations for number 22.
Reached 1 in 112 iterations for number 55.
Reached 1 in 21 iterations for number 234.
Your question has only code, but I think this is what you might be looking for:
def collatz(tweak):
while tweak != 1:
if tweak % 2 == 0:
return int(tweak)
elif tweak % 2 != 0:
return int((3 * tweak) + 1)
print(tweak)
tweak = int(input("Input an integer:"))
result = collatz(tweak)
print(result)
Your returning values in if and else so it wont print beyond..
instead assign it in variable and do print..
tweak = input("Input an integer")
def collatz(number):
while number != 1:
if number % 2 == 0:
return int(number)
elif number % 2 != 0:
return int((3 * number) + 1)
print number # this wont work.. your returned already
print "output:%s"%collatz(tweak)
output:
me#dev-007:~/Desktop$ python test.py
Input an integer10
number 10
output:10

Resources