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!

Implementing a Button | Unity Tutorial

In virtual reality (VR) games, one of the few interactions a player can make is press a button by looking at it. In this tutorial, we will implement the button we made in our previous Unity tutorial.

If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

There are two ways to interact with the button. Both ways involve looking (the looking logic). We need to understand how to identify the button. To do this, we will perform raycasting.

To draw an image, Main Camera throws rays in multiple directions to find pixels to draw. We will use the ray that shoots forward in the direction the camera is facing. If the ray flying from the camera touches an object, we will identify the object.

Rename Main Camera “Player” because the player will look through the lens of the camera. We can treat the camera as the eyes of the player. Create a C# script in Assets. Name the script “Player”. Drag and drop the Player script to “Player” in the Hierarchy.

Double-click on the Player script to open it. Type the following code in the Update method in Player.cs. This code declares the local variable hit of type RaycastHit.

public class Player : MonoBehaviour {
// Use this for initialization
void Start () {

}

// Update is called once per frame
void Update () {
Raycast hit;
}
}

hit is a local variable because we declared it in one function. You can only call a local variable within its function. If you know you are only going to use a variable in one function, declare it as a local variable.

If you declare a variable in a class outside of a function, you can use the variable throughout the functions in the class. These variables are global.

If you hover over “RaycastHit”, you can read that if your raycast hits an object, the object will be stored in hit, along with other details.

Create the following if block, which calls the Raycast method from the Physics class.

// Update is called once per frame
void Update () {
Raycast hit;

if (Physics.Raycast()) {

}
}

We need to pass three parameters to perform the raycast:

1. We need to pass the origin of the raycast. We want the ray to come from the exact position of the camera. transform.position is the position of Player.

// Update is called once per frame
void Update () {
Raycast hit;

if (Physics.Raycast(transform.position)) {

}
}

2. We need to pass the direction of the ray. transform.forward refers to the direction of the blue arrow. transform.forward always points forward even when the camera rotates.

// Update is called once per frame
void Update () {
Raycast hit;

if (Physics.Raycast(transform.position, transform.forward)) {

}
}

3. We need to pass where we will save the hit information if there is a hit. We will store the information in the hit variable.

// Update is called once per frame
void Update () {
Raycast hit;

if (Physics.Raycast(transform.position, transform.forward, out hit)) {

}
}

The if block’s condition will return true when the raycast hits something. In this case, we will use the hit variable. The condition will return false when the raycast does not hit anything. hit will not store a value, so we will not use it.

If the condition returns true, use the following code to print the name of the object the raycast hit.

// Update is called once per frame
void Update () {
Raycast hit;

if (Physics.Raycast(transform.position, transform.forward)) {
Debug.Log (hit.transform.name);
}
}

Save the script, and open Unity. Press Play. Press Alt/Option, and move the cursor until the crosshair is on top of Button. The console will print the message “Button” constantly because every time the Update method is called, it sees that we are looking at the button, and it prints the message.

Save your project. Want to learn more about buttons? Check out our Unity3D course, where you build 30 virtual reality games!

Designing a Button | Unity Tutorial

In virtual reality (VR) games, one of the few interactions a player can make is press a button by looking at it. In this tutorial, we will design a button in Unity. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

VR has limited interactions with keys. Other devices like computers or Xbox, which have a lot of keys that players can press to interact with the game. Create a cube in the Hierarchy. We will have the cube work like a button. Give Cube the position 0 -1 -5. Change its X Scale value to 2.

Create a material in the Assets folder. Make sure that you do not create the material in the Google SDK folders. Name the material “ButtonMaterial”. Drag ButtonMaterial to Cube in the Scene. Change the color of ButtonMaterial to green with RGB values such as 0 184 100.

We will have the button be somewhat see-through. From the Rendering Mode menu in the Inspector, select “Transparent”.

In the Color window, set the alpha of ButtonMaterial to 147.

We will have the button contain some text. Right-click on “Cube” in the Hierarchy. Select 3D Object > 3D Text. “New Text” will appear in the Hierarchy. The text “Hello World” will appear in the Scene.

Set the X Scale value of New Text to 0.5. In the Text Mesh component, set Anchor to “Middle center” and Alignment to “Center”.

Set the text to sit just in front of the cube by changing its Z position to -0.7. Change Font Size to 15. In the Text property of Text Mesh, change “Hello World” to “Btn” (a shortened form of “Button”).

The text “Btn” will be of poor quality in the Scene. To correct this, scale down New Text in the Transform component. Then increase its font size in the Text Mesh component.

As such, the button’s text will be of better quality. Rename New Text “Label”. Rename Cube “Button”. Want to learn more? Check out our Unity3D course, where you build 30 virtual reality games!

Activating VR Split Mode | Unity Tutorial

If you want to make your game work in VR, you need to activate the VR Split Mode. If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

Once you’ve integrated a VR software development kit (SDK), press Play to simulate the game. Notice that you will still not see the screen split to show the views of two cameras.

With Google VR SDK, we need to make a small adjustment to the game to view the scene in split mode. Stop playing the scene. In Assets, open the GoogleVR folder. Then open the Prefabs folder. We will use the GvrViewerMain.prefab file. This file has been saved for later reuse, so we do not have to build an entire game object that will change the scene.

Drag and drop GvrViewerMain.prefab to the Hierarchy. In the Inspector, you will see that the GvrViewerMain game object contains a Gvr Viewer (Script) component. This script does the VR logic.

Press Play. The Game window will show the scene from two cameras.

In the Hierarchy, click on “Main Camera”. You will see that this object contains Main Camera Left and Main Camera Right.

Click on “Main Camera Left”. In the Inspector, you can see that this camera’s X position is -0.032. Main Camera Right’s X position is 0.032. The distance between the cameras represents 6.5 centimeters, which refers to the distance between the human eyes.

A VR game contains two cameras to represent two human eyes. The left camera shows the scene from the player’s left eye. The right camera shows the scene from their right eye. With the help of a VR device, dividing the view into two cameras makes feel as though they are in a virtual world.

Create a cube in the Hierarchy. Move the cube closer to the camera. If you cross your eyes, you may be able to see the illusion that occurs because of the split view: the cube appears to be popping from the screen.

Press and hold the Alt/Option key. As you move the cursor, you will be able to look around the scene. If you hold Control, when you move the cursor, the scene will tilt. This could be used to change the weapon a player is holding when the player tilts their head.

Want to learn more? Check out our Unity3D course, where you build 30 virtual reality games!

Activating Virtual Reality | Unity Tutorial

The first step to making a virtual reality (VR) game is activating VR Mode. In this tutorial, you will learn how to integrate a VR software development kit (SDK). If you are a beginner and want to learn how to build virtual reality games, check out our Unity3D course!

What is VR Mode?

Create a new Unity project named “VRInteractions”. Save the file to your Project folder. Leave 3D rendering enabled.

In the file that opens, select Main Camera from the Hierarchy. Notice that in the Scene window, there are gray lines protruding from the camera. These lines outline the area that the camera renders.

Create a cube in the Hierarchy. Put the cube in the position 0 0 0. Select Main Camera. In the Scene, you will be able to see that the cube is inside the rendering area of Main Camera. The cube is inside the shape made by the gray lines protruding from Main Camera.

If you move the cube outside the area outlined by the gray lines, the camera will not render the cube. The player will not be able to see the cube.

A VR game contains two cameras to represent two human eyes. The left camera shows the scene from the player’s left eye. The right camera shows the scene from their right eye. With the help of a VR device, dividing the view into two cameras makes feel as though they are in a virtual world.

Downloading SDK

Delete Cube and Main Camera (1) from the Hierarchy. There are multiple ways to create a VR environment. We will use the SDK of Google Cardboard. Google Cardboard is a VR platform in which a user places a smartphone into a cardboard viewer. When the user looks into the viewer, they see the game on their phone in 3D.

If you do not have Google Cardboard, you can change the SDK settings to disable VR Mode. You will be able to play the game on your phone without VR Mode.

To download Google Cardboard, go to www.developers.google.com/vr/unity. You will reach the page “Google VR SDK for Unity”. This page provides details about the features of this SDK.

The bottom of the page contains useful links. Click on the “Unity API Reference” link to open a page containing details on how to implement the SDK.

You can look through this page to see details regarding the coding of the SDK, such as the available classes.

To download the SDK, click on the “Google VR SDK for Unity” link at the bottom of www.developers.google.com/vr/unity.

To integrate the SDK into the Unity project, you could clone the entire repository hosted on GitHub. Alternatively, click on the “gvr-unity-sdk” link.

You will be taken to a GitHub webpage. Click on “GoogleVRForUnity.unitypackage”. On the page that loads, press the Download button to download the SDK.

Double-click on the file that appears in your Downloads folder. Once the files decompress, an Import Unity Package window will open.

A Unity Package is like a zip file. It is a compressed file that contains many other files inside it.

You can see that the file contains scripts, materials, images, prefabs, and more. Instead of making our own plug-ins, we can import the ones in this package and adjust them. Press the Import button. Once the assets import, all the necessary files for activating the VR Mode will be in your Assets folder.

Depending on the Unity or SDK version you are using, you may be prompted to perform another import to ensure compatibility. You can press Import Package > Import to import the second package.

Want to learn more? Check out our Unity3D course, where you build 30 virtual reality games!