I’m new to Python and I’m finding this weird (and amazing). Can someone explain?
a = 2.0
b = 3.1
if b==3.1:
print "%f"%a
a = "Hi!"
print "%s"%a
print "%s"%a
Output:
2.000000
Hi!
Hi!
How is the type of a changing from float to string?
How can something similar be done in C/C++ ?
Python is a dynamically typed language, meaning that the same variables can refer to objects of different types. Languages like C, C++ and Java are statically typed, meaning that types are determined at compile time.
In statically typed languages which support object-oriented programming, like C++, you can use inheritance and polymorphism (base class pointers) to refer to multiple objects of different sub-class types, but it is not as flexible as the “duck typing” you get in Python.
In C and C++ you can also use generic
void*pointers to point to an object of any type, but you lose the type-safety provided by the compiler.