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 numbernis prime. It returnsTrueifnis prime andFalseotherwise. - 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 numberiin this range, it checks ifiis prime using theis_prime(i)function. - If
iis prime, it is printed to the console.
Similar Questions
# Write a function in python which accept a number from user to return True, if the number#is a prime number else return False. Use this function to print all prime numbers from 1#to 100.
prime number in python
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.
Create a Python function that takes a list of integers as input andreturns a new list containing only the prime numbers from the input list.Provide a clear explanation of your implementation and include a test case.
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.