简体   繁体   中英

Python Type Casting with Print

Why does this return a class/type of 'NoneType'?

The input is a string. I have cast type to an int...

first_digit = print(int(two_digit_number[0]))
print(type(first_digit))

I know that the following will return class/type of int:

first_digit = int(two_digit_number[0])

But, I don't understand why adding print creates a NoneType class. FYI, I'm on day 2 of learning Python.

Functions that don't return anything return a None (of NoneType ) by default. Print doesn't return what it printed or anything else, just None .

print function doesn't have a return value. Assigning it to a variable makes its value None of type NoneType .

Print is a function to print something on screen it did not return anything to user so it return None

In its most simple view you are doing this:

first_digit = print(1)

What's the value of first_digit ? It is NoneType because you did not assign any value to the first_digit .

Try this instead:

[ins] In [14]: first_digit = 1

[ins] In [15]: print(type(first_digit))
<class 'int'>

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM