Python has many built-in functions that are very useful. In this article, we will see few of them and how they can be used to make our life easier.
Example 1 : Simple range function
The range() function is used to create lists of numbers in a given range. This function can be used to create lists of numbers in a given range. Here are some examples:
- Create list of numbers from 1 to 10:
>>>range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- Create list of numbers from 0 to 99:
>>>range(100)
Example 2 : Show all the numbers in a range
The range() function returns a sequence of numbers. You can pass it two arguments to specify the start and end of the sequence that is returned.
A simple example would be:
range(10) yields [0, 1, 2, 3, 4, 5 ,6 ,7 ,8 ,9]
range (10) – This returns a list of integers starting at 0 and ending at 9. The result will be an empty list if you ask for something outside this range such as range(10) – This returns an empty list since there are no even numbers in between 0 and 2
Example 3 : Show only even numbers within a range
The range() function is used to create lists of numbers. The first number in the list is 0 and the last number in the list is 1 less than the second argument.
The Python equivalent of this code would be:
# example 3
import random
random_numbers = [i for i in random.randint(0, 2)]
Example 4 : Show only odd numbers within a range
To display only the odd numbers in a range, you can use the following code:
range(2,10,2)
Example 5 : Check whether a number exist in the range
- Check whether a number exists in the range
We can use the in operator to check if a number is in a range. For example, If you want to know if 9 exists in [1-10], then use the following.
“`python
print(9 in [1,2,3]) #True
“`
The above code will print “True” because 9 is present in [1, 2, 3] .You can also use not in operator to check if a number does not exist in a range. For example: :: ::: “`python > print(9 not in [1-10]) #False > print(5 not in [1-10]) #False > print(8 not in [1-10]) #True > print(“Concept” notin[0 – 10]) False “` The above code will produce following result: True False False True
The range function is a powerful tool that can be used for multiple purposes. It is a great tool to use when you are working with lists and arrays of data, as well as for generating random numbers. There are numerous other functions available in Python 3 which can help make your code more efficient and readable at the same time.