Programming for Complete Beginners: Python - Lesson 1
As a continuation of my last post, I'm going to try to give a quick little introductory lesson on Python that's going to teach the very basics. My goal is to make these lessons short, sweet and to the point so that no one gets bored.
- Note: There are two main versions of Python. Python 3 and Python 2. This lesson (and probably all the others) will use Python 3. Just because it's new and shiny. Who doesn't like new and shiny?
Variables and Data Types
Variables and data types are the tools you use to write any piece of code. Let's say you want to save your age and maybe add 2 to it. In Python you can do it like this:
age = 10
Yep. That's it. No quotations. No weird words. You just type a name and then equate it to whatever you want.
Note that variable names cannot start with a number or contain any weird characters. A variable name must start with a letter and contain only letters, numbers and underscores.
One of the biggest advantages of Python is that it has type inference. Type inference is the ability of a language to figure out the type of the thing you wrote depending on what it looks like. To Python, the above line of code looks like you're equating a number to the variable age
so that is what it's going to treat the 10 as. Just a number.
You can also perform any math operation:
watermelonSize = (1 + (3*3) - 2/ 2))
Python automatically figures out order of operations. You can obviously also use variables together:
myAwesomeNumber = 21
myOtherAwesomeNumber = myAwesomeNumber + 2
(will evaluate to 23)
What if you want to write a word/sentence? Easy.
my_name = 'robert'
or
my_name = "robert is still my name"
Notice here you can use either double or single quotes when writing strings, Python doesn't care.
If you want to concatenate (mash up) two or more strings together you can use the +
operator between them.
name = 'robert'
myName = 'my name is: ' + name
("my name is: robert")
Try it Yourself!
You can try everything above yourself in this link. To display a variable value in the console just type print(yourVariableHere)
in your code.
Go play around for a bit. Maybe calculate the circumference of the sun or something. The next lesson will teach you how to save multiple values in the same variable at the same time and no it's not magic :)
If you run into any problems leave me a comment and I'll get back to you as soon as I can. Also, if you would like to learn anything in particular also leave a comment. I would also be grateful if you resteem this post so more people can learn about the wonders of Python! :-)
Very cool. Thanks for this.