For loops that include range in python3

Related searches

I need to define a function receives a string that is made of numbers and checks the following requirement:

  1. the string isnt empty
  2. the first character is in range (1,10)
  3. every character besides the first is in range (0,10) if the string answers all the requirements return True, else return False.

What ive tried is if in for loops and vice versa.

I've also tried moving the return function in the following code to different indentations which didn't help

def is_positive_int(st):
n = len(st)
if n > 0:
    if st[0]>= 0 and st[0]<= 9:
        for i in range(1,n):
            if st[i]>= 0 and st[i]<= 9
        return True

I've also tried:

def is_positive_int(st):
n = len(st)
for n > 0:
    if st[0] >= 1 and st[0]<=9:
        for i in range (1,n):
            if st[i]>=1 and st[i]<= 9
        return True
    else:
        return False

which returns: invalid syntax for n > 0 (I'm not sure why)

For example:

print(is_positive_int("123")) 
should return True

Where as

print(is_positive_int("123.0")) 
should return False

And

print(is_positive_int("0")) 
should return False

You can also just iterate over the string:

for character in st:
    # your conditionals 

Then use character in place of st[i]

But also note, that with the conditionals you can not compare a string with a number. So what you should do is either make a set of the digits or use the isdigit() method for strings. Taking it all together your function should be something like this:

def is_positive_int(st):
   if not (st and st[0] != '0'):
       return False

   for character in st:
       if not character.isdigit():
           return False

   return True

Python range() Function Explained with Examples, For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. (Python 3 uses the range function, which acts like xrange). the first character is in range (1,10) every character besides the first is in range (0,10) if the string answers all the requirements return True, else return False. What ive tried is if in for loops and vice versa. I've also tried moving the return function in the following code to different indentations which didn't help

I can suggest 2 alternative approaches:

Option 1: iterate directly over the string and compare each char to allowed chars for each position (do not compare chars to numbers).

import string

def func(input_str):
    if len(input_str) == 0:
        return False

    for i, c in enumerate(input_str):
        if i == 0:
            allowed_chars = string.digits[1:]       # exclude '0'
        else:
            allowed_chars = string.digits

        if c not in allowed_chars:
            return False

    return True

Option 2: use regular expressions; I know that they aren't always a solution, but in this case they allow for a really short code solution.

import re

def func(input_str):
    if re.match(r'^[1-9][0-9]*$', input_str):
        return True

    return False

Does this help?

For Loops in Python 3, You can also just iterate over the string: for character in st: # your conditionals. Then use character in place of st[i]. But also note, that with the� For loop with range. In the previous lessons we dealt with sequential programs and conditions. Often the program needs to repeat some block several times. That's where the loops come in handy. There are for and while loop operators in Python, in this lesson we cover for. for loop iterates over any sequence.

Try this If you input something that isnt a string that can convert to int, it will run the except condition. len(input)>1 just confirms that there is a second digit

def is_positive_int(input):
    try:
        if int(input[0]) in range(1,10) and int(input) and len(input)>1:
            return True
        else:
            return False
    except:
        print('invalid input')

Loops - Learn Python, One of Python’s built-in immutable sequence types is range (). In loops, range () is used to control how many times the loop will be repeated. When working with range (), you can pass between 1 and 3 integer arguments to it: start states the integer value at which the sequence begins, if this is not included then start begins at 0

Use range(len(iterable)) to iterate over the indexes of an iterable:

def is_positive_int(string):
    positive_ints = {1, 2, 3, 4, 5, 6, 7, 8, 9}

    if len(string) == 0:
        return False
    if int(string[0]) not in positive_ints:
        return False

    for i in range(1, len(string)):
        if int(string[i]) not in (positive_ints | {0}):
            return False

    return True

Note the use of sets to define accepted numbers, since it's an efficient data structure for this purpose, and could also be constructed dynamically with positive_ints = set(range(1,10)).

The int() calls are there because the elements of the string (string[i]) will be strings, and would always compare to false since 1 == "1" is False.

Lastly, the cascading style of returns is often preferred as it skips parts of the function that won't be relevant and only returns True if nothing else stops it until the end.

Instead of operating on indexes, you can iterate on the characters of the string themselves:

def is_positive_int(string):
    positive_ints = set(range(1, 10))

    if len(string) == 0:
        return False
    if int(string[0]) not in positive_ints:
        return False

    for character in string:
        if int(character) not in (positive_ints | {0}):
            return False

    return True

Note that both of these will raise an exception if a character in the string cannot be converted to int. This can be prevented by converting the numbers to string instead:

def is_positive_int(string):
    positive_ints = set(str(x) for x in range(1, 10))

    if len(string) == 0:
        return False
    if string[0] not in positive_ints:
        return False

    for i in range(1, len(string)):
        if string[i] not in (positive_ints | {"0"}):
            return False

    return True

For loops that include range in python3, The for statement in Python has the ability to iterate over the items of any sequence, such as a list or a string. for iterating_var in sequence: statements(s) If a sequence contains an expression list, it is evaluated first. Then, the first item in the sequence is assigned to the iterating variable

You need to convert the entries in your string to int, otherwise your conditional statements will throw an error:

your code:

def is_positive_int(st):
    n = len(st)
    if n > 0:
        if (st[0]>= 0) and (st[0]<= 9):
            for i in range(1,n):
                if st[i]>= 0 and st[i]<= 9:
                    return True

Should throw an error. At least it does when I run it on '123'

TypeError: '>=' not supported between instances of 'str' and 'int'

So, you could change to:

def is_positive_int(st):
    n = len(st)
    if n > 0:
        if (int(st[0])>= 0) and (int(st[0])<= 9):
            for i in range(1,n):
                if int(st[i])>= 0 and int(st[i])<= 9:
                    return True

Since nowhere in this function it is asserted if there are non-digit characters, it cannot return False when encountering those. Contrary, it will throw an error, when it tries the conversion. So you could do:

def is_positive_int(st):
    entries = list(st)              # create a list of all items in the string
    if entries:                     # assert this list has length > 0
        output = True               # initialise output
        for e in entries:           
            output *= e.isdigit()   # update outputs : a single False will convert output to 0.
        return bool(output)         # convert output to boolean
    else:                           # if the string is empty, return False. 
        return False

The range () function is used to generate a sequence of numbers. range () is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Most common use of range () function in Python is to iterate sequence type (List, string etc..) with for and while loop. Python range () Basics :

To loop through a set of code a specified number of times, we can use the range () function, The range () function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

For loops in Python allow us to iterate over the values returned by any iterable object, in others words, any object that can yield a sequence of values. This the main different between for loops

Use of xrange() and range() in Python 2. range(1, 500) will generate a Python list of 499 integers in memory. So It will use high memory and increased execution speed; xrange(1, 500) function doesn’t generate all numbers at once. It produces number one by one as for loop moves to the next number. Use of range() in Python 3. Python 3’s range() function returns the range object, i.e., It doesn’t generate all numbers at once.

Comments
  • Stopping at the first issue: what do you anticipate for n > 0: to mean? n = len(st) is your stopping criteria, but nothing communicates that to your loop.
  • for n > 0 doesn't mean anything in Python, since for works on iterables. A while loop would work with it, but since n doesn't change, n > 0 will be either always True or always False unless you increment it inside the loop. Note that this sort of operation is usually done with for loops.
  • im not sure i understand, i need the string to not be empty, hence only if len(st)>0 can i check the next requirements
  • Sure, but I'm trying to make you think about how Python might see for n > 0. In isolation, what does that mean to you? Anything greater than 0, so it would be open-ended
  • thats right, im not trying to put an upper limit on the string length, only that it not be empty.
  • It is not advisable to use a blank except; rather use except ValueError: instead.
  • with this change it still returns True when i run a string such as "99.0", which should be returned as False
  • If you can avoide it you should not cast string to int as you will need all the try except clutter to catch all possible exceptions