简体   繁体   中英

how to declare variable type, C style in python

I'm a programming student and my teacher is starting with C to teach us the programming paradigms, he said it's ok if I deliver my homework in python (it's easier and faster for the homeworks). And I would like to have my code to be as close as possible as in plain C.
Question is:
How do I declare data types for variables in python like you do in C. ex:

int X,Y,Z;

I know I can do this in python:

x = 0
y = 0
z = 0

But that seems a lot of work and it misses the point of python being easier/faster than C. So, whats the shortest way to do this?
PS I know you don't have to declare the data type in python most of the time, but still I would like to do it so my code looks as much possible like classmates'.

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

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

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.

I'm surprised no one has pointed out that you actually can do this:

decimalTwenty = float(20)

In a lot of cases it is meaningless to type a variable, as it can be retyped at any time. However in the above example it could be useful. There are other type functions like this such as: int() , long() , float() and complex()

Simply said: Typing in python is useful for hinting only.

x: int = 0
y: int = 0 
z: int = 0

But strong types and variable definitions are actually there to make development easier. If you haven't thought these things through in advance you're not designing and developing code but merely hacking.

Loose types simply shift the complexity from "design/hack" time to run time.

Everything in Python is an object, and that includes classes, class instances, code in functions, libraries of functions called modules, as well as data values like integers, floating-point numbers, strings, or containers like lists and dictionaries. It even includes namespaces which are dictionary-like (or mapping) containers which are used to keep track of the associations between identifier names (character string objects) and to the objects which currently exist. An object can even have multiple names if two or more identifiers become associated with the same object.

Associating an identifier with an object is called "binding a name to the object". That's the closest thing to a variable declaration there is in Python. Names can be associated with different objects at different times, so it makes no sense to declare what type of data you're going to attach one to -- you just do it. Often it's done in one line or block of code which specifies both the name and a definition of the object's value causing it to be created, like <variable> = 0 or a function starting with a def <funcname> .

How this helps.

I use data types to assert unique values in python 2 and 3. Otherwise I cant make them work like a str or int types. However if you need to check a value that can have any type except a specific one, then they are mighty useful and make code read better.

Example : you might want to conditionally filter or print a value using a condition or a function handler.

from __future__ import print_function # for python2 & 3 to work
class unset(object):
    pass


def some_func(a,b, show_if=unset):
    result = a + b
    
    ## just return it
    if show_if is unset:
        return result
    
    ## handle show_if to conditionally output something
    if hasattr(show_if,'__call__'):
        if show_if(result):
            print("show_if("+ str(result) +")", result)
    elif show_if:
        print(show_if, " condition met ", result)
        
    return result
    
print("Are > 5)")
for i in range(10):
    result = some_func(i,2, show_if= i>5 )
    
def is_even(val):
    return not val % 2

print("Are even")
for i in range(10):
    result = some_func(i,2, show_if= is_even )

Output

Are > 5)
True  condition met  8
True  condition met  9
True  condition met  10
True  condition met  11
Are even
show_if(2) 2
show_if(4) 4
show_if(6) 6
show_if(8) 8
show_if(10) 10

if show_if=unset is perfect use case for this because its safer and reads well. I have also used them in enums which are not really a thing in python.

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