In: Computer Science
Comments using # and "" "should also be included for reader to understand each part.
Question: 14. Write in python a script code which tells the user to enter an integer bigger than 5. Any input numbers which are smaller than 5 or 5 are not considered by this script. The code then should output all the prime numbers starting at 5, which are smaller than the number inputted by that user.
Code:
# Taking an input from user
number = input("Enter a number greater than 5: ")
# Converting the inputted string to integer datatype
number = int(number)
# If the input number is <=5, display a message and exit the code
if (number<=5):
print("The input number must be greater than 5.")
exit
# else find the prime numbers
else:
# Print statement to convey the information
print("Prime numbers starting from 5 and smaller than "+ str(number) +" are:")
# for loop to find the prime numbers between 5 and the input number
for num in range (5, number):
count = 0
# checking the divisors of the number
for i in range(2, (num//2 + 1)):
if(num % i == 0):
count = count + 1
break
# if divisors are zero, then print the number
if (count == 0):
print(" %d" %num, end = ' ')
Screenshot for better understanding:
Output examples:
Using the input() we take user input and then check whether it satisfies our condiiton. If it does, we find all the prime numbers in that range using the for loop. The first for loop traverses the numbers in range, while the second counts number of divisors of that number except 1 and itslef. If the count of divisors comes out to be zero, that means it is prime and we print it.