Write a python script that accept a number from the user and display a prime number from 1 to the value:
Question
Write a python script that accept a number from the user and display a prime number from 1 to the value:
Solution
Sure, here is a simple Python script that accepts a number from the user and displays all prime numbers from 1 to that value:
def is_prime(n):
if n <= 1:
return False
if n == 2:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
num = int(input("Enter a number: "))
for i in range(1, num + 1):
if is_prime(i):
print(i)
Here's how it works:
- The
is_prime(n)
function checks if a numbern
is prime. It returnsTrue
ifn
is prime andFalse
otherwise. - The script then asks the user to input a number and stores it in the variable
num
. - The script then loops from 1 to
num
(inclusive) and for each numberi
in this range, it checks ifi
is prime using theis_prime(i)
function. - If
i
is prime, it is printed to the console.
Similar Questions
Write a program primes.py that reads a positive integer from standard input, and determines whether or not the number is prime.
Write a single line Python code to print all the prime numbers between 1 and 200.
Please create a pseudocode function that can check if a given number n is prime or not, where n > 1.
Write a Python program using a while loop to calculate and display the factorial of a user-inputnumber. Ensure your program handles invalid inputs gracefully.
Write a C++ program to generate all the prime numbers between 1 and n, where n is a value
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.