Python For Beginners (A tutorial that teaches more then hello world)
Python For Beginners
Python is one of the coolest and easiest (in my opinion) to learn languages!. Anybody who doesn’t learn python must be an idiot! Just kidding, but it’s a great language to learn.
Before I get started, there are three rules you should ALWAYS follow when coding, and these are them:
Rule Number 1: Never stop learning
Rule Number 2: Always know what your code is doing. If I point to a line of code and you don’t know what the line of code does, then you need to go back to the basics until you figure it out.
Rule Number 3: Ask for help, don’t avoid asking others for help because you think it will make you look dumb. Everybody was a beginner once (except for me of course) , and asking questions will accelerate your learning process.
Ok, now for the basics. In programming, we have something called a ‘variable’ or ‘variables’, var for short. Variables hold pieces of data that we use in our code.
In python, you assign a variable a value with the ‘=‘ sign. Like this:
myVar = data
The name of a variable can be whatever you want, as long as it doesn’t conflict with other special words in python (i.e with, if, else, in, for, while, etc.)
There are four types of variables, string, integer, float, and boolean.
A string is just a string of text. However, strings get cold easily so you need to cover them with a quotation mark blanket, one on each side.
myString = “This is a string!”
You can also do multiline strings, that is a string with multiple lines, however, big string like these need lots of blankets, so we put 3 Quotation marks on each side, like this:
Next we have Integer. Integer is just a normal number. He’s a very stern and stiff variable, and has some rules. First off, he never has any little helpers, as in decimals. He’s always just a number. And, he’s tough and doesn’t need a blanket like those weak little strings.
Variables that hold integers look like this:
myInt = 19
Floats are almost like Integers, but they are a little on the softer side. They don’t need the blankets, and they like to have some little helpers around, decimals. Floats look like this:
myFloat = 4.39394
And finally, we have Booleans. Booleans are a unique type of variable, they only have two values. While an integer or a string or a float can be whatever number, text, or decimal number you want it to be. Booleans can only be ‘True’, or ‘False’
They are like a computer bit, 1, or 0.
Booleans look like this:
myBoolean = False
Now, there are two more ways to hold data that I want to show you. Lists and Dictionaries.
Lists, are a list of values, they can be a mixture of numbers or strings or booleans or floats or even other variables or lists. Data in lists need to social distance, so make sure to put a comma between them. Lists are sort of like a farmers field, the cows are the data. Too keep them in they need a fence around them, and that fence is a brace ‘[‘ You put an opening brace at the start of a list, and then a closing brace at the end of a list.
A list should look like this:
myList = [“This is a list of data’” 18, 23.33, True, “list’s are cool!”]
Then we have dictionaries, dictionaries are sort of like lists, but their data is special. Each have their own special name or tag called a key, and instead of being kept in by normal braces, they are kept in with curly braces. Dictionaries look like this:
Pretty cool right, but wouldn’t it be cooler if we could see what was going on? Well we can, with print()
Print is the python command to print something to the console. Print, prints whatever is inside of the parenthesis. You can print something like this:
You can also print variables, all you have to do is put the variable inside of the print instead of a string
Now what a minute, what is that line of code with the hashtag (or number) symbol infant of it?
That is a note. Notes are invisible to python, they are simply there for us to use to help us remember what we were doing, or what a line of code does. All you have to do to create a note is put ‘#’ and then whatever you want after it.
Alright, back to print. Print can also print numbers and floats and strings and booleans.
Now that we can print stuff to the console, let’s do some cool stuff with a list. As I said above, a list holds a list of data. But how do we get that data? Well, first, we mention the list
myList then add brackets
myList and then the index number of the item we want to get from the list.
To computers, counting to ten looks like this: 0 1 2 3 4 5 6 7 8 9 10, so zero is always the index number of the first item in a list, then 1, and 2 and so on.
So if we want to print the first item in a list, all we have to do is:
And if we want to print the second item in a list, we just need to print
Lists are pretty cool right? But they get even cooler, in python, we can add and remove items from a list. To add an item, we use
Append adds an item to the back of a list. And using it looks like this:
Removing items from a list is just as easy, we use
.remove() with what we want to remove being in-between the parenthesis
Suppose we changed our mind and wanted to keep myList as only counting to four. It’s simple, just:
And Viola, ‘Four’ is gone.
Dictionaries are a bit more confusing, at least they were for me. To get an item from a dictionary, you do the same thing as a list, but instead of putting the index number in the brackets, you put the name of the item, called the key. It looks like this:
You can also change the value in a key, like this:
myDict[‘key1’] = new_value
Now that you know the basics, we can get into the more fun stuff, like loops and functions. I think that I’ll do loops first because I think they are easier to understand.
There are two main types of loops, the while loop, and the for loop. The first is the while loop. The while loop repeats a block of code while a condition is equal to a certain value. Sounds complicated, but it isn’t.
First, let’s make a Boolean variable, and let’s set him equal to true
Now, let’s make it print something while that variable is equal to true.
Now, let’s break this code down into lines. The first line, sets the variable myBool equal to True.
The next line says that while myBool is equal to true, do the code that is indented below. It uses double equal signs to check if myBool is equal to true. However, there are other types of operators (I think that’s what they are called), like ‘!=‘ or ‘>’ or ‘<=‘. Here’s a full list, and what they mean.
‘==‘ means: ‘is equal to’
‘!=‘ means: ‘is not equal to’
‘>’ means: ‘greater than’
‘<‘ means: ‘less than’
‘>=‘ means, ‘greater than or equal to’
‘<=‘ means, ‘less than or equal to’
After these, you put the value that you are checking against, which in our loop is ‘True’. Then we put ‘:’ so it knows to do all the code below.
Now, when we drop a line we indent it with tab. And it will run whatever code is below until the condition above changes, which in our case never happens.
There are two ways to break a loop, the first is ‘break’ which breaks out of the loop. Or you can change the condition. For example, we could change myBool to False, and then it would break the loop.
The next type of loop is a for loop. A for loop does the block of code below it for a certain amount of times. We use range to make it do something a certain number of times
Now, ‘number’ in this loop, can be anything, it can be bob or bill or a;ldskjfa;kdjf;aljdf. But most of the time people use ‘i’ I don’t know why, but I guess because maybe it means in? But idk.
For loops are also great friends with lists, and they work well together. Let’s make a fun little program.
Joe is a farmer, he has a list of the names of his cows, and he would like it if we could print them all out
We should make a for list to print out each item.
So, line one is the list of names.
Line two is a for loop. Broken down simple, goes for cow (and cow can be anything you want, I often use item) in cows: Notice that there is a colon at the end of the line, that is important and don’t forget them
And finally print(cow) (and if we had change it to item, we would of put: print(item))
And now we have if/elif/else statements.
If statements check if something is equal to something else, and should look like this:
Else, is basically, else to this
And then we have elif, which means, else if. It’s like an if statement as in we can check if the value is equal to something, it it happens after the first if statement, You can have as many elif’s as you would like.
Now, let’s use this in our example.
Joe the farmer is pretty impressed with our simple system, so he asked as to make him another system. He has a list of cow ages, and he would like to know if the cow is old or young, and then have us output two numbers, the first number is how many young cows he has, and the second should how how many old cows he has. According to him, an old cow is any cow older then 5
Sort through the list of cows and check the value using if and elif
Then add the values to variables depending if they are old or your
So, the first three lines of code, are our variables to hold the data. Beneath that is the for loop, that is going to run the block of code below for every number in the list of cow ages.
Now, for each number, it checks if the value is greater then five, and from there it chooses from two items.
If it is greater then five, it adds one to old_cows using +=
If is isn’t greater then five, then we add one to young_cows
Then, we print the number of old cows and then the number of young cows.
Now, I think you should have a pretty good understanding of loops.
It’s time for Functions! 👏
Functions are awesome in coding, because they are a block of code that you can reuse and reuse and reuse! They are great for things that you do over and over again.
To create a function, we need to define it. The keyword to define a function is ‘def’ then we put the name of the function, and then parenthesis. In between these parenthesis we put any inputs we want going into the function, then we put a colon, and drop a line. Anything indented beneath a function is part of that function, and will be run every time that we call that function.
Let’s make a simple function:
To call a function, we simple type the name of the function, and then the parenthesis, but we don’t need the ‘def’ or the colon.
Calling this function will result in ‘This is a cool function!’ Being printing to the console.
Now, let’s make one that is a little more complex.
Farmer Joe has a lot of cows, and he finds himself doing a lot of simple math problems over and over again. Joe isn’t that great at math so it would be great if we could code him a program that enables him to do simple math. He needs it to be able to tell how many months old a cow is from the amount of years. There will be one input, years, and one output, months.
Now, there is a lot of cool code going on in those lines. First, we define a function called age, with a single argument (input) called years.
Below that is the block of code that is executed with the function is called.
First, we set the variable m equal to years divided by twelve.
Then we use the keyword, return to return the value of m.
Below the function we have a line of code with something new. Input.
Input is used to get input from the terminal. It gives us the ability to type.
To use input, we create a variable, then set it equal to whatever input returns.
Input takes one argument which is the prompt that will be printed asking the user for an input.
Input returns on a string, so on the next line we use
int() to convert whatever is between the parenthesis into an integer. Then, we set a variable called months equal to whatever our function returns, which is the years divided by the months. And finally we print that out.
Now that we’ve gone over functions a bit, I want to teach you a few more things. If we are converting a string into an int, it has to be something that can be a number. We can’t convert ‘as;ldfjka’ into a number, it will just give as an error. Let’s build a simple program to see if the input can be turned into a number. We’ll use try, and except.
Try, basically says, ‘hey, try and do this’
And except: ‘And if you can’t, do this!’
Here’s what it looks like:
Try and except are great for error handling, which basically means knowing if an error happens of if something isn’t working.
One of the awesome things about python is that it is filled with hundreds or probably thousands of modules and libraries that you can import into your code. These imports allow you to do cool stuff like generate random numbers or clear the console. Some of the more common python modules are time, os, and random. I’ll show you how to use each one, but first let’s go over importing.
To import something into your file, all you need to do is type
That will import the file. Let’s suppose we wanted to do some more advanced math then pythons basic addition, subtraction, multiplication, and division. We would type:
However, math has a lot of stuff it in, and maybe I only want to use the
sqrt() function to get the square root. So instead of importing the whole module, I could type:
from math import sqrt
Now I can use the sqrt() function. However, if I had only typed import math, I could still use the sqrt() function, but I would have to type:
Another way to get around having to type
module_name.function_name every time is to simple import everything from that module, like this:
from math import *
In python the asterisk means all.
Time is probably the most common python module of all, because it allows you to pause you code and make it wait a certain amount of time. You use it like this:
os is really cool because it allows us to run command line commands in or code. It is mainly used to clear the screen, with
Random is one of the coolest of all, because you can use it to generate random numbers, or pick a random item from a list, here’s both of them demonstrated:
These aren’t the only modules in python though, there are thousands of others that are really awesome!
Now that you know the basics of python, let’s put those skills to work with three cool game that you can make!.
Number Guessing Game!
Requirements If and else statements, using random, os, and time, getting user input
Difficulty Rating: Easy
Ok, so the first thing we need to do is get a random number. We do this by importing the random library.
Now, let’s get ourselves a random number from 1, to 10
Ok cool, now we have our number. Let’s make a while loop so that the game keeps on going util the player guesses the correct number
So, the first thing we need to do inside of our while loop is get the user input, then we need to see if it is our number or not
Great! Now we have a cool working game, but we can still make it better. Let’s start by adding a variable that starts with 5 points, and every time that they guess the wrong answer, it removes one point!
Our game is looking pretty good, but it gets kind of messy and cluttered with all the printed text, so let’s do something to fix that!
Wow! That’s a pretty cool game and it wasn’t that hard to make.
Random Dare Generator
Requirements: Using os and random. Loops and lists.
Difficulty: Easier then spelling difficulty
Suppose you are hosting a party, and to show off your new coding skills, you want to build a fun dare generator game for you and your friends to play, here’s how to make one:
First, let’s import random and os, then make three different lists, the first list will be what you have to do, the second will be what else you have to do, and the third will be who you have to do it in front of.
This is starting to look good, let’s add a while true loop so they can keep on getting dares, then we’ll generate them a random dare
And there you go, now you have a cool dare generator
Requirements: More complicated coding, functions, random, os
Building a monster battle game is really fun, and here’s how to do it.
We’ll start by created some variables
Now let’s start by creating a battle function
Now we need to check whether or not we died after that attack
Alright, now that we have that battle function done, let’s build the beginnings of our game
The game looks great! This is just a simple one though, you can make them as complex as you would like. I would suggest to start by adding colors, then defensive armor or different types of weapons
Cool Code Snippets
Here’s some cool snippets of code
Slow print (Prints one character at a time)
Reading and writing to text files in python
Well, we’ve finally reached the end. I know it might seem like there is a lot in this tutorial, this is just the basics of python and there is so much awesome stuff you can do with it. Don’t get discouraged if you feel like you aren’t picking up on things quickly or don’t understand code. It took me months before I even started understanding what import did!
And if you run into problems with your code, don’t get frustrated, it happens to everybody. Just carefully look over your code, even the lines where it doesn’t say there is an error. Often an unclosed paragraph or bracket will lead to issues a few lines down.
If you can’t figure out what the problem is, just take a break, work on something else or get off the computer and take a breather in the great outdoors. Comeback fresh and you’ll probably see the issue, and if not, repl.it has a great space for asking questions and there are plenty of people there who will help you.
Don’t over code, don’t let yourself get so into coding that you do it night and day, if you do, you’re likely to get tired and you’ll actually find yourself getting worse. Coding is about solving problems and you can’t solve problems and think logically if you’re tired, not hydrated, or have had your snozzle glued to the computer screen for the last twelve hours.
Code with other people, it’s a great way to challenge yourself and get into the coding community.
Participate in coding challenges, test your skills, and work on the areas you are lacking.
Don’t just learn one code, there are lots out there and each have their uses
Don’t copy and paste code! This is really important because when I was learning to code I copy and pasted stuff, the only issue was, I had no idea what the code was doing. I’m not too much against copy and pasting, as it can help you learn, but credit the creator and don’t copy it if you have no idea what it is actually doing.
Don’t try and hack people. If you dumb enough to think you can hack somebody and get away with it, then you are probably too dumb to actually hack it and leave no trace. If you really think that you are a good hacker, go to hackthissite.org, there’s some pretty cool stuff to do around there, and you get to try some real hacking without committing a crime.
And finally, your mind is part of your body and your body is part of your mind, both of them need to be fit and taken care of for you to operate at maximum capacity, take care of your body, keep clean, don’t sit around on the computer too much, breath fresh air and get 7-8 hours of solid sleep. Trust me, you’ll code a lot better if you do.
if you need any help or have any questions, please let me know, I would love to help you (if I have time)
wow pretty cool, but try to separate your text in paragraphs as it pretty hard to read it.
also you first talk about:
Ok, now for the basics. In programming, we have something called a ‘variable’ or ‘variables’,
shouldn't you start with who made python and what it's used for? And maybe start with