Variables for Absolute Beginners: Free Python Tutorial

What are Python variables?

Let’s learn all about them! In this tutorial, you’ll learn how to use Python variables to code.

Want to code more? Enroll in our Python course – on sale today.

Variables are a way of storing information or data that you may want to keep for later, or for storing information you may not know yet.

For instance: suppose you’re writing code that will ask for user input. At the beginning of the code, you won’t know the user input, so you will store the user input in a variable.

Variables are convenient because they let you save information and use it later. Let’s look at an example of a variable below. Note that we’re using the development environment Spyder (Python 3.5) to test our code.

Suppose you’re writing code and want to store the number 1. You can declare (create) a variable to do so.

To declare a variable, write the variable name in the Editor, followed by an assignment operator, which is represented by an equals sign.

one = 

The preceding code declares a variable with the name one. one will be assigned the value on the other side of the operator. Let’s make the value 1 with the following code.

one = 1

You can use the same format to make variables with the values 2 and 3.

one = 1
two = 2
three = 3

With the preceding code, we created the variable two with the value 2. We also created the variable three with the value 3.

Thus we have 3 different variables that we can call. We can do different things with them, and they do not affect one another.

Printing Variables

To prove that we’ve created the variables successfully, we can use the print function. This function lets you print output to the screen so that you can see it. You can learn more about functions in our Python course. Right now, we’ll use one function so that we can see our variables in action.

Type the word print, which is the keyword for the print function. The development environment will color the word in purple.

one = 1
two = 2
three = 3

print

In parentheses after the variable name, you put the parameters of the function. In this case, the parameter will be the name of the variable you want to print. Let’s print one first using the following code.

one = 1
two = 2
three = 3

print(one)

On subsequent lines, use the same format to print two and three.

one = 1
two = 2
three = 3

print(one)
print(two)
print(three)

If you run the code by pressing the Run button, the console on the right side will print the values of the variables that we assigned earlier.

You can reuse variables. For example, the following screenshot shows that you can print the variables backwards.

What happens if you overwrite variables?

You can overwrite a variable (change its value) by assigning it a new value. For instance, the following code changes the value of two to 4.

one = 1
two = 2
three = 3

print(one)
print(two)
print(three)
two = 4
print(two)
print(one)

You will see in the console that before you overwrite the variable, the print function will print the variable’s initially assigned value. After the overwriting line, print will print the variable’s new value because you’ve overwritten the data.

You’ve changed the value of the data inside the variable. When you call the print function, your computer looks at the last known value and prints it to you. When you modify the value, the value stored inside the computer gets changed.

Types of Variables

We’ve created variables (one, two, three) of a certain type: integers. They are integers because their values (1, 2, 3, 4) are integers (whole numbers). You can create other types of integers.

For instance, the following code creates a variable that is a decimal. Note that the name of the variable can be whatever you wish, but it is logical to name it something that relates to its value.

one = 

The preceding code declares a variable with the name one. one will be assigned the value on the other side of the operator. Let’s make the value 1 with the following code.

Decimal = 1.1

Another type of variable you can make is a string. Use the following format to create a new variable named StringVar (to stand for string variable.)

StringVar

Notice that we capitalized the first letter of each word in this variable’s name. Although not required in Python, it is a naming convention and makes code easier to read.

A string is a series of characters. To declare a variable as a string, you can assign it a value in quotation marks. The following code gives StringVar the value "Hello".

StringVar = "Hello"

You can print this variable as well, using the same format for the print function.

StringVar = "Hello"
print(StringVar)

In Python, you don’t have to tell the computer what type you want a variable to be. Python automatically assigns a variable a type depending on the variable’s value. This differs from some other programming languages. You can simply assign a value, and the computer will store it in memory to be used later.

There are some rules, however. For instance, if you want to add a value to a variable, you can do so with the + operator. However, each variable can only be of one type. Let’s look at an example.

Suppose you want to add “1” to the end of StringVar. If you simply write + 1 to where you declared StringVar, you will get an error message. The console will print the TypeError “Can’t convert ‘int’ object to str implicitly.”

This error occurs because "Hello" is a string, whereas 1 is an integer. If you put quotation marks around 1, although 1 is still a number, the computer will interpret it as a string. You will no longer get an error message.

StringVar = "Hello" + "1"

All the variables we created are called global variables because they are not contained in any function. The variables are contained in the core of the code and aren’t in a subsection. As such, you can access them from anywhere.

An example of a local variable is a variable inside a function. For instance, the following code outlines how to set up a function. We provide more information on functions in our Python course.

def FunctionName(Input):
Action
return Output

You can declare a variable inside the function like so:

def FunctionName():
newVar = "World"
return

As such, newVar is a local variable. It is local to a function. You cannot access newVar from outside the function. You can call the print function on newVar in the function. The console will print the value of the variable: World.

However, if you try to print newVar outside FunctionName, the code will crash. Because newVar is locally defined, it doesn’t exist outside the function. Your computer will give you the NameError “name ‘newVar’ is not defined”.

def FunctionName():
newVar = "World"
return

FunctionName()
print(newVar)

On the flip side, you can use global variables inside functions. For instance, you can call the one variable by simply typing its name in FunctionName. However, to let other developers know or to remind yourself that one is global, you can write the keyword global before the variable name.

def FunctionName():
global one
newVar = "World"
return

Comment out the line print(newVar) that is outside FunctionName so that we don’t get any errors. To comment out a line, add a hashtag to the beginning. The console will skip over any commented lines.

def FunctionName():
global one
newVar = "World"
return

FunctionName()
#print(newVar)

Call print on one inside FunctionName. The console will print 1, the value of one that we defined earlier.

def FunctionName():
global one
print one
newVar = "World"
return

What else can you do with variables? There is another way to define variables that is a shorthand.

An alternate way to declare our variables one, two and three is with the following format:

one, two, three = 1, 2, 3

This code assigns the value 1 to one, 2 to twoand 3 to three.

What else can you do with variables?

You can create a new variable that is the sum of 2 values. For instance, the following code declares a variable five and assigns it the value 3+2. If you print five, the console will print the sum: 5.

five = 3+2

What can you not do?

You can’t use variables that are not yet defined. For instance, the following line would return an error because we have yet to declare a variable six.

five + six = 5

You also cannot declare a variable value-first. For instance, the following code would give the SyntaxError “can’t assign to literal”.

5 = five

This occurs because code to the left of the assignment operator (equals sign) is what you’re giving the value to, and code to the right of the sign is what the value is.

What are counting variables?

You will use counting variables a lot when programming. You can use counting variables to keep track of the number of times a certain event occurs. Let’s look at an example. Create a variable count, and give it the initial value 0.

count = 0

Call print on the count variable. Comment out all the other print lines so that you can clearly see what this example prints in the console. The console will print 0.

count = 0
print(count)

Let’s make the value of count 1. There are several ways we can do this. One way we’ve already seen: to overwrite the value with the following code.

count = 0
print(count)
count = 1
print(count)

Another way is to add a value to the variable with the following code.

count = 0
print(count)
count = count + 1
print(count)

The preceding code assigns the value of count to be count’s current value plus 1. With a print function, the console would print 1.

You can increment count‘s value in this way because it will always add onto the latest value. For instance, assign count the value count + 1 again, and print it. The console will print 0 1 2.

count = 0
print(count)
count = count + 1
print(count)
count = count + 1
print(count)

A shorthand notation to add a value to the current value of count is the following. This code will add to and redefine count.

count += 1

Similarly, you can multiply the value of count and reassign its value.

count = count * 3
print(count)

There is shorthand notation for this, too:

count *= 3
print(count)

The console will print 3 at this line.

You can divide the value of count and reassign its value.

count = count / 3
print(count)

There is shorthand notation for this, too:

count /= 3
print(count)

The shorthand is helpful because as you write more code, you will find that the more ways you can write less, the more efficient you will be as a coder.

Want to code more? Enroll in our Python course – on sale today.

In this course, you will learn how to code in the Python 3.5 programming language. Whether you have or have not coded before, you can learn how to use Python. Python is a popular programming language that is useful to know because of its versatility. Python is easy to understand and can be used for many different environments. Cross-platform apps and 3D environments are often made in Python.

We will cover basic programming concepts for people who have never programmed before. This course will cover key topics in Python and coding in general, including variables, loops, and classes. Moreover, you will learn how to handle input, output, and errors.

To learn how to use Python, you will create a functioning Blackjack game! In this game, you will receive cards, submit bets, and keep track of your score. By the end of this course, you will be able to use the coding knowledge you gained to make your own apps and environments in Python.

What students have said about our courses:

“He explains everything.. great course, great teacher.”

“The instructor tells us why we do things and breaks down everything so you will understand better.”

“Pace is excellent, iterates points without being redundant. Builds on previous knowledge in a very organic way.”

“Great course. Clear voice, good screen material. I liked it.”

“I absolutely love this course. I’m only part way through so far but felt compelled to leave a review. This is such a comprehensive course that was well worth the money I spent and a lot more!. Well done. Will definitely be looking at more Mammoth Interactive courses when I finish this.”

This course is project-based, so you will not be learning a bunch of useless coding practices. At the end of this course, you will have real-world apps to use in your portfolio. We feel that project-based training content is the best way to get from A to B. Taking this course means you learn practical, employable skills immediately.

Learning how to code is a great way to jump in a new career or enhance your current career. Coding is the new math and learning how to code will propel you forward for any situation. Learn it today and get a head start for tomorrow. People who can master technology will rule the future.

Get the course here!

Build 177 Games: The Complete 2D, 3D and VR Bundle

Guess what? You can build 177 games in this course bundle.

We hand-picked our top-selling game development and design courses and put them into one convenient bundle you can enroll in right now:

  • Learn how to make 20 games in GameMaker (24 hours)
  • Learn to make 2D and 3D games in Unity® (45 hours)
  • Learn how to make 6 games in the Unreal Engine (20.5 hours)
  • The Complete Game Developer Course – Build 80 Games in Construct 2 (36.5 hours)
  • Build 30 Mini 3D Virtual Reality Games in Unity® from Scratch (CC) (77 hours)
  • Build and model a 3D Super MARLO runner clone in Unity® (17 hours)

Get it now

See what people are saying about the courses in this bundle:

“Really love how this is beginning. I’m an old-school coder trying to get back in and work on some personal game projects and this doesn’t treat me as dumb, but also doesn’t require a CS degree to understand what’s going on. Really appreciating this.”

“Clear, fast and clean!”

“The instructor is very thorough and makes no assumptions about previous knowledge. The pace is fast but not overly so. I prefer project-based learning so this is right up my alley. I’m looking forward to continuing through to the end.”

“I like the pace of the instruction as well as the granularity the instructor is using in the steps he is demonstrating as well as in his description of the various components and functions. It’s easy to follow.”

“This is an awesome course! If you have only a basic understanding of C++, this will walk you through how to get a few games up and running. Completely AWESOME!”

“Great sharing and explanation of everything”

“The instructor is very good at teaching. He teaches at a great pace and covers anything a beginner would need to understand (every little detail). I am already learning a lot and I just started yesterday.”

“Great intro, assumes that the student knows nothing, which is great for an introductory lesson!

“Really enjoying this course so far. Good pace and easy to follow.”

“I like using this course to go back to the basics. It really helps to get you going. I make games all the time. When i need a little help i come back here and watch some videos.”

“Perfect course for people with some experience in the field, specially with C++ The instructor goes to the point without entering in details which is perfect to leave the details to you to check the documentation. For me this is a 5/5 course 🙂

“My learning is deep and fun”

“77 hours of content. Project code and assets included to be able to easily check where the typo/error is. I love this course”

“Great pacing, good explanations and understandable examples. It is the kind of approach that I really appreciate when I am trying to learn new skills. I also admit that I really love the opening graphics and music! Cool!”

“This is a fantastic course that walks you through step by step. An excellent course for beginners and those who are trying to improve their coding skills.”

“An easily understood course, with detailed instruction and good explanation of the concepts involved in making this clone game. A very well done tutorial, especially for someone like me is just now learning how to write code.”

“Very in depth and well explained. Great course for beginners looking for a place to get a strong start in Unity.”

Grab this bundle while this super offer exists! See you there.

Get it now

Give the Gift of Hello Coding

If you want to stand out as a gift giver, give 164 hours of learning to someone you know. Your gift will be of Mammoth Interactive’s largest course ever released, plump with hands-on projects from 6 instructors.

Buy Hello Coding to send to someone else for only $49 – include a personal message for FREE!

This online course makes the perfect gift for your friends (or enemies – why not?). You will show your support for their professional development or personal interests. What’s better than the gift of knowledge?

Happy holidays! Click here to start giving.

When you purchase this course, we will create a single-use coupon for free access to our Hello Coding course. You will have the option of sending this coupon to your recipient or letting us send a pre-formatted email to them.

Level 1 of Hello Coding is an introduction to coding and the programming industry. Mammoth Interactive founder John teaches you to market yourself and network in the field, both of which are necessary to successfully work as a coder.

Level 2 introduces you to web development. Our web developer Chris breaks down the fundamentals of coding in the 3 primary coding languages HTMLCSS JavaScript. We show you how to directly apply what you learned to build a landing page and modular website.

Level 3 is mobile app development. App developer Nimish demonstrates how to code in Java, currently the most widely used language to make Android apps. As well, you learn the programming language basics of Swift 4, Apple’s official coding language for iOS app development.

This level is unique because we show you how to make a project both for iOS and Android, which is important these days where the majority of smartphone users have one of these two. You build a finance calculator for the web and a weather app.

Level 4: Game developer Glauco gives you a thorough guide to Unity®, the popular & FREE program used to make games for a range of devices.

Get ready for game design by learning to navigate BlenderPhotoshop and Illustrator. Our artist Kevin teams up with Glauco to take you through coding and designing 3 complete games from scratch: a Flappy Bird clone, Angry Birds and Air Hockey.

Level 5: Learn the diverse web language Python & TensorFlow, the software library for Machine Intelligence, from data scientist Max. Apply data analysis tools to make a stock market prediction app, image recognition model & credit card fraud detection model.

Give the Gift of Hello Coding.

Get rewards by supporting our Kickstarter.

2018 is the year you finally crush your New Year’s resolution and learn to code.

Start off 2018 on the right foot by learning how to code. If you pledge for this Kickstarter you will not only learn to code, you will learn how to build machine learning models from scratch. This bundle of courses is a must have if you want to keep your skills and knowledge relevant in today’s fast moving world.

This year is your year. Crush your New Year’s resolution by pledging today. There are limited seats so don’t miss out!

PLEDGE NOW

Self-driving cars. Artificial intelligence. Genomics. And you.

What do these have in common? They use machine learning, the technology shaping our future. Machine learning isn’t a magical concept exclusive to top-level researchers – you can learn it, too!

Machine learning is changing the world around us. It’s bringing us self-driving cars, facial recognition and artificial intelligence. ML began on computers, but the next big wave is machine learning for mobile. Have you ever thought: why can’t my mobile device do more?

We from Mammoth Interactive are here to tell you that your Android and iOS apps can become smarter, stronger and more convenient thanks to machine learning. Better yet, we’ll show you how to build your very own intelligent software that grows with you.

Pledge today to get a massive online course on machine learning (ML), a subfield of Artificial Intelligence (AI) on how computers learn from experience to improve how they react in the future.

PLEDGE NOW

Anyone – yes, including you – can learn to create data analysis that allows computers to learn from data and get smarter without extra programming.

Who is this for?

If you want to build sophisticated and intelligent mobile apps or simply want to know more about how machine learning works in a mobile environment, this course is for you.

No prior knowledge is required. We will teach you all you need to know about the languages, software and technologies we use. If you have lots of experience building machine learning apps, you may find this course a little slow because it’s designed for beginners.

PLEDGE NOW

Blender’s Mirror Modifier + Cutting an Object

Let’s learn how to use a basic modifier that we is often used when making 3D low poly art in Blender.

To follow along hands-on, create a new project in Blender containing a Cube. Expand the Properties window (covered here) by clicking and dragging its left edge. Select the wrench icon to open the Object Modifiers context.   

The Mirror Modifier can help you save time when creating art. You can make half of an art piece and use the Mirror modifier to generate the second half.

Dividing an Object in Half in Blender

Let’s split Cube in half. Enter Edit Mode (covered here). Hit Control+R. Double-click on the edge loop to divide Cube.

Enter Face Mode. Delete the right side of faces. Half a cube will remain in the Viewport.

Mammoth Interactive Image

Blender’s Mirror Modifier

Enter Object Mode. In the Properties window, press Add Modifier. Select “Mirror” from the “Generate” list.

Unselect X from the “Axis” list that appears in the Properties window. Select Y. This will mirror the cube in the scene in the Y axis. Any modifications you make to the original side of the cube will mirror on the other side.

Enter Edit Mode. Extrude the outer face of Cube. Scale the face down. Extrude it outwards. As evident, the other side of Cube will also scale.

Mammoth Interactive Image

The edge loop between the cube and its mirror is a separation. To fix this, select “Clipping” from the “Options” list in Properties. To apply the mirror, enter Object Mode. Press Apply in Properties. The cube and its mirror will be one combined object.

Enter Edit Mode. If you edit one side of Cube, the other side will not change!

If you want to learn more about Blender and making digital art, join our course Make Low Poly 3D Environment Models in Blender and Unity®.

Course Image