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>
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 | 不相等 |
-
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>
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>
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>
- 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>
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>
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>
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>
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>
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>
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!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

WebStorm Mac version
Useful JavaScript development tools

Atom editor mac version download
The most popular open source editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
