lower = int(input("Enter lower range limit:"))
upper = int(input("Enter upper b range limit:"))
Count = 0
for i in range(lower, upper+1):
if((i%3==0) & (i%5==0)):
Count += 1
print(count)
I want to print 100 values which are divisible by 3 and 5, but in count only 7 is showing, can anyone suggest what to do, it will be appreciated!
Use this
num = int(input("How many Numbers you want :"))
i=0
Count = 0
while(Count != num):
if((i%3==0) and (i%5==0)):
Count += 1
print(i)
i = i + 1
print("Count is :",Count)
Python program to print all the numbers
divisible by 3 and 5 for a given number
Result function with N
def result(N):
# iterate from 0 to N
for num in range(N):
# Short-circuit operator is used
if num % 3 == 0 and num % 5 == 0:
print(str(num) + " ", end = "")
else:
pass
Driver code
if name == "main":
# input goes here
N = 100
# Calling function
result(N)
Related
So I could print out the odd numbers. However, the output isn't what i want. It should look like 1+3+5+7 = 16 but I could not make it into a single line.
I couldn't figure out how to extract the values from the while loop as with my method it only gives the latest odd number which is 7 while 1,3 and 5 could not be taken out
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
odd = (str(oddNum))
print (odd)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (odd + "=" + str(total))
#output will be:
'''
1
3
5
7
7=16
but it should look like 1+3+5+7=16
'''
An alternative method would be the use of:
range() method to generate the list of odd numbers
.join() method to stitch the odd numbers together (eg. 1+3+5+7)
f-strings to print odds together with the total = sum(odd_nums)
Code:
num = int(input("Insert a postive integer:")) #4
odd_nums = range(1, num * 2, 2)
sum_nums = "+".join(map(str, odd_nums))
print(f"{sum_nums}={sum(odd_nums)}")
Output:
1+3+5+7=16
Note:
Same but using two lines of code:
num = int(input("Insert a postive integer:")) #4
print(f"{'+'.join(map(str, range(1, num * 2, 2)))}={sum(range(1, num * 2, 2))}")
Output:
1+3+5+7=16
You are not storing old oddNum values in odd. With minimal changes can be fixed like this:
num = int(input("Insert a positive integer:"))
oddNum = 1
total = 0
count = 1
odd = ""
while count <= num:
total = total + oddNum
odd += f"{oddNum}"
oddNum = oddNum + 2
count += 1
odd = "+".join(odd)
print(odd + "=" + str(total))
There are a few options, you can either create a string during the loop and print that at the end, or create a list and transform that into a string at the end, or python3 has the ability to modify the default end of line with print(oddNum, end='').
Using a string:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
sequence = ''
while count <= num:
sequence += ("+" if sequence != "" else "") + str(oddNum)
total = total + oddNum
oddNum = oddNum + 2
count += 1
print (sequence + "=" + str(total))
Using print:
num = int(input("Insert a postive integer:")) #4
oddNum = 1
total = 0
count = 1
while count <= num:
if count != 1:
print('+', end='')
print (oddNum, end='')
total = total + oddNum
oddNum = oddNum + 2
count += 1
print ("=" + str(total))
Alternatively using walrus (:=), range,print, sep, and end:
print(*(odd:=[*range(1,int(input('Insert a postive integer:'))*2,2)]),sep='+',end='=');print(sum(odd))
# Insert a postive integer:4
# 1+3+5+7=16
This is the question:
Write a Python program that reads a positive integer n and finds the
average of all odd numbers between 1 and n. Your program should not
accept a negative value for n.
And here is my code, which curiously doesn't work:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
while b <= k:
if b % 2 == 1:
sum1 = sum1+b
b += 1
avg = sum/k
print(avg)
Example: input: 8 and output: 2.5, while it should be 4. Any tips?
if we use while True, the program will run until it receives a positive number. and when we get a positive number, then we execute the instructions and turn off the loop using a break
1 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = [i for i in range(1, n + 1) if i % 2 == 1]
print(sum(numbers) / len(numbers))
break
2 version with list:
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
numbers = []
for i in range(1, n+1):
if i % 2 == 1:
numbers.append(i)
break
print(sum(numbers)/len(numbers))
3 version with counter
n = int(input())
while True:
if n <= 0:
n = int(input('Enter a positive number: '))
else:
summ = 0
c = 0
for i in range(1, n+1):
if i % 2 == 1:
summ += i
c += 1
print(summ/c)
break
You have used sum (builtin function name) instead of sum1 (your variable name) in the 2nd last line. Additionally, you need to count the total number of odd numbers and divide using that number instead of the input.
Okay I reviewed the question and here is the answer:
k = int(input('Enter a positive integer: '))
while k <= 0:
print('Please enter a positive integer!! \n')
k = int(input('Enter a positive integer: '))
else:
b = 1
sum1 = 0
c = 0
while b <= k:
if b % 2 == 1: #determines if odd
sum1 = sum1+b
c += 1 #variable which counts the odd elements
b += 1 #counter
avg = sum1/c
print(avg)
sum = int(input("Enter a positive integer: "))
Oddtotal = 0
for number in range(1, sum+1):
if(number % 2 != 0):
print("{0}".format(number))
Oddtotal = Oddtotal + number
An Emirp is a prime number whose reversal is also a prime. For
example, 17 is a prime and 71 is a prime, so 17 and 71 are emirps.
Write a program that prints out the first N emirps, five on each line.
Calculate the first N emirp (prime, spelled backwards) numbers, where
N is a positive number that the user provides as input.
Implementation Details
You are required to make use of 2 functions (which you must write).
isPrime(value) # Returns true if value is a prime number. reverse
(value) # Returns the reverse of the value (i.e. if value is 35,
returns 53). You should use these functions in conjunction with logic
in your main part of the program, to perform the computation of N
emirps and print them out according to the screenshot below.
The general outline for your program would be as follows:
Step 1: Ask user for positive number (input validation) Step 2:
Initialize a variable Test to 2 Step 3: While # emirps found is less
than the input:
Call isPrime with Test, and call it again with reverse(Test).
If both are prime, print and increment number of emirps found. Test++ Hint - to reverse the number, turn it into a string and then
reverse the string. Then turn it back into an int!
MY CODE:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
count = 0
while(test < value):
if( value % test == 0):
count+=count
test+=test
if(count == 0):
return 1
else:
return 0
def reverse(value):
reverse = 0
while(value > 0):
reverse = reverse * 10 + (value % 10)
value = value / 10
return reverse
n = float(input("Please enter a positive number: "))
while(count < n):
i+=i;
if(isPrime(i)):
if(isPrime(reverse(i))):
print("i" + "\n")
count+=count
if((count % (5)) == 0 ):
print("\n")
where are the mistakes?
UPDATED CODE BUT STILL NOT RUNNING:
n = 0
count = 0
i = 1
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
def reverse(value):
return int(str(value)[::-1])
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
There are a lot of issues with your code. I altered the function isPrime. There is among other no need for count here and if you want to increment test by 1 every loop use test +=1:
def isPrime(value):
test = 2
while(test < value):
if( value % test != 0):
test +=1
else:
return 0
return 1
There is an easy way to reverse digits by making value a string in reversed order and to convert this into an integer:
def reverse(value):
return int(str(value)[::-1])
You among other have to assign the input to i. n in your code is a constant 5. You have to increment i by one in any condition and increment the count by one if i is an emirp only:
i = int(input("Please enter a positive number: "))
count = 0
while(count < 5):
if(isPrime(i)):
if(isPrime(reverse(i))):
print(str(i) + "\n")
count += 1
i += 1
else:
i += 1
else:
i +=1
def emrip_no(num):
i=0
j=0
for i in range(1,num+1):
a=0
for j in range(1,i+1):
if(i%j==0):
a+=1
if(a==2):
print("Number is a prime number")
k=0
l=0
rv=0
while(num!=0):
r=num%10
rv=(rv*10)+r
num=num//10
print("It's reverse is: ",rv)
for k in range(1,rv+1):
b=0
for l in range(1,k+1):
if(k%l==0):
b+=1
if(b==2):
print("It's reverse is also a prime number")
else:
print("It's reverse is not a prime number")
n=int(input("Enter a number: "))
emrip_no(n)
I am trying to make a code in Python that shows the number of steps needed to reach one from any number using a simple algorithm. This is my code:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(max - min):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num / 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(int(n)+min)+' Steps needed: '+count)
It freezes up without showing an error message, and I have no clue why this happens.
1) You are invoking range() incorrectly.
Your code: for n in range(max - min): produces the range of numbers starting at 0 and ending at the value max-min. Rather, you want the range of numbers starting at min and ending at max.
Try this:
for n in range(min, max):
2) You are performing floating-point division, but this program should use only integer division. Try this:
num = num // 2
3) You are updating the count variable in the wrong loop context. Try indenting it one stop.
4) Your final line could be:
print('Number: '+str(n)+' Steps needed: '+str(count))
Program:
print('Enter the lowest and highest numbers to test.')
min = input('Minimum number: ')
min = int(min)
max = input('Maximum number: ')
max = int(max) + 1
print(' ')
for n in range(min, max):
count = 0
num = n
while not num == 1:
if num % 2 == 0:
num = num // 2
else:
num = (num * 3) + 1
count = count + 1
print('Number: '+str(n)+' Steps needed: '+str(count))
Result:
Enter the lowest and highest numbers to test.
Minimum number: 3
Maximum number: 5
Number: 3 Steps needed: 7
Number: 4 Steps needed: 2
Number: 5 Steps needed: 5
It looks like it's getting stuck in the while not num == 1 loop. Remember that range() starts at 0, so num is first set to 0, which is divisible by 2, and so will be reset to 0/2... which is 0 again! It will never reach 1 to break the loop.
EDIT: I earlier said that count = 0 needed to be moved. Actually, looking more carefully it seems like the line count = count + 1 line just needs to be moved under the while loop.
f=0
c=1
n=raw_input("Enter the value of n")
while c<n:
for i in range(2,100):
for j in range(1,i):
if i%j == 0:
f =f+1
if f == 1:
print i
c = c+1
f = 0
If n is 5 then the output should print the first 5 prime numbers.
2,3,5,7,11
You have a few mistakes. You do not parse n as integer, you have an unnecessary loop, you inistailise c with a wrong value.
Here is a corrected version
c = 0
n=int(raw_input("Enter the value of n"))
i = 2
while True:
for j in range(2,i):
if i % j == 0:
break
else:
print i
c = c + 1
if c == n:
break
i += 1
Copy of answer to this question.
You're only checking the value of count at the end of the for loop so you will always end up with the full range of 1-100 being tested. Why is the range limited to 100?
You don't need a for loop at all. Use the while loop to keep finding primes until you have num of them.
Try something like:
import math
def isPrime(num):#this function courtesy of #JinnyCho
if num == 1:
return False
if num % 2 == 0 and num > 2:
return False
for i in range(3, int(math.sqrt(num))+1, 2):
if num % i == 0:
return False
return True
def getPrimes(num):
count = 0
i = 1
highPrime = None
while count < num:
if isPrime(i):
count += 1
yield i
i += 1
n = int(raw_input("Enter the value of n: "))
list(getPrimes(n))