> For the complete documentation index, see [llms.txt](https://learn.qanplatform.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://learn.qanplatform.com/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/python-smart-contract/writing-a-smart-contract-in-python.md).

# Writing a smart contract in Python

### Sample contract functionality

The sample contract serves as a demonstration of general QVM logic.

It is capable of:

* registering users into the database
* storing the last registered user's name in the database
* echoing the previous user's name to STDOUT
* incrementing the total registered user count
* storing above counter in the database

### Sample smart contract code

```python
import os
import sys

def getenv(key, deft):
    return os.getenv(key) or deft

def get_int_env(key, deft):
    try:
        return int(getenv(key, ""))
    except Exception:
        return deft

def stdout_writeln(s):
    sys.stdout.write(s + "\n")

def stderr_writeln(s):
    sys.stderr.write(s + "\n")

def contract(argv):
    
    # THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
    if len(argv) == 3 and argv[1] == "register":
        
        # GET THE CURRENT USER'S NAME OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
        previous_name = getenv("DB_USER_CURRENT", "unknown")
        
        # GET THE TOTAL USER COUNT
        total_user_count = get_int_env("DB_TOTALUSERS", 0)
        
        # WRITE PREVIOUS USER NAME TO STDOUT
        stdout_writeln("OUT=prevname: " + previous_name)

        # UPDATE CURRENT USER NAME BY WRITING IT TO DB
        stdout_writeln("DBW=USER_CURRENT=" + argv[2])

        # STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
        stdout_writeln("DBW=USER_%d=%s" % (total_user_count, argv[2]))

        # INCREMENT THE TOTAL USER COUNT
        stdout_writeln("DBW=TOTALUSERS=%d" % (total_user_count+1))

        # CONTRACT RAN SUCCESSFULLY, EXIT WITH ZERO CODE
        sys.exit(0)

    # WRONG INVOCATION
    if len(argv) >= 2:
        stderr_writeln("Wrong CMD: %s" % argv[1])
        sys.exit(1)

    stderr_writeln("Wrong argv!")
    sys.exit(1)


if __name__ == '__main__':
    contract(sys.argv)
```

### Save the smart contract

Open a text editor and save above sample contract as `main.py` file.

{% content-ref url="/pages/2EyW530TwTg38Rgiurq3" %}
[Compiling a smart contract in Python](/developers/qvm-multi-language-smart-contracts/docs-for-supported-languages/python-smart-contract/compiling-a-smart-contract-in-python.md)
{% endcontent-ref %}
