Python from Scratch: Variables, Data Types and Control Structure

Python from Scratch: Variables, Data Types and Control Structure

Tutorial Details
  • Program: Python
  • Difficulty: Easy
  • Estimated Completion Time: 20 minutes
This entry is part 2 of 5 in the Python from Scratch Session
« PreviousNext »

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!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://ashwin.co.in Ashwin

    This seem to be the great startup to learn python. Thank you very much.

  • Hiroshi

    Running on PC here, 30min into your tut. Good stuff so far. Could you also include how to access the document tree in PC? The bit where you enter “doc” then entered the python.py script to run. So I’m wondering what the PC equivalent of your “doc” is? Thanks in advance.

    • Hiroshi

      Nevermind! I rewatched and realized your new tab was strictly terminal. I opened command line (win+r); (cmd) and drag and dropped lessoon2.py into the GUI and it worked!

  • http://twitter.com/brunogama Bruno

    python is awesome.

  • Sparcorel

    Finally! …hope for some Django 1.3 tuts after this series. Keep up the good work!

  • http://butenas.com Ignas

    Finally! Finally you starting to write about Python. Of course for the web development beginners I think PHP is still the choice (while it’s easier to deploy, easier to find the hosting and easy to learn), but Python is the next level. Hope to see more tuts on Python here and then Django tuts :) Python rules! :)

    • Giles Lavelle
      Author

      Hey guys,

      Sorry to hear that the spacing has made it harder for you to learn – I don’t actually choose when these go up, I just make them and send them off. As you can see in the video, this one was actually made at the end of April.
      Not trying to shift the blame to the site editor though! There’s a lot of series running here on Nettuts+ so I’m sure it’s challenging scheduling them all.
      I have half of the next video created, and this comment thread should be some good motivation to get on and finish it! Again, I can’t make any promises about when it’ll appear, so I guess waiting until they’re all done and watching then might make sense if you’re struggling to remember previous content.

      Thanks for watching though! :D

      • w1sh

        Makes sense. I think in the last tut you told everyone in the comments these would be up once a week. I didn’t realize you meant you’d make them once a week and they’d go up once a month.

        Either way it’s cool so long as this basic Python series is followed by an in-depth, full-on, sweet, sweet love-making of Django and other Python frameworks. This is after all NETtuts. :)

        Thanks for trying your hardest to get the joy of Python out there Giles.

  • Jason

    It would be great if you could ramp up the speed in which these come out. A month and a half between instalments means it not worth even reading until sometime next year when the series is complete..

    • Will

      Yeah, weekly instalments would be a lot better… Please :)

      • w1sh

        Y’know. I catch a lot of flak for being the jerk around these parts because I say things like, “Wtf happened to the Python tuts?”

        But this proves a good point.

        I’m not the only one.

        These Python tuts are far and few between.

        To anyone interested in taking Python seriously, I suggest you check out:

        http://docs.python.org/tutorial/index.html (use 2.7.x – not 3.x – just trust me)

        …once you have a solid grasp of what Python is and how it works, move on to…

        http://djangobook.com/en/2.0/

        Enjoy!

      • http://www.vareen.co.cc Neerav

        Totally Agree!

        Actually, I didn’t remember anything of the first lesson and now I have to read it again.

  • AJ

    Thanks bud. This tutorial is really great. Could you please release screencasts more frequently, as it helps keep the pace, and that way, I’ll also remember what was taught in the previous screencast.
    Thanks

  • http://juniornascimento.com Junior Nascimento

    Very good tutorial, it helped me alot!

  • Jonathan Chrisp

    Thanks Nettuts!! Giving us endless opportunities to constantly learn!! :)

  • Mike

    I want the next part!

    MOAR!

  • Mohammed Husein

    Awesome !

  • Daquan Wright

    I’m gonna watch the vid, learning Python through a computer science book. It’s a popular language for scientific computing and generally a good glue language for big applications. There’s a host of good books on amazon, be sure to check it out people.

    Python is capable of web development, just not nearly as intuitive as is PHP or even Ruby (imo). Anyway, cheers.

  • http://www.universalsoftworks.com Joseph Williams

    Very interesting Giles. I can not wait for the next video.

    Keep it up!

  • Miguel

    You explain everything so well. I will be watching this series all the way to the end. I am a python beginner and this was an A+ tut!

  • w1sh

    For those interested, there is also an entire MIT course on Python (complete with videos, code snippets, assignments, etc). Follow through with this (exercises and all) and you’ll be a Python guru in weeks to a month: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008/

  • http://nxqd3051990.blogspot.com nXqd

    Aside from nettuts, if you guys want to learn more about python. You guys should check out diveintopython.com and diveinpython3.com :)

  • http://twitter.com/brunogama Bruno

    Google have some nice tutorials for the newcomers: http://code.google.com/edu/languages/google-python-class/

  • http://pixelwolf.tumblr.com Niam

    Nice tutorials! By the way, what text editor are you using in Chrome?

  • http://www.mediazoom.ca John

    This is a great series! I’ve decided this to be the first language to learn and I must say your very easy to understand and follow!

    Also some good references to other resources for learning in the comments I didn’t know about. I love you guys!!

    • ddub

      Just my opinion, but I don’t think this article is broad enough to make it the best option for learning how to program.

  • Raja

    Thank you so much…………..This is a great way to get started with python …:)

  • Michael Frasco

    Hello,

    I was wondering how to navigate to files that are not stored in my documents folder, for both pc and mac, could you please shed any light upon this situation?

    thank you

  • phoenix.rising055

    Thanks for your time, this is really helpful.

  • http://forrst.me/adityamenon aditya menon

    Thank you! I come from PHP, and a few things like no semi-colons and curly brackets are slightly unnerving :) This video really helped me grasp the basic syntax variations in Python – I will certainly see all these videos! Great job!

  • https://twitter.com/#!/Caparico Kobe

    Pretty sure that at around 38:30 you removed Photoshop from your deck. :-)

    • Kobe

      Dock, of course. tihi

  • http://brandonvlaar.com brandon

    Thank you so much for this tutorial!
    You’re a great teacher

  • Justin

    Oh and also thank you for all your tutorials, they are so in depth and I’ve probably learned more from them then any accumulated source up to this point. Thanks and be well!

  • Liam

    Thanks man, these tutorials have helped me a great deal! Really appreciate it!

  • Walter

    Simply great! You can be the smartest guy on earth, but if you don’t have the ability to teach, forget it. Remember, there are no bad students, only bad teachers. I bet you, everybody here is a good student.

  • Mangalamurthy Bhat

    Hi
    in python 3.3 the print “some thing” gives error i have to type like print (“some thing” ).

    I am using ubuntu 12 with python shell

    • Kamil

      Yes, because print is function (method). And with function you need to provide argument with parenthesis. Using print without parenthesis was comfortable but generally incorrect. In python 3.x it’s deprecated, so since you are using newer version of Python you need to write print(“here text”) which also works in previous python versions (2.x).