+ 3

Counting Numbers in a range

# how can we modify this code to count the numbers in a given range which can divide by 2 we can’t use lists etc. import math while True: num1 = int(input("input lower number: ")) num2 = int(input("input upper number: ")) for numbers in range(num1, num2 + 1): if numbers % 2 == 0: print(numbers) else: break

27th Aug 2020, 3:23 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar
13 Respuestas
+ 2
Well you don't need to import math and you don't need the while loop or the else block
27th Aug 2020, 3:38 PM
Steven M
Steven M - avatar
+ 1
can you use sets? print({x for x in range(0,100) if x%2==0}) what about dictionaries? print({i:x for i,x in enumerate(range(0,100),1) if x%2==0}) tuples? print(tuple(x for x in range(0,100) if x%2==0))
27th Aug 2020, 3:26 PM
Steven M
Steven M - avatar
+ 1
there are other ways, yeah, but I don't think they will be as efficient as the ones we have already identified, the for loop does a pretty good job and the comprehensions do as well, the only other thing would be maybe a lambda or recursive function
27th Aug 2020, 3:42 PM
Steven M
Steven M - avatar
+ 1
You can use Pandas, but you are still storing your values in an array, you need to store the values somehow import pandas as pd x=int(input()) y=int(input()) z=range(x,y+1) df=pd.Series(z,index=z).apply(lambda x: x%2==0) print(df) print(f"There are {sum(df)} in even numbers in {z}")
27th Aug 2020, 4:07 PM
Steven M
Steven M - avatar
+ 1
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ This is what I’m looking for. thank you so much :)
27th Aug 2020, 4:24 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar
+ 1
print([1 for i in range(int(input()),int(input())+1) if i%2==0].count(1))
31st Aug 2020, 3:36 PM
Kunevich Evgeniyy Evgenievich
Kunevich Evgeniyy Evgenievich - avatar
+ 1
Kunevich Evgeniyy Evgenievich this is short and effective. thanks.
1st Sep 2020, 4:06 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar
0
No we can’t use any of them. is there any other way?
27th Aug 2020, 3:37 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar
0
so what should I do? for example if I give the first number 10 and second 20. then the numbers between this range is which can divide by 2 are: 10, 12, 14, 16, 18, 20 now I want another print that says “there are 6 even numbers” how can I count these even numbers there?
27th Aug 2020, 3:43 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar
0
♤♢☞ 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 ☜♢♤ yes but I want to print how many even numbers between that range. for example if I entered 10 and 20 then it should give me the print that says “there are 6 even numbers”
27th Aug 2020, 4:18 PM
YAKUP KARAKAŞ
YAKUP KARAKAŞ - avatar