Learn Python • #2 Variables and Data Types • Python's Building Blocks
Key Takeaways
This video teaches how to use variables and data types in Python
Full Transcript
welcome to part two of this 12-part Python tutorial series for beginners in this chapter we'll learn about variables and primitive data types in Python variables in Python are how we can store data and then reference them later on here are some examples of variables in this example I have a variable called X and the value is the number nine I also have a variable called Y and the value is the word hello to see how this works let's open up our editor and actually write it up ourselves I'm inside my vs code editor and I'm going to create a new file and I'm just going to call it main.py and here I'm going to type x equals to 9 and then y equals to hello and if I click up here to run that then nothing happens nothing shows up on our terminal because even though we declared these variables we actually haven't done anything with them yet we haven't told python to print it out to the terminal so to do that let's just add a print statement and print out X and then let's add another print statement and also print out why so we'll hit save and then run that again and you can see that the values of 9 and hello are now printed to the terminal now what if I overwrite to the value of x before I print it out I'm going to say x equals a b c d here and then if I run that again I don't have the number nine being printed out anymore because by the time I reach this line here in my interpreter the value of x has already been overwritten by a b c d so with variables in Python you can create them like this and you can also override their value and whatever was the last value that you've assigned to the variable will be what's stored there when you try to access it for example when you try to print it out and when you overwrite the value of a variable it doesn't even have to be the same type as the previous value so here I created a variable with a value of 9 as an integer and here I've overwritten it with a string it's generally not good practice to reuse variables for different types of data but you can do that and python won't complain about it if you it's just not a good idea to do it if you can avoid it now let's see what happens if we try to print a variable that doesn't exist yet so here I'm printing out the word hello but that's because I've set the string value of hello equal to this variable why but if I delete all that and I just try to print the word hello on its own what do you think will happen if I run that it doesn't work there's an error here and it says name hello is not defined that's because if you don't put a word inside quotation marks python doesn't think of it as a string or a word it thinks of it as a variable and it's expecting it to be declared earlier in your application so if I literally wanted to print out the word hello and not the variable hello I can put this in quotes and then if I run that it'll be fine and it will print out but often I don't like to do this because I have values that the meaning to me as a developer is something but the value it stores can be something else so an example of this is something like a user and to me I don't care about who the user is specifically it can be anybody all I care is that that's the user that I'm dealing with but we do need to define the user so here I can do user equals to Jack and if I print that out you'll print out the name Jack even though for me as a developer reading this all I care about is that this is whoever is the current user and I can change this to somebody else as well so I run that again and now it prints Alice and generally if you try to use a variable that hasn't been defined in Python you will see this name error coming up so if you see an error that looks like this it's probably because you try to use a variable that you haven't defined at that point in the program and also if you do come up against errors like this but also maybe other errors in the future you might want to search for it on the internet to get a clue on how to fix it but just something to keep in mind is that the errors will contain very specific information about your file and your program so if you copy paste the entire error message into stack Overflow or into Google some of these words and names that are specific to your program might make it difficult for the real answer to show up so if you do have a situation like this I recommend you looking at what's specific to your program so for example here the name user specific to the program I won't copy that I'll just copy name error is not defined and then search for that if you're using vs code the editor will help you identify variables that you haven't defined it as well because here if I'm using the variable user without first giving it a value it's given me this little underline saying that there's something wrong with me trying to use that that this user variable is not defined and I can fix it by simply just defining it up here so to recap variables are references to data so in this case it could be the number nine or the word hello and in Python we use variables whenever we want to refer to the data that they're storing when we're writing our program here we've used X and Y as our variable names and I've just chosen that arbitrarily for no special reason in reality we can actually use anything for these variable names but there are certain things that make good names and bad names examples of good variable names include x y and z because they're commonly used in math as well as descriptive but not overly long names like temperature Fahrenheit in Python it's also conventional to write the name in all lowercase letters with each separate word in the name separated by an underscore you can use a space in the name so you use an underscore to separate them instead here are some examples of data that can be stored in variables this includes things like numbers and decimals text and true false values there are some reserved words in python as you see here in this list such as min max class continue and so on if these words have special meaning and cannot be used as variable names additionally variable names cannot start with a number although you can use the numbers after the first character so if you want to write a variable like VAR underscore 1 that will be valid so now here are some examples of variable names that are invalid or they're valid but they're not good variable names the first one is min which is one of the reserved words so as you can see our editor highlights it in a different color and we can't use that in the second example we try to start the name with a number and we can do that as well now in the third example actually from the third example onwards these names are all valid but they're not the best names R1 works but it's not really descriptive it doesn't tell me what the variable is or what it does student name is good as well but the casing is wrong remember I said that in Python it's conventional to use snake case which has all lowercase characters punctuated by underscores at first glance the next variable name on the list looks like it meets all the rules except that it's a little bit too abbreviated I don't know what the proc word stands for in this case and I don't know what CTR stands for and it's common that if you work with a program or you work in your project you might come up with very short abbreviations that you know but that's bad practice to over abbreviate things because in general you want your work to be understood by other people and they might not have the same knowledge as you do when it comes to the abbreviations or only use abbreviations when it's really really obvious what they are for finally the last one on the list distance that's actually a pretty good variable name except that we can improve it because something like a distance would actually have a unit with it as well if you tell me the distance of something as a number then I don't know whether it's meters kilometers or miles so in this case it's useful to actually add the unit name to the variable name as well for example it would be better to say distance underscore km in this case instead of just a distance on its own don't worry if you struggle to come up with good variable names from the start there's definitely a skill that takes time to learn and it's not easy in fact here's a famous quote among software Engineers there's only two hard things in computer science action validation and naming things now let's take a quick look at how we can use variables to represent real world problems if we wanted to build a game we can use variables to represent things like a character's Health power and speed if we wanted to build a food ordering app we might use it to represent the name of the item the price of the item and whether or not it's a vegetarian item and if we wanted to make a finance or a stock trading app then we could use variables to represent the different types of stock symbols the quantity we wanted to buy and what type of order we want to place whether it's a buy order or a sell order so that was just some quick examples of how to use variables with real world problems now let's take a closer look at the values that the variables themselves can contain they're shortened to int float Str for string and Bool for Boolean integers are whole numbers so anything like one two three four loads are numbers with decimal places even if you have a whole number like 1.0 but it has a decimal place that's still afloat strings are anything surrounded by quotes so that could be a character that could be a single Emoji it could be a whole paragraph or even a huge chunk of text and finally booleans are either true or false so these are the four primitive data types in Python and they are the building blocks to more complex data structures that we'll see later here are some examples using these different data types to create new variables you can store these values inside the variable and then when you want to use them later on you can refer to them by using the name or the label of the variable the reason for having these four distinct types of data in particular is to ensure that the data is stored in the most efficient and accurate way possible each data type requires a different amount of memory in storage and having the wrong data type for something could potentially lead to inaccuracies and another important factor is that the data type itself also gives us a clue about what we can do with the data so here if I have two integers then I know that I can add them together and if I add the two integers here two plus two I'm going to get four and that is also going to be an integer I can also add an integer with a float in this scenario the result would always be a float even if the operands were actually whole numbers so when you add a float to any number the result is always going to be a float what if I try to add two strings together I can actually do it but it would behave quite differently strings are characters they're treated as text and they have no numerical value so when I try to add them it treats it as if I've just cut out letters out of a newspaper and pasted them together so just keep that in mind that even if the strings you have are strings of numbers when you add them together or do anything with them in python python will treat them as strings and so you'll get results like this so if I add the string 2 with the string 2 instead of 4 I'm going to get the string 22. now that you know a little bit about variables and data types you're probably wondering what you can do with them and how you can use them well one of the most useful and basic things you can do with them is to make them appear on your screen it's super helpful when you're debugging or just working on your app in Python we can do this using the built-in print function which you've already seen before but there's several ways to use this print function in Python so let's take a quick look at them now first we can just print out a value directly so for instance here I don't even have a variable I'm just printing out the string hello world directly with this line but of course the print function can also be used to print the value of a variable so here if I have a variable called X and I set it to the value of 12 if I print X then I'm going to get 12 in my terminal you could also print out multiple values at once so for example if you want to debug two values at the same time you can use this print function and then just separate the values with a comma and you can do this with as many values as you want although it's probably a good idea to keep it quite small maybe between two to three values at a time if you want to work with larger than a handful of values then stay tuned for chapter 5 where we're going to be looking at the list which is how we can work with a large amount of data and when we print out multiple values with one statement they don't always have to be the same data type and they don't even all have to be variables you can combine text and variables in the print statements so I like doing this if I want to print a variable for example like X but I also want to label it in the print statement so here I can put a string like hello and then when I print it out I'll get hello 12. you know I can change the string to whatever I want to be descriptive when I'm printing this out but that's just a handy trick to have and if you're using python 3.6 or above then my favorite way to print out something is to use a format string which is also called an F string this is a popular approach because it allows us to easily combine text and variables so here you start by just writing a string with double quotes but you put the letter F at the front and it turns into a format string and then you can open the curly brackets as you see there at any point you want in the string and in there you can put any variable or any value you want and it will replace that in the string that it prints out now the F string isn't even a feature of the print function it's a feature of the string so this is useful even if you just want to create a string where you want to insert specific pieces of information throughout the string so as you're going through this tutorial I actually recommend you opening up your terminal and then trying out all these examples for yourself just so you can become more familiar with them but also see how they actually work so let's go ahead and try the last example let's create a variable called X and I'll give it the value of 12. now I want to print out x with a format string but instead of printing the format string directly I want to create another variable called the message which is going to be the string in case I want to use it for something else normally when you print out information or you log it you might also want to save it to a file or save it to a database for safe keeping so it's useful to actually have our messages stored inside the variable so let's do that let's make it an F string so it's basically just a string with the letter F at the front and then I'm going to write the value of x is and then open your curly brackets and in there you can put anything you want and here I'm just putting X now I have X on the message let's actually print just the message so now if I run that I get this output the value of x is 12. I think it might be useful to end this chapter with a coding and concise so that you can practice what you've learned imagine that you're building an e-commerce application and you need to describe some items like their name their quantity what the price is and whether you have them in stock so for this exercise I want you to think about how you would model this data what variable names would you use for each of them and then what would be the type of data pause the video now for a moment and then write a few lines of python to describe these things and feel free to plug it in with some example data once you've had a moment to think about it then feel free to resume the video okay so I hope you had a chance to think about it and this is probably what I would answer for that question so for the item name it's going to be a string because the name can be anything in this case I've chosen appled and the variable name is item underscore name so that it sort of matches Python's snake case convention quantity can be an integer so here I have quantity equals four because you're probably going to have whole numbers of the quantity of your item you're not going to have half an item for example so an integer is probably the best choice for this for the price I've named it price underscore USD because as I mentioned when you have something that can have ambiguous units it's better to have the unit specified in the variable name so that when you use it or other people use this variable there's no confusion about what it's um what it's storing and in this case I've chosen price to be afloat because if we're dealing with USD we don't always have whole numbers we usually also have uh decimal places with the numbers especially when dealing with items like apple which is quite cheap and finally whether or not it is available in stock we've chosen a Boolean it's best to store that as Boolean because that's the most efficient data type to express that type of information so that was a quick introduction to variables and data types in Python if you get stuck or have questions then leave me a comment in the video or check the links in the description for where you can get help see you in the next video where we're going to take a look at operators in Python which lets us manipulate compare or do other useful things with our data
Original Description
Variables and data-types are the foundational building blocks of your Python code.
They will let you store any type of data, and allow you to refer to it later on when you need to do something with it. Learn all about them in this quick tutorial.
This video is part of a beginner tutorial series for anyone who wants to learn Python from scratch, and get to a point where you can start coding your own projects.
🔗 Project Code (GitHub): https://github.com/pixegami/python-for-beginners
🔗 Full Playlist: https://www.youtube.com/playlist?list=PLZJBfja3V3Rsbiz84Z63IXnTQZH_Rnfuo
🔗 Next Chapter: Coming Tomorrow!
👉 Follow me on Twitter: @pixegami
📚 Chapters
00:00 - Using Variables in Python
05:20 - Good vs Bad Variable Names
08:48 - Data Types in Python
11:08 - Using print() in Python
14:38 - Coding Exercise: Variables
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from pixegami · pixegami · 34 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
▶
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
How to Build an AWS Lambda Function in Python in Just 7 Minutes!
pixegami
AWS CDK Tutorial: Deploy a Python Lambda Function using AWS
pixegami
I used GPT-3 to Write Poetry • Is AI the Future of Creative Writing?
pixegami
Create NFT Generative Art with Python! (Full Tutorial)
pixegami
Build an AI-driven SaaS Application: FULLSTACK Tutorial with Python, React, and AWS
pixegami
NextJS and TailwindCSS: How to Build a Portfolio Site from Scratch
pixegami
Python Web Scraping Tutorial • Step by Step Beginner's Guide
pixegami
Build Wordle in Python • Word Game Python Project for Beginners
pixegami
How to create 1000+ unique NFT-style images (like Cryptopunk) | Python Tutorial
pixegami
Top 10 Python Modules 2022
pixegami
How to Send SMS Text Messages with Python & Twilio - Quick and Simple!
pixegami
How To Write Unit Tests in Python • Pytest Tutorial
pixegami
How to Style Your React Landing Page with Tailwind CSS
pixegami
FastAPI Python Tutorial - Learn How to Build a REST API
pixegami
How to Deploy FastAPI on AWS EC2: Quick and Easy Steps!
pixegami
PyScript • How to run Python in a browser
pixegami
My Custom Ubuntu Linux Terminal with Themes and Plug-ins 💻
pixegami
Deploy FastAPI on AWS Lambda ⚡ Serverless hosting!
pixegami
NextJS Firebase Auth Tutorial • How to Authenticate Users for Your App
pixegami
AWS Lambda Python functions with a database (DynamoDB)
pixegami
How To Build a CRUD (TO-DO) App on AWS using FastAPI and Python
pixegami
How to Make a Discord Bot with Python
pixegami
How To Use GitHub Copilot (with Python Examples)
pixegami
PyTest • REST API Integration Testing with Python
pixegami
Python Beginner Project: Build a Caesar Cipher Encryption App
pixegami
Decorators in Python: How to Write Your Own Custom Decorators
pixegami
NextJS 13 Tutorial: Create a Static Blog from Markdown Files
pixegami
Exploring ChatGPT for Coding and Business ✨ 8 Real Examples!
pixegami
How I Would Learn Python (if I had to start over) • A Roadmap for 2023
pixegami
Build an AI Pokemon Generator with Python and Midjourney
pixegami
Why You Should Learn Python in 2023 (as your first programming language)
pixegami
ChatGPI API in Python ✨ How to Build a Custom AI Chat App
pixegami
Learn Python • #1 Installation and Setup • Get Started With Python!
pixegami
Learn Python • #2 Variables and Data Types • Python's Building Blocks
pixegami
Learn Python • #3 Operators • Add, Subtract and More...
pixegami
Learn Python • #4 Conditions • If / Else Statements
pixegami
Learn Python • #5 Lists • Storing Collections of Data
pixegami
Learn Python • #6 Loops • How to Repeat Code Execution
pixegami
Learn Python • #7 Dictionaries • The Most Useful Data Structure?
pixegami
Learn Python • #8 Tuples and Sets • More Ways To Store Data!
pixegami
Learn Python • #9 Functions • Python's Most Important Concept?
pixegami
Learn Python • #10 User Input • 4 Ways To Get Input From Your User
pixegami
Learn Python • #11 Classes • Create and Use Classes in Python
pixegami
Learn Python • #12 Final Project • Build an Expense Tracking App!
pixegami
Stripe & Firebase Tutorial • Add Payments To Your NextJS App
pixegami
How To Use GitHub Actions • Automate Your AWS Deployments
pixegami
How to Run a Python Docker Image on AWS Lambda
pixegami
My MacOS Terminal Setup for HIGH Productivity
pixegami
Host a Python Discord Bot on AWS Lambda (Free and Easy)
pixegami
Python FastAPI Tutorial: Build a REST API in 15 Minutes
pixegami
Pydantic Tutorial • Solving Python's Biggest Problem
pixegami
How to Get Started with AWS • Crash Course
pixegami
Python Requests Tutorial: HTTP Requests and Web Scraping
pixegami
Amazon Bedrock Tutorial: Generative AI on AWS
pixegami
How to Publish a Python Package to PyPI (pip)
pixegami
Langchain: The BEST Library For Building AI Apps In Python?
pixegami
RAG + Langchain Python Project: Easy AI/Chat For Your Docs
pixegami
Python Dataclasses: Here's 7 Ways It Will Improve Your Code
pixegami
Build a Custom AI RPG Game with OpenAI GPTs
pixegami
Create a Custom AI Assistant + API in 10 Mins
pixegami
Related Reads
Chapters (5)
Using Variables in Python
5:20
Good vs Bad Variable Names
8:48
Data Types in Python
11:08
Using print() in Python
14:38
Coding Exercise: Variables
🎓
Tutor Explanation
DeepCamp AI