Table of Contents
What are data types?
Numbers - Integers and their variants
Home Backend Development Python Tutorial Vyper Data Types (Series 2)

Vyper Data Types (Series 2)

Jan 16, 2025 pm 12:28 PM

Vyper Data Types (Series 2)

Previously, we discussed why Vyper is a game changer as it is one of the fastest growing smart contract development languages.

We also covered some basics like Pragma and Constructor. You can read it here.

Today we’ll take a deep dive into data types and how they work.

What are data types?

Data types help us organize different information in our code, just like we sort items into specific locations at home.

These types are set before the program is run. Just like a container designed for liquids is not suitable for storing solids, each variable in Vyper can only store the data type for which it was designed.

When writing code, we need to specify what data type each variable will hold - whether it's a number for calculations, text for a name, or true/false for simple decisions. These types ensure that our programs handle information correctly, preventing errors such as trying to multiply someone's name or add letters together.

Understanding data types in Vyper

  • Boolean - simple true/false

Think of Boolean values ​​like light switches - they can only be in two states: true or false. We use them in our code to make yes/no decisions.

<code>is_active: bool = True
is_paused: bool = False

# 可以翻转布尔值
is_active = not is_active  # 现在是 False</code>
Copy after login
Copy after login
Copy after login
Copy after login

Certain operators can be used effectively with boolean values, including not, or == and !=. This means we can use them to prove truth or falsehood.

**运算符** **描述**
not x 逻辑否定
x and y 逻辑合取
x or y 逻辑析取
x == y 相等
x != y 不相等
Think of these operators as ways to make decisions in your code:
  • not x - flip true/false values ​​to their opposites

    is_door_locked = True
    is_door_unlocked = not is_door_locked # Result: False

It's like saying "opposite" - if the door is locked, then being unlocked means it's open.

  • x and y - both conditions must be true

    has_ticket = True
    has_id = True
    can_board_plane = has_ticket and has_id # Result: True

Just like you need a ticket and ID to board a plane, both values ​​must be true for the result to be true.

  • x or y - at least one condition must be true.

    has_cash = False
    has_credit_card = True
    can_pay = has_cash or has_credit_card # Result: True

For example, when paying, you can use cash or credit card; you need one of these to be true.

  • x == y - checks if two values ​​are the same

    password = "secret123"
    entry = "secret123"
    is_correct = password == entry # Result: True

It's like checking if two keys are the same.

  • x != y - checks if two values ​​are different

    expected_price = 100
    actual_price = 90
    price_changed = expected_price != actual_price # Result: True

This is like checking to see if something is different, such as noticing that a price is different than expected. These operators help you make logical Boolean decisions.

Numbers - Integers and their variants

When using numbers in smart contracts, Vyper provides two basic methods for handling integers: signed integers and unsigned integers. Each method has its specific purpose, and understanding their differences is critical to writing efficient and safe code.

  • Signed integer

Signed integers are probably the most versatile number type in Vyper, capable of representing both positive and negative values. Think of a bank account - you can make deposits (positive numbers) and withdraw money (negative numbers). This is where signed integers shine. When you declare a variable such as age: int8 = -5, you are telling Vyper to reserve 8 bits of space, which can hold any number between -128 and 127.

<code>is_active: bool = True
is_paused: bool = False

# 可以翻转布尔值
is_active = not is_active  # 现在是 False</code>
Copy after login
Copy after login
Copy after login
Copy after login

For larger values, Vyper provides larger storage capacity. The int256 type is typically used for a large number of numerical operations and can handle larger numbers. Consider tracking a company's profit and loss: balance: int256 = 1000. This can represent a large financial move in either direction.

  • Unsigned integer

Some values ​​in the real world are never negative. You cannot have -3 apples or -5 users. This is where unsigned integers come into play. A statement like quantity: uint8 = 255 is perfect for inventory systems or user counting.

The uint8 type effectively uses 8 bits to store values ​​between 0 and 255, making it ideal for small positive numbers.

<code>is_active: bool = True
is_paused: bool = False

# 可以翻转布尔值
is_active = not is_active  # 现在是 False</code>
Copy after login
Copy after login
Copy after login
Copy after login

The most commonly used unsigned integer in Vyper is uint256. When you write price: uint256 = 1000 you create a variable that can hold a huge positive number, perfect for the number of tokens or the wei value in an Ethereum transaction.

  • Decimal

When you need to use decimal points for precise calculations

<code># 有符号整数(可以为正数或负数)
age: int8 = -5          # 存储范围为 -128 到 127
balance: int256 = 1000  # 较大的范围用于更大的数字</code>
Copy after login
  • Address - for Ethereum accounts

We use addresses every day to identify locations - your home, a store or a friend's home. In the Ethereum world, addresses work similarly, but instead of pointing to a physical location, they point to digital wallets and smart contracts. Let’s explore what makes these addresses unique and how they work in Vyper.

What is an Ethereum address?

<code># 无符号整数(只有正数)
quantity: uint8 = 255   # 存储范围为 0 到 255
price: uint256 = 1000   # 常用于存储大型正数</code>
Copy after login

Think of your Ethereum address as a unique digital mailbox. Just like your home address ensures that mail reaches only you, an Ethereum address ensures that cryptocurrencies and digital assets reach their intended destination. In Vyper we use a special type called address to handle these addresses.

When you write something like:

<code>price: decimal = 19.99  # 适用于财务计算
tax_rate: decimal = 0.15</code>
Copy after login

You are creating a variable that can only store valid Ethereum addresses. These addresses always start with "0x" followed by 40 characters consisting of numbers (0-9) and letters (a-f).

Real world examples Let's say you are building a simple digital wallet contract. You can store the address like this:

<code>owner: address = 0x123...  # 存储钱包地址
contract: address = 0xABC...</code>
Copy after login

Use address Addresses in Vyper have special properties. You can check the following:

  • How many Ether coins does one address hold
  • Whether an address belongs to a smart contract
  • The code is stored in the contract address

For example, checking the balance of an address is as simple as this:

<code>owner: address = 0x71C7656EC7ab88b098defB751B7401B5f6d8976F</code>
Copy after login

Addresses help us navigate the blockchain, ensuring our digital assets and interactions reach their intended destination safely and reliably.

  • byte array - for raw data

In Vyper, byte arrays are used to process raw binary data. Think of them as containers for storing information that a computer can directly process. Byte arrays are particularly useful when working with files, cryptographic hashes, or binary operations.

<code># 钱包的所有者
owner: address = 0x71C7656EC7ab88b098defB751B7401B5f6d8976F



# 可靠的备份地址
backup_wallet: address = 0x8626f6940E2eb28930eFb4CeF49B2d1F2C9C1199</code>
Copy after login

Static byte array Static byte arrays have a fixed size and cannot be changed. This makes it simple and efficient.

Example: Storing a fixed size hash Suppose you have a unique code such as a fingerprint that is always 32 bytes long. Here's how to store it in Vyper.

fixed_code: bytes32 This means bytes32 will always be 32 bytes.

Dynamic byte array

A dynamic byte array can accommodate data of different lengths if it does not exceed the maximum size. It helps in storing content like short messages.

Example: Save a short message Suppose you want to save a message, such as "Hello, World!", which can be up to 100 bytes long:

<code>is_active: bool = True
is_paused: bool = False

# 可以翻转布尔值
is_active = not is_active  # 现在是 False</code>
Copy after login
Copy after login
Copy after login
Copy after login

Okay, that’s it for today’s study. Our next article will examine more data types and understand their capabilities.

To read more of the above, check out the Vyper documentation and Vyper examples.

The above is the detailed content of Vyper Data Types (Series 2). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

How to get news data bypassing Investing.com's anti-crawler mechanism? How to get news data bypassing Investing.com's anti-crawler mechanism? Apr 02, 2025 am 07:03 AM

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...

See all articles