Do I Have to Set Variable Types?


#1

Hello
I have a question about the variable declaration
do I have to write the type of the variable in Python as we do in Java ?
ex: String name , int num and char x?
Thank you.


FAQ: Learn Python - Python Syntax - Variables
FAQ: Learn Python - Python Syntax - Variables
#2

Hi @aljohara_r8,

Python automatically handles variable types. You can even change a variable’s type, like this:

num_eggs = 1 # int
num_eggs = "one" # string, same variable

#3

Python variables behave like a variable in Java with the type Object

That is, any variable can refer to any value regardless of type, and to figure out which type something has you would inspect the value, not the variable

Python doesn’t care nearly as much about types as Java does. Python does what the code says. If something isn’t possible, it’ll fail and an exception is raised.