Understand Variables and Data Types Using Cricket Stats
SkillVeris Team
Content Team
A variable is a labelled box — exactly like a column on a cricket scorecard, with a name and a value underneath it.
In this guide, you'll learn:
- Python's four core types map cleanly to cricket: int (runs/balls), float (strike rate/average), str (names), bool (out/not-out).
- Type casting with int(), float(), and str() converts between types safely — essential when reading data from files or forms.
- Collections store groups: lists for batting orders, tuples for fixed match details, dicts for player records, sets for unique opponents.
- type() and isinstance() let you inspect what a value actually is — the first debugging tool every Python programmer needs.
1About This Guide
This guide is part of the SkillVeris Learn Through Hobbies series, built on one simple idea: when you learn a technical skill through something you already love, it sticks. If you have ever argued about a batting average or checked an economy rate during a tense over, you already think in data — you just have not written it in Python yet.
By the end of this article you will be able to explain what a variable is and create your own in Python, recognise Python's four core data types and when to use each, convert one type into another safely, store an entire squad using lists, tuples, dictionaries, and sets, and build a small program that prints a clean player stat card.
No prior programming experience is assumed. If you have completed our pillar guide, Learn Python Through Cricket: Your Ultimate Beginner's Guide, this is the natural next step.
2Why Cricket Stats Make Variables Click
Cricket is one of the most data-rich sports on earth. A single delivery can produce runs, an extra, a wicket, a boundary, or a dot ball — and every one of those outcomes is a piece of information a computer can store. That makes the sport a perfect training ground for learning how programs hold and move data.
Here is the mapping we will build on throughout the guide: a single number like runs scored maps to an integer; a decimal like a batting average maps to a float; a name like "Rohit Sharma" maps to a string; a yes/no fact like "is the batter out?" maps to a boolean; and a full squad maps to a list, with each player's full record stored as a dictionary.
💡Pro Tip
Grab a real dataset before you start. The IPL ball-by-ball dataset on Kaggle is free and gives you genuine numbers to experiment with. Practising on data you care about turns every exercise into something satisfying.
3What Is a Variable? The Scorecard Analogy
Think of a scorecard. Each column has a label at the top — Runs, Balls, Fours, Sixes — and a value underneath it. In Python, a variable works the same way: a name (the label) pointing to a value (the number underneath).
Three things are worth noticing: the = sign does not mean "equals" in the maths sense — it means assign, as in "put the value on the right into the box named on the left". You can change a variable any time; after the next ball, runs = 86 simply updates the box. And Python figures out the type for you — you never have to declare "this is a number".
Your first cricket variables
Copy this into a new file called cricket_stats.py and run it. Experiment by changing the numbers.
01# Label on the left, value on the right
02runs = 82
03balls = 53
04player = "Shubman Gill"
05
06print(player, "scored", runs, "off", balls, "balls")
07# Output: Shubman Gill scored 82 off 53 balls
4Naming Variables Like a Professional Scorer
A good scorer keeps a tidy book so anyone can read it. Good variable names do the same for your code. Python has a few firm rules and several strong conventions.
Hard rules — Python will error if you break these: names may use letters, numbers, and underscores but cannot start with a number (4runs is invalid; runs_4 is fine); no spaces — use an underscore (strike_rate, not strike rate); you cannot use reserved keywords such as if, class, or for as variable names.
Conventions — Python will run, but readers will judge: use lower case with underscores for ordinary variables (total_runs, wickets_taken); be descriptive — sr saves typing but strike_rate saves confusion three weeks later; reserve ALL_CAPS for fixed values that never change, like MAX_OVERS = 20.
⚠️Watch Out
Python is case sensitive. Runs, runs, and RUNS are three different variables. Mixing them up is one of the most common reasons a beginner's program quietly uses the wrong number.
5Python's Core Data Types — Through Cricket
Every value in Python has a type, and the type decides what you can do with it. You can add two scores together, but adding two player names makes no sense. Let us meet the four core types using a single innings.
Integers (int): Runs, Wickets, Balls
An integer is a whole number with no decimal point — perfect for anything you count. Integers support all the arithmetic you would expect: +, -, *, and // (whole-number division). Counting things — runs, balls, wickets, matches — almost always means an integer.
01runs = 82
02wickets = 3
03balls_faced = 53
04sixes = 4
05
06total_boundaries = sixes + 9 # 4 sixes + 9 fours
07print(total_boundaries) # 13
Floats (float): Averages, Strike Rate, Economy
A float is a number with a decimal point. The moment you divide, you usually get one. Strike rate, batting average, and bowling economy are all floats because they rarely land on a whole number. Use round(value, 2) to keep results readable, just as a broadcaster would quote a strike rate to two decimals.
01runs = 82
02balls = 53
03
04strike_rate = (runs / balls) * 100
05print(round(strike_rate, 2)) # 154.72
Strings (str): Player and Team Names
A string is text, wrapped in quotes. Names, team names, and venues are all strings. Useful string tools: .upper() and .lower() change case; .strip() removes stray spaces from messy data; len(player) counts the characters; f-strings build clean formatted output.
01player = "Virat Kohli"
02team = "Royal Challengers Bengaluru"
03
04headline = player + " plays for " + team
05print(headline.upper())
06# VIRAT KOHLI PLAYS FOR ROYAL CHALLENGERS BENGALURU
Booleans (bool): Is the Batter Out?
A boolean holds just two possible values: True or False. It answers yes/no questions, which is exactly how cricket decisions work. Booleans are the engine behind decisions — in the next guide on control flow, you will use them to decide whether to print "Fifty up!" or "Keep going".
01is_out = False
02is_captain = True
03scored_fifty = runs >= 50 # comparison returns a boolean
04
05print(scored_fifty) # True (because runs is 82)
6Type Conversion: Turning Overs into Balls
Cricket constantly switches between units — overs and balls, percentages and decimals. Python lets you convert between types deliberately, a process called casting. The three casts you will use most are int("4") which turns text into a whole number, float("7.5") which turns text into a decimal, and str(82) which turns a number into text so you can join it to other strings.
⚠️Watch Out
You cannot add a number to a string directly. "Economy: " + 7.5 raises a TypeError. Wrap the number in str() first, or use an f-string: f"Economy: {economy}".
Casting in action
01overs_text = "4" # this is a STRING, not a number
02overs = int(overs_text) # cast string -> integer
03balls = overs * 6
04print(balls) # 24
05
06# Going the other way for display
07economy = 7.5
08print("Economy: " + str(economy)) # Economy: 7.5
7Collections: Building a Whole Team
A single variable holds one value, but cricket deals in groups — a batting order, a squad, a season's scores. Python gives you four collection types, each with a clear cricketing role.
A list is an ordered, changeable sequence — perfect for a batting order where position matters. A tuple is like a list but cannot be changed after creation — use it for fixed facts like a match venue and date. A dictionary stores labelled key-value pairs — exactly what a player stat card is. A set stores only unique values and ignores duplicates — handy for tracking which teams a player has faced.
List — the batting order
01batting_order = ["Rohit", "Gill", "Kohli", "Iyer"]
02batting_order.append("Rahul") # a new batter walks in
03
04print(batting_order[0]) # Rohit (positions start at 0)
05print(len(batting_order)) # 5
Tuple — fixed match details
01match = ("Wankhede", "2026-04-12", "IPL")
02print(match[0]) # Wankhede
03# match[0] = "Eden" -> raises TypeError: tuples are locked
Dictionary — a player's career card
01kohli = {
02 "name": "Virat Kohli",
03 "matches": 280,
04 "runs": 13900,
05 "average": 49.6
06}
07
08print(kohli["runs"]) # 13900
09kohli["runs"] = 13985 # update after a new innings
Set — unique opponents
01opponents = {"AUS", "ENG", "AUS", "SA"}
02print(opponents) # {'AUS', 'ENG', 'SA'} — the duplicate is dropped
8Inspecting Types: type() and isinstance()
When data misbehaves, the first question is usually "what type is this, really?" Python answers with two tools. type(x) tells you exactly what something is. isinstance(x, int) asks a yes/no question and returns a boolean — useful before doing maths on data you did not create yourself.
Checking types in practice
01runs = 82
02average = 49.6
03player = "Kohli"
04
05print(type(runs)) # <class 'int'>
06print(type(average)) # <class 'float'>
07print(isinstance(player, str)) # True
9Common Beginner Mistakes (and Fixes)
Knowing the pitfalls before you hit them saves hours of frustration.
- Reading numbers as text — input from a file or form arrives as a string. "82" + "5" gives "825", not 87. Cast with int() first.
- Integer division surprises — 7 // 2 is 3, not 3.5. Use a single slash / when you want a float result.
- Overwriting built-ins — naming a variable list or str breaks those tools for the rest of your program. Use player_list instead.
- "50" == 50 is False — one is text and the other a number. Convert before comparing types.
- Forgetting floats lose precision — tiny rounding errors are normal; use round() for display rather than for critical comparisons.
10Mini Project: Build a Player Stat Card
Time to put every concept together. This short program stores one innings using the right types and prints a tidy card — integers, a float, a string, a boolean, and a dictionary all working as a team.
Notice how each value uses the type that suits it: counts as integers, the rate as a float, the name as a string, the dismissal status as a boolean, and the whole record as a dictionary. That is good data modelling — the same instinct professional developers use on far larger systems.
Player Stat Card — full code
01# --- Player Stat Card ---
02player = {
03 "name": "Shubman Gill", # str
04 "runs": 82, # int
05 "balls": 53, # int
06 "is_not_out": True # bool
07}
08
09strike_rate = round((player["runs"] / player["balls"]) * 100, 2)
10status = "not out" if player["is_not_out"] else "out"
11
12print("================================")
13print(f" {player['name']} ({status})")
14print("================================")
15print(f" Runs : {player['runs']}")
16print(f" Balls : {player['balls']}")
17print(f" Strike rate : {strike_rate}")
18# ================================
19# Shubman Gill (not out)
20# ================================
21# Runs : 82
22# Balls : 53
23# Strike rate : 154.72
11Practice Drills and What to Learn Next
Reading code builds familiarity; writing it builds skill. Try these drills on your own before moving on.
- Create variables for a bowler: overs, runs_conceded, and wickets. Calculate and print the economy rate as a float rounded to two decimal places.
- Store three team names in a list and print the second one.
- Build a dictionary for your favourite player with at least four keys, then update one value after an imaginary innings.
- Take the string "6", cast it to an integer, multiply by 6 (one over in balls), and print the result.
- Use isinstance() to confirm that a computed strike rate is a float, not an integer.
💡Keep the Momentum
Stuck on a drill? Open the SkillVeris Code Lab and paste your attempt — the AI Mentor will explain exactly where a type went wrong, rather than just handing you the answer. Your next guide: Learn Loops in Python by Building a Cricket Scoreboard.
Get The Print Version
Download a PDF of this article for offline reading.
About the Publisher
SkillVeris Team
Content Team
We believe the best way to learn tech is through what you already love — sports, music, photography, and more.
View all postsRelated Posts
Never miss an update
Get the latest tutorials and guides delivered to your inbox.
No spam. Unsubscribe anytime.