how to declare variable type, C style in python
Python isn't necessarily easier/faster than C, though it's possible that it's simpler ;)
To clarify another statement you made, "you don't have to declare the data type" - it should be restated that you can't declare the data type. When you assign a value to a variable, the type of the value becomes the type of the variable. It's a subtle difference, but different nonetheless.
Edit: Python 3.5 introduced type hints which introduced a way to specify the type of a variable. This answer was written before this feature became available.
There is no way to declare variables in Python, since neither "declaration" nor "variables" in the C sense exist. This will bind the three names to the same object:
x = y = z = 0
Starting with Python 3.6, you can declare types of variables and funtions, like this :
explicit_number: type
or for a function
def function(explicit_number: type) -> type:
pass
This example from this post: How to Use Static Type Checking in Python 3.6 is more explicit
from typing import Dict
def get_first_name(full_name: str) -> str:
return full_name.split(" ")[0]
fallback_name: Dict[str, str] = {
"first_name": "UserFirstName",
"last_name": "UserLastName"
}
raw_name: str = input("Please enter your name: ")
first_name: str = get_first_name(raw_name)
# If the user didn't type anything in, use the fallback name
if not first_name:
first_name = get_first_name(fallback_name)
print(f"Hi, {first_name}!")
See the docs for the typing
module
Simply said: Typing in python is useful for hinting only.
x: int = 0
y: int = 0
z: int = 0