payment by upi: sinhamit@icici or payment by bank account name: amit kumar sinha, account number: 2646728782 IFSC code: KKBK0005660 SWIFT: KKBKINBB

Please support if you like my work by payment through upi: sinhamit@icici or payment by bank

account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB


range(), all(), any(), chr() built-in functions   in Category: Python   by amit

🕙 Posted on 2023-08-30 at 11:32:34     Read in Hindi ...


Some Built-in Functions

    You have already learned about various built-in functions, for example print(), input(), exit(), quit(), dir(), help(), type(), id(), len(), bool(), int(), float(), str(), list(), tuple(), dict(), set(), slice(), hash(), zip(), etc. in previous pages.

range()

Example 1:

a = range(12)
print( a, type(a) )   # Outputs range(0, 12) <class 'range'>

    The range() built-in function is used to create a special data-type, range, which is a sequence data-type object. However, you can use range() built-in function in conjunction with list(), tuple(), etc. built-in functions, which will produce index-based data-type literals. The syntax is range(start, stop, step ) where start is (inclusive) value at first index, stop (exclusive) is the numeric value, before which sequence will be stopped, and step is the increment or decrement value.

Example 2:

b = list(range( 10, 22, 2 ))
print( b, type(b) )   # Outputs [10, 12, 14, 16, 18, 20] <class 'list'>

Example 3:

c = list(range( 40, 22, -2 ))
print( c, type(c) )   # Outputs [40, 38, 36, 34, 32, 30, 28, 26, 24] <class 'list'>

Example 4:

d = tuple(range( 10, 22, 2 ))
print( d, type(d) )   # Outputs (10, 12, 14, 16, 18, 20) <class 'tuple'>

Example 5:

e = tuple(range( 40, 22, -2 ))
print( e, type(e) )   # Outputs (40, 38, 36, 34, 32, 30, 28, 26, 24) <class 'tuple'>

    Caution: In the above four examples, when you reverse start and stop values, that is when the step value is positive, and the start value is greater than the stop value, the range() function in conjun­ction with list() or tuple() function will create empty list or empty tuple, respect­ively. Similarly, when the step value is negative, and the start value is smaller than the stop value, the range() function in conjun­ction with list() or tuple() function will create empty list or empty tuple, respect­ively.

Examples:

print( range( 10, 2, 2 ) )   # Outputs range(10, 2, 2)

print( range( 10, 20, -2 ) )   # Outputs range(10, 20, -2)

print( list(range( 10, 2, 2 )) )   # Outputs []

print( list(range( 10, 20, -2 )) )   # Outputs []

print( tuple(range( 10, 2, 2 )) )   # Outputs ()

print( tuple(range( 10, 20, -2 )) )   # Outputs ()

    There may be other data-types also, either in Python core (that is, str() and set()) or other modules, which can create index-based sequence data-type. Those index-based sequence data-type can convert the output of range() built-in function as useful results. However, non-indexed data-types, such as dict() will output TypeError as shown below:

Example 6:

f = str(range( 10, 22, 2 ))
print( f, type(f) )   # Outputs range(10, 22, 2) <class 'str'>
g = set(range( 10, 22, 2 ))
print( g, type(g) )   # Outputs {10, 12, 14, 16, 18, 20} <class 'set'>

Example 7:

h = dict(range( 10, 22, 2 ))
print( h, type(h) )   # Outputs TypeError (as shown below)

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    o = dict(range( 10, 22, 2 ))
        ^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot convert dictionary update sequence element #0 to a sequence

    The range() built-in function has two methods: index() and count(), which are already discussed in previous page.

More about for loop

    You can use range() built-in function and for loop to create (traditional way of) for loop generally used in other program­ming languages, such as PHP, JavaScript, etc. This traditional way of creating for loop will be useful in WEB-APP pagination and other function­alities of such applic­ations. The code in PHP is only illust­rative here, and you should follow the instruc­tions provided in PHP language to execute following PHP codes:

PHP for Loop Examples:

<?php for( $i = 0; $i < 10; $i++ ) { echo $i . "<br />"; } /* PHP, JavaScript, etc. can be written in one line, when you don't use single-line comments. Output is same as following first Python script. */ ?>
<?php $my_var = "Hello World"; for( $i = 0; $i < strlen($my_var); $i++ ) { echo $i . " " . $my_var[$i] . "<br />"; } /* PHP, JavaScript, etc. can be written in one line, when you don't use single-line comments. Output is same as following second Python script. */ ?>

Python for Loop Examples:

Example 8:

for i in range(0, 10, 1):
    print(i)   # Output is shown below:

0
1
2
3
4
5
6
7
8
9

Example 9:

my_var = "Hello World"
for i in range(0, len(my_var), 1):
    print(i, my_var[i])   # Output is shown below:

0 H
1 e
2 l
3 l
4 o
5  
6 W
7 o
8 r
9 l
10 d

    You can omit optional arguments for start and step parameters, passed in above examples, when you want first item/character to be inclusive, and each item/character to be displayed or used in output from the for loop as shown in the first example of range() function.

Example 10:

my_var = "Hello World"
for i in range(0, len(my_var), 2):
    print(i, my_var[i])   # Output is shown below:

0 H
2 l
4 o
6 W
8 r
10 d

    Omitting only start argument will output NOTHING, because the range() built-in function will treat range(len(my_var), 2) same as equivalent to range(10, 2) (only start and stop arguments are passed.) The range() function either takes one argument (that is, stop), or two arguments (that is, start, stop), three arguments (that is, start, stop, step). For some methods and functions, you can pass keyword name and its respective value as argument, inside the paren­theses as per your choice, but range() does not take any keyword argument, and following ERROR will be shown.

Examples:

print( range( start=0, stop=10, step=2 ) )

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    print( range( start=0, stop=10, step=2 ) )
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: range() takes no keyword arguments

print( range( stop=10, step=2 ) )

Traceback (most recent call last):
  File "C:\xampp\htdocs\python2023\new.py", line 1, in <module>
    print( range( stop=10, step=2 ) )
            ^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: range() takes no keyword arguments

Some simple built-in functions

    In various progra­mming languages, some literals are called falsy values, for example, False, 0 (zero either integer or float), '' (empty string), [] (empty list), () (empty tuple), {} (empty dictionary/mapping), etc. are evaluated as same falsy value, and also when they are type-casted into other data-types. Some data-types (e.g. False, None or other non-iterables) cannot be type-casted into iterable data-types, such as list, tuple. Doing so will throw TypeError.

    All other literals are evaluated as True (or truthy value). Remember, [''], ('',) an item inside a pair of paren­theses when not followed by a comma symbol, is not treated as tuple literal, {''} when an item in a pair of curly braces is not in key:value pair, then that data-type is not dictionary, {None:''}, {'':None}, [[]], ((),), etc. are not empty, but these sequence literals contain an item, which is empty string/list/tuple, etc.

print( int( False ) )   # Outputs 0 (zero)

print( bool( 0 ) )   # Outputs False

print( bool( '' ) )   # Outputs False

print( bool( [] ) )   # Outputs False

print( bool( () ) )   # Outputs False

print( bool( None ) )   # Outputs False

print( bool( [''] ) )   # Outputs True

print( bool( ('',) ) )   # Outputs True

print( bool( {''} ) )   # Outputs True

print( bool( {'': None} ) )   # Outputs True

print( bool( {None: ''} ) )   # Outputs True

print( bool( [[]] ) )   # Outputs True

print( bool( ((),) ) )   # Outputs True

    These examples are described above to explain you that whenever you use falsy literals either in condition checking of control struc­tures/blocks (that is, if elif else), loops (for, while), other built-in functions, or custom functions, etc. you may not get expected result, because those condi­tions will be evaluated as False. Therefore, you should care­fully use these falsy values, also in following built-in funcitons.

abs(x)

Return the absolute value of the argument.

print( abs( -23.5 ) )   # Outputs 23.5

print( abs( False ) )   # Outputs 0

all(iterable, /)

Return True if bool(x) is True for all values x in the iterable. If the iterable is empty, return True.

    The all() built-in function checks whether all items in a list, a tuple, etc. are evaluated as True or not. When any item is evaluated as False, then all() function will output False.

print( all( [True, False, None] ) )   # Outputs False

print( all( [True, [[]], True] ) )   # Outputs True (at least one item should be inside the iterable, so that it is not empty.)

any(iterable, /)

Return True if bool(x) is True for any x in the iterable. If the iterable is empty, return False.

    The any() built-in function checks whether any item in a list, a tuple, etc. are evaluated as True or not. When all items are evaluated as False, then any() function will output False.

print( any( [True, False, True] ) )   # Outputs True

print( any( [[], (), ''] ) )   # Outputs False (When all items in the iterable are evaluated as False, then only output is False.)

chr(i, /)

Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.

print( chr( 90 ) )   # Output Z

print( chr( 2309 ) )   # Output เค… (First letter of HINDI language, however, you cannot see these types of characters in CONSOLE or VSCode Editor Terminal. In my MS-DOS console, when I had copied the output (by Ctrl C or Cmd C), and paste it in VSCode Editor, while writing this page, the output − is shown!)

    These UNICODE characters are described in UNICODE Symbols pages and you can display them (from 33 to 13311, and more...) in jupyter notebook by installing it either through Anaconda software, or as a module of Python as described below. You don't have to run jupyter notebook from your project folder, however, when you save your work after experi­menting or writing Python scripts, it will be saved in that folder, where you run following commands.

    If you are using Mac OS or Linus OS (ubuntu, centOS, etc.), you can run it, by typing python3 or python3.10 instead of simply python or py (usually run in Windows OS). Locate your project folder, as shown below. Install pip if it is not already installed in your system (PC). You can check version of your Python and pip by executing following commands.

C:\Users\yourName>cd \
C:\>cd xampp\htdocs\python2023

C:\xampp\htdocs\python2023>python --version
C:\xampp\htdocs\python2023>python -m pip --version

    If the above command does not show you the PIP version, so you can change directory to scripts within the folder where python program is installed. Or, you have not declared your Environ­ment Variable Path in your system. You should visit previous pages, to add to the Environ­ment Variable Path, PIP or install PIP, and then add its path.

C:\xampp\htdocs\python2023>pip --version
C:\xampp\htdocs\python2023>pip install --upgrade pip

C:\xampp\htdocs\python2023>python -m pip install --upgrade pip

    Now, you can install jupyter notebook in your Python library. If pip is installed, and pip --version is not showing the result, you may try pip3 instead of pip. Remaining syntax of these commands are same.

C:\xampp\htdocs\python2023>python -m pip install notebook

    A large number of modules will also be installed when you run the above command. Your PC (system) should have a good internet connection, to install respective modules, which are required in specific projects. Or, you can use the following command, and then check all the modules installed by next command.

C:\xampp\htdocs\python2023>python -m pip install jupyter
C:\xampp\htdocs\python2023>python -m pip list
C:\xampp\htdocs\python2023>python -m jupyter notebook

    When you execute the above command, the jupyter notebook will start running in WEB-BROWSER. You should not kill the VSCode Editor Terminal or Command Prompt Console. When you have done experiment and saving your work, you can kill/terminate jupyter notebook by switching to the VSCode Editor Terminal or Command Prompt Console, and pressing Ctrl C or Cmd C.

C:\xampp\htdocs\python2023>py -m jupyter notebook

_ _ _ _
| | | |_ __ __| |__ _| |_ ___
| |_| | '_ \/ _` / _` | _/ -_)
\___/| .__/\__,_\__,_|\__\___|
|_|

Read the migration plan to Notebook 7 to learn about the new features and the actions to take if you are using extensions.

https://jupyter-notebook.readthedocs.io/en/latest/migrate_to_notebook7.html

Please note that updating to Notebook 7 might break some of your extensions.

[I 13:12:58.708 NotebookApp] Serving notebooks from local directory:C:\xampp\htdocs\python2023
[I 13:12:58.708 NotebookApp] Jupyter Notebook 6.5.4 is running at:
[I 13:12:58.708 NotebookApp] http://localhost:8888/?token=2136257ca151da9865a862625ac1cf34c2204bfd3c034a5e
[I 13:12:58.708 NotebookApp] or http://127.0.0.1:8888/?token=2136257ca151da9865a862625ac1cf34c2204bfd3c034a5e
[I 13:12:58.708 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 13:12:58.802 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///C:/Users/priyamit/AppData/Roaming/jupyter/runtime/nbserver-6796-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=2136257ca151da9865a862625ac1cf34c2204bfd3c034a5e
    or http://127.0.0.1:8888/?token=2136257ca151da9865a862625ac1cf34c2204bfd3c034a5e

    To run jupyter notebook properly, you may need apache server to be installed on your computer. Therefore, I had already mentioned how to install XAMPP (including apache server, PHP, MySQL − a database which will be required when creating a PYTHON WEB APP.) Check your default web browser, or type in the address bar of WEB BROWSER: http://localhost:8888/ or http://127.0.0.1:8888/ if the jupyter notebook don't run itself. Don't copy the token in shown in above illustration.

running jupyter notebook

    You should remember two important commands in jupyter notebook:
(1) Shift Enter or Shift Return to execute the python codes, and
(2) Alt Enter or Option Return to go to the next line/cell.
You can directly run Python codes without print() function, and you will get output in the same browser window.

chr( 2309 )   # this will output (All rules of PYTHON progra­mming will be applied to run/execute codes properly.)

jupyter notebook python codes

    Many unicode symbols in between 33 and 13311 are not defined yet, hence you may not use some of them, for example, ΢ (Writing UNICODE symbol: &#930; in HTML, \\0930 in CSS, and simply 930 in Python, etc.). You can also see links of many EMOJI symbols (from 127744 to 129425) at the bottom of this page. In hexa-decimal, digits are from 0 to f (that is, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f). These six alpha-digits can also be written in uppercase. F is 15 (0 is first digit, hence F is sixteenth digit), FF is 255 (256-1), FFF is 4095 (16*16*16 - 1), and FFFF is 65535 (16*16*16*16 - 1). Hence, 10FFFF is 655359 (10*16*16*16*16 - 1).

    Some more built-in functions will be discussed in next page.


Leave a Comment: