Python range count by 2

Python for loop increment by 2

A regular for loop will increase its iteration counter by one in each iteration.

But there are situations where you want to increment the iteration counter by 2.

For some reason you might want to work with only even values.

Let’s see a few solutions for this.

range function

The solution to increment a for loop by 2 in Python is to use the range() function.

This function allows you to specify three parameters: start , stop , and step .

start is the counter’s initial value, step is by how much you want to increment until you reach the value of stop — 1 , because the value of stop is included.

The example bellow shows how to use range() with a step of 2 starting from 0.

for i in range(0,20,2): print(i)

Of course, you can use range() to specify any step you would like, so if you want a step of 5, just do:

for i in range(0,20,5): print(i)

Slicing

If you never heard of slicing before, I recommend you to read Understanding Slicing in Python first, there is also a video linked in the article if you prefer.

Slicing is useful when you want to apply a different step when working with a pre-defined list.

In this case I have a list numbers with the number from 1 to 16.

The logic is very similar to range() , since you also have a start , a stop , and a step .

In this case I’m starting on index 1, which is the number 2 in the list, remember lists are 0-indexed in Python.

I won’t put any stop value since I want to go until the last index.

Finally, I put a step of 2.

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in numbers[1::2]: print(i)

Another way to implement the slicing from the code above is to combine range() with len() :

numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] for i in range(1, len(numbers), 2): print(numbers[i])

Again, the same way we could use any step in range() , we can change the step in slicing to anything we would like.

What about about float values?

An extra trick is how to achieve the same thing with float values.

In this case you have to use the library numpy and its function arange .

This way you can use floats as start , stop , and step .

import numpy as np for i in np.arange(1.5, 2.5, 0.1): print (i)
1.5 1.6 1.7000000000000002 1.8000000000000003 1.9000000000000004 2.0000000000000004 2.1000000000000005 2.2000000000000006 2.3000000000000007 2.400000000000001

Watch this on Youtube:

Источник

How count by 2 with python?

Again, this is not the only or even the best way to do this, but it’s the way I’m using because it teaches a lot of basic strategies like writing modular programs (each function is performed by its own bit of code) and using functions rather than straight code to perform your task. It just defines functions that we’ll leverage to solve the problem at hand.

How count by 2 with python?

Your var, number , is of the type string . You have to convert it to a ‘number’ like type, like float or int before you can calculate with it. To do this, wrap int() around your raw_input() call and change your while loop to check for < 4 rather than < '4' . To have it calculate as you want, using steps of two, you should use xrange . Example:

number = int(raw_input("Please enter a number:")) while number < 4: number = int(raw_input("Please enter a number bigger than 4:")) for i in xrange(4, number+1, 2): print i 
number = raw_input ("Please enter a number:") while number < '4': print raw_input("Please enter a number bigger than 4:") number += 1 

The error message says, you are trying to add 1 to a string. This is why you are getting error. You know you can't count with strings. So you should change your codes to;

x=2 while True: try: number=int(raw_input ("Please enter a number: ")) except ValueError: #catching ValueError, if user entry something that is not number print("You should enter a number.") continue #if user entry something that is not number, then skip other codes ask again. if number 
>>> Please enter a number: 3 Please enter a number bigger than 4 Please enter a number: 10 2 4 6 8 10 >>> >>> Please enter a number: 2 Please enter a number bigger than 4 Please enter a number: asd You should enter a number. Please enter a number: 10 2 4 6 8 10 >>> 
n = raw_input("Please enter a number:") n = int(n) i = 2 while i 

How to count by twos with Python's 'range', 3 Answers. Sorted by: 66. Use the step argument (the last, optional): for x in range (0, 100, 2): print (x) Note that if you actually want to keep the odd numbers, it becomes: for x in range (1, 100, 2): print (x) … Code samplefor x in range(1, 100, 2):print(x)Feedback

Python 3 - Counting up with two different values

You can use itertools.cycle for this

import itertools a = 0 it = itertools.cycle((2,3)) while a < 100: a += next(it) print(a) 

The itertools.cycle generator will just continuously loop back over the tuple as many times as you call it.

You need to print the content of a after adding two, and after adding three:

That being said, you can better construct a generator, that iteratively adds two and three interleaved:

def add_two_three(a): while True: a += 2 yield a a += 3 yield a 

You can then print the content of the generator until it hits 100 or more:

from itertools import takewhile print(' '.join(takewhile(lambda x: x < 100,add_two_three(0)))) 

You have to increment a with different value each time (2 and 3). You can just swap the two values being used to increment a on each iteration to achieve this.

a = 0 inc1 = 2 # values being used to increment a inc2 = 3 while a < 100: a = a + inc1 inc1, inc2 = inc2, inc1 # swap the values print(a, end=' ') 

Counting - how count by 2 with python?, Also it's kind of a strange way to count by two. There's a range function for that in Python, which takes an optional third argument for step. for count in range(1, number+1, 2): print count Share. Improve this answer. Follow edited May 23, 2017 at 12:20. Community Bot

Counting numbers in a range

Just for example's sake, let's write a function that counts how many numbers are above 50, then one for equal to 50, then one for less than 50. Disclaimer: this is not the only, or even the BEST way to accomplish what you want to do, this is just the best teaching aid :). Also, some of the nomenclature may change if you're not using Python 3.x.

#this function returns how many values in the list that's passed to it #are greater than 50 def greaterThanFifty(list_to_compare): how_many_above_fifty = 0 for value in list_to_compare: if value > 50: how_many_above_fifty += 1 return how_many_above_fifty #this function returns how many values in the list that's passed to it #are less than 50 def lessThanFifty(list_to_compare): how_many_under_fifty = 0 for value in list_to_compare: if value < 50: how_many_under_fifty += 1 return how_many_under_fifty #this function returns how many values in the list that's passed to it #are equal to 50 def equalToFifty(list_to_compare): how_many_are_fifty = 0 for value in list_to_compare: if value == 50: how_many_are_fifty += 1 return how_many_are_fifty 

Now we have our functions that will return the values we need. Again, this is not the only or even the best way to do this, but it's the way I'm using because it teaches a lot of basic strategies like writing modular programs (each function is performed by its own bit of code) and using functions rather than straight code to perform your task. Unfortunately, on their own, this code doesn't do anything. It just defines functions that we'll leverage to solve the problem at hand. In essence -- we've made our hammer, nails, and saw, but now we have to cut the lumber to size and nail it up. Let's do that.

def main(): #this is always the name of our function that does the heavy lifting list_of_numbers = [] user_input = input("List some numbers, comma separated please: ") for num in user_input.split(","): #loop through user_input, split by commas list_of_numbers.append(num.strip()) #add to list_of_numbers each item that we find in user_input, #stripped of leading and trailing whitespace #at this point we've looped through all of user_input and added each number #to list_of_numbers, so we can use our functions, defined earlier, to return #the requested values. Luckily we set up our functions to accept #lists! greater_than_fifty = greaterThanFifty(list_of_numbers) less_than_fifty = lessThanFifty(list_of_numbers) equal_to_fifty = equalToFifty(list_of_numbers) #now just to display the results to the user, and we're done. print("There are "+str(greater_than_fifty)+" numbers over fifty") print("There are "+str(less_than_fifty)"+ numbers under fifty") print("There are "+str(equal_to_fifty)"+ numbers that are fifty") 

We still haven't actually DONE anything, though, since all we've done is define functions that do what we want from start to finish. our greaterThanFifty function is our hammer, our lessThanFifty function is our saw, and our equalToFifty function is our nails. Now we've added a main function, which is our handyman. Now we need to tell him to work. Luckily that's easy 🙂

For comparison purposes, this is how I'd write all that:

input_list = [int(each.strip()) for each in input("Enter a list of numbers, comma-separated: ").split(",")] print("<> are less than 50, <> are more than 50, <> are 50".format(len([each for each in input_list if each<50]),len([each for each in input_list if each>50]),len([each for each in input_list if each==50]))) 

You'll get there, young padawan 🙂

def main(): inp = input('enter number of positive numbers to enter ') print 'enter the list of positive numbers' num = [] count_eq = 0 count_gr = 0 count_ls = 0 for elem in range(inp): num.append(input('')) for item in num: if item == 50: count_eq += 1 if item > 50: count_gr += 1 if item < 50: count_ls += 1 print '%d are equal %d are less than and %d are greater than 50' % (count_eq, count_ls, count_gr) main() 

This is a very basic program ! You should start python's beginner tutorial here

Count numbers between a range in python, for i in range(a, b): These will start from 5 to 8. If i use like below . for i in (a, b): These will print 5 and 8. Now i need a help from you, if a = 5 and 8 means i need find the the range between 5 to 8 is 1 to 4 and form for loop 1 to 4 . if a = 3 and 5 means i need find the the range between 3 to 5 is 1 to 3 and form for …

Источник

Читайте также:  Document
Оцените статью