Blockchain technology has revolutionized digital transactions, and Python—thanks to libraries like Web3.py—has become a powerful tool for developers to interact with Ethereum and other EVM-compatible networks. This comprehensive guide walks you through the process of connecting to the Ethereum blockchain, creating accounts, and transferring tokens using Python—all while following best practices for security and usability.
Whether you're new to blockchain development or expanding your skill set, this tutorial provides hands-on experience with real-world applications of Web3.py.
Setting Up Your Environment
To begin interacting with the Ethereum blockchain using Python, you'll need a few essential tools. First, ensure that Python 3 is installed on your system. Most modern operating systems support it natively or via package managers like brew (macOS) or apt (Linux).
Next, install the web3.py library:
pip install web3We’ll also use Infura, a popular Web3 infrastructure provider, as our API gateway to the Ethereum network. Infura allows developers to connect to Ethereum without running a full node.
👉 Get started with blockchain development using powerful tools and resources.
Connecting to the Ethereum Testnet
In this tutorial, we’ll use the Rinkeby testnet (note: deprecated but still referenced in legacy tutorials; consider Goerli or Sepolia for 2025+), which enables experimentation without spending real funds.
Start your Python interpreter:
$ python3
>>> from web3 import Web3, HTTPProvider
>>> import jsonNow initialize a connection using an Infura endpoint:
>>> w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/YOUR_PROJECT_ID"))Replace YOUR_PROJECT_ID with your actual Infura project ID. You can obtain one by signing up at Infura.io.
⚠️ Always include https:// in your endpoint URL—omitting it will result in connection errors.Since Rinkeby uses Proof-of-Authority (PoA), inject the appropriate middleware:
>>> from web3.middleware import geth_poa_middleware
>>> w3.middleware_onion.inject(geth_poa_middleware, layer=0)Verify your connection:
>>> w3.isConnected()
TrueIf this returns True, congratulations—you're connected to the Ethereum blockchain!
Troubleshooting Connection Issues
- Double-check your Infura URL and project ID.
- Ensure
web3.pyis properly installed. - Confirm you've included
https://. - Re-import modules if restarting the interpreter.
Creating an Ethereum Account
To send transactions, you need an Ethereum account. Web3.py allows you to generate one directly in Python:
>>> my_account = w3.eth.account.create('Nobody expects the Spanish Inquisition!')
>>> my_account.address
'0x5b580eB23Fca4f0936127335a92f722905286738'
>>> my_account.private_key
HexBytes('0x265434629c3d2e652550d62225adcb2813d3ac32c6e07c8c39b5cc1efbca18b3')This generates a public address and private key pair using cryptographic entropy derived from the input string. However, never use predictable phrases in production—doing so compromises security.
🔐 For real-world applications, rely on secure wallets like MetaMask or Geth to manage keys.
Understanding ENS: Human-Readable Addresses
Ethereum addresses are long hexadecimal strings—difficult to remember and prone to input errors. The Ethereum Name Service (ENS) solves this by mapping readable names (e.g., coogan.eth) to addresses.
While .eth domains are only available on mainnet, ENS support is integrated into many dApps and developer tools—including Web3.py. In future projects, you can resolve ENS names like this:
w3.to_checksum_address("coogan.eth")This simplifies user interaction and reduces transaction risks caused by incorrect address entry.
Interacting with Smart Contracts: Transferring Tokens
One of the most common tasks in Web3 development is transferring tokens—especially stablecoins like Dai, which maintain a 1:1 value with the US dollar.
What Is Dai?
Dai is a decentralized stablecoin built on Ethereum. Unlike volatile cryptocurrencies like ETH or BTC, Dai offers price stability, making it ideal for payments, lending, and trading within DeFi ecosystems.
To transfer Dai, we interact with its smart contract—a self-executing program deployed on the blockchain.
Contract Instantiation with ABI
To communicate with a smart contract, Web3.py needs two things:
- The contract’s address
- Its Application Binary Interface (ABI)
The ABI defines available functions and their parameters. Since ABIs aren’t stored on-chain, developers must retrieve them from sources like Etherscan or GitHub.
Here’s the truncated ABI for the testnet Dai contract:
abi = '''[{"constant":true,"inputs":[],"name":"name",...}]'''Parse it using JSON:
>>> abi = json.loads(abi)Set the contract address (for testnet Dai):
>>> address = '0xc3dbf84Abb494ce5199D5d4D815b10EC29529ff8'Instantiate the contract object:
>>> dai = w3.eth.contract(address=address, abi=abi)Test the connection by checking total supply:
>>> dai.functions.totalSupply().call()
10100000000000101001376883458034812485564519This confirms successful contract interaction.
Building and Sending a Token Transfer
Now, let’s transfer Dai from our generated account to another.
Use the transfer function defined in the ABI:
transaction = dai.functions.transfer(
'0xRecipientAddressHere',
1000000000000000000 # 1 DAI (18 decimals)
).build_transaction({
'from': my_account.address,
'nonce': w3.eth.get_transaction_count(my_account.address),
'gas': 200000,
'gasPrice': w3.toWei('50', 'gwei')
})Sign and send the transaction:
signed_txn = w3.eth.account.sign_transaction(transaction, my_account.private_key)
txn_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(f"Transaction hash: {w3.toHex(txn_hash)}")You can monitor the transaction on a block explorer using the returned hash.
👉 Explore decentralized finance tools to manage and transfer digital assets securely.
Frequently Asked Questions
Can I use Web3.py on mainnet?
Yes. Simply switch the Infura endpoint from rinkeby.infura.io to mainnet.infura.io and ensure your account holds ETH for gas fees.
Is it safe to generate private keys in code?
Only for educational purposes. In production, use secure key management solutions like hardware wallets or encrypted key stores.
Why do I need an ABI?
The ABI tells Web3.py what functions the smart contract exposes and how to encode calls correctly. Without it, interaction isn't possible.
What is the difference between ETH and DAI transfers?
ETH transfers use w3.eth.send_transaction, while token transfers (like DAI) require calling methods on their respective smart contracts.
How do I check my token balance?
Use the contract’s balanceOf function:
dai.functions.balanceOf(my_account.address).call()Can I automate multiple transfers?
Yes. Wrap the transfer logic in a loop or function and batch transactions carefully, managing nonces and gas limits.
Final Thoughts
Mastering Web3.py opens doors to building powerful decentralized applications—from automated trading bots to NFT mints and DeFi integrations. This tutorial covered core skills: connecting to Ethereum, generating accounts, and transferring tokens via smart contracts.
As you advance, explore topics like event listening, contract deployment, and interacting with other protocols such as Uniswap or Aave.
👉 Level up your blockchain development journey with cutting-edge tools and insights.
By combining Python’s simplicity with Ethereum’s robustness, you’re well-equipped to innovate in the rapidly evolving world of Web3.