Advertisement
Python

Python from Scratch: Variables, Data Types and Control Structure

by

Welcome back to Python from Scratch, where we're learning Python...from scratch! In the last lesson, we installed Python and got set up. Today, we're going to cover quite a bit, as we learn the essentials. We'll review variables, operators, and then finish up by learning about control structures to manage the flow of your data.


Video Tutorial

Alternate Source
Subscribe to our YouTube and Blip.tv channels to watch more screencasts.

Variables

Variables are the first thing you should learn in any new language. You can think of them as named containers for any kind of data. The syntax to declare them is: name = value You can name anything you like (except for a handful of keywords), and their values can be any type of data.


Data Types

There are many data types, but the following four are the most important:

Numbers

Numbers can be either integers or floating point numbers.

  • Integers are whole numbers
  • Floats have a decimal point

Strings

String are lines of text that can contain any characters. They can be declared with single or double quotes.

	empty = ""
	escaped = "Can\'t"
	greeting  = "Hello World"
	multiLine = "This is a long \n\
	string of text"

You have to escape single and double quotes within the string with a backslash. Otherwise, Python will assume that you're using them to end the string. Insert line breaks with \n. Python also supports string interpolation using the percent symbol as follows:

name = "John Doe"
greeting = "My name is %s" % name

You can access sets of characters in strings with slices, which use the square bracket notation:

"Hello"[2] #outputs "l"

Booleans

Booleans represent either a True or False value. It's important to note that you have to make the first letter capital. They represent data that can only be one thing or the other. For example:

	isMale = True #Could be used in software with a database of users
	isAlive = False #Could be used in a game, set when the character dies

Lists

Lists are used to group other data. They are called Arrays in nearly all other languages. You can create a list with square brackets.

	emptyList = []
	numbersList = [1, 2, 3]
	stringsList = ["spam", "eggs"]
	mixedList = ["Hello", [1, 2, 3], False]

As you can see above, lists may contain any datatypes, including other lists or nothing at all.

You can access parts of lists just like strings with list indexes. The syntax is the same:

numbersList[1] #outputs 2
stringList[0] #outputs spam
mixedList[1][2] #outputs 3

If you nest a list within another list, you can access them with multiple indexes.


Comments

Comments are used to describe your code, in the case that you want to come back to it later, or work in a project with someone else.

#This a comment on it's own line
#You create them with the hash symbol
var = "Hello" #They can be on the same line as code

Operators

You've seen operators before. They're those things like plus and minus, and you use them in the same way that you learned in school.

	2 + 3 #Addition, returns 5
	8 - 5 #Subtraction, returns 3
	2 * 6 #Multiplication, returns 12
	12 / 3 #Division, returns 4
	7 % 3 #Modulo, returns the remainder from a division, 1 in this case.
	3**2 #Raise to the power, returns 9

You can also assign the result of an operation on a variable back to the same variable by combining the operator with an equals sign. For example, a += b is a more concise version of a = a + b

	x = 2
	x += 4 #Adds 4 to x, it now equals 6
	x /= 2 #Divides x by 2, it now equals 3

Control Structures

Once you've created and manipulated variables, control structures allow you to control the flow of data. The two types we're learning today are conditionals and loops.

Conditionals

Conditionals allow you to run different blocks of code based on the value of data.

a = 2
b = 3

if a < b:
    print "Success"

Loops

The two types of loops we're discussing here are for loops and while loops. for loops work using lists, and while loops work using conditions.

while loops

a, b = 0, 5

while a < b:
	print a
	a += 1

for Loops

myList = [1, 2, 3, 4, 5]

for a in myList:
	print a

Conclusion

That's it for today, but we've covered a bunch of techniques. Feel free to run though everything a few times until it makes sense. I'll try and answer any more questions in the comments, and I hope you'll join me for the rest of the series!

Related Posts
  • Code
    PHP
    Object-Oriented Programming in WordPress: Control Structures IIWordpress oop
    WordPress is a powerful CMS that provides a flexible foundation on which to build both sites and applications. If you want to extend WordPress functionality, then you do so via plugins. Although there are a number of different ways to do that, this series has us taking a look at object-oriented programming specifically from the perspective of a beginner and in the context of WordPress. In this post, we're looking at a second set of control structures that allow us to control the flow of code throughout an application.Read More…
  • Computer Skills
    Electronics
    Building a Wireless Sensor Network in Your HomeSensors
    Your environment is full of all sorts of fun and useful data, but getting it all together can be a challenge. In this tutorial you will learn how to use Arduino and Raspberry Pi technology to create inexpensive, wireless sensor nodes that report their data back to the Internet of Things. Read More…
  • Code
    WordPress
    Object-Oriented Programming in WordPress: TypesWordpress oop
    In the last post, we took a look at classes which are the building blocks of object-oriented programming. Before we go any further, we need to take a survey of some of the data types that PHP offers. Though we won't be reviewing every type in this particular article, we're going to take a look at some of the more popular types that we'll be using in WordPress development.Read More…
  • Web Design
    eCommerce
    Getting Started With Liquid; Shopify's Template LanguageShopify 2 preview
    This tutorial will introduce Liquid, the Shopify template language. We'll look at the benefits of Liquid, discuss how it enables us to pull in and manipulate data from our stores and finally showcase a number of its key features that you will find yourself using daily in your Shopify theme development.Read More…
  • Code
    iOS SDK
    Objective-C Succinctly: Data Types0e5ds8 preview image@2x
    Objective-C has two categories of data types. First, remember that Objective-C is a superset of C, so you have access to all of the native C data types like char, int, float, etc. Objective-C also defines a few of its own low-level types, including a Boolean type. Let's call all of these "primitive data types."Read More…
  • Code
    Android SDK
    Android SDK: Java Application ProgrammingAndroid preview@2x
    Our goal in this series is to learn about Android SDK development. So far we explored the development tools, looked at the structure of an Android app project, started to create a user interface, and responded to user interaction. In this tutorial, we will look at the basic structures and concepts in Java that you need to know in order to start developing apps for Android.Read More…