Python For Beginners (A tutorial that teaches more then hello world)
h
InvisibleOne (765)

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.
Like this: 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:

multiline_string = “””This is a multiline string!
It is more then one line!
Lots of lines
Lots and lots of lines!
“””

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:

myDict = {
	‘key1’ : ‘This is the value of key1’,
	‘key2’ : 25
}

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:
print(“Hello World!”)
You can also print variables, all you have to do is put the variable inside of the print instead of a string

myVar = “Hello World!”
print(myVar)
#This will print “Hello World!" to the console

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:

myList = [“This is index 0”, “This is index 1”, “This is index 3”]
pritn(myList[0])
#This will print the item in myList with an index number of 0

And if we want to print the second item in a list, we just need to print myList[1]
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()
Append adds an item to the back of a list. And using it looks like this:

myList = [‘One’, ‘Two’, ‘Three’]
print(myList)
#This will print [‘One', ‘Two', 'Three’]
myList.append(‘Four’)
print(myList)
#This will print [‘One', 'Two', 'Three’, 'Four’]

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: myList.remove(‘Four’)
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:

myDict = {
	‘key1’ : ‘This is key 1!’,
	‘key2’ : ‘This is key 2!’
}
print(myDict[‘key1’])

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

myBool = True

Now, let’s make it print something while that variable is equal to true.

myBool = True
while myBool == True:
	print(“This will print forever!!!!!”)

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

for number in range(10):
	print(“This will be printed ten 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.

Back story:

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

Solution:

We should make a for list to print out each item.

cows = [‘George’, ‘Marco’, ‘Tim’, ‘Bessy’, ‘Martha’]
for cow in cows:
	print(cow)

Explanation

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:

if value == another_value:
	do this code

Else, is basically, else to this

if value == another_value:
	do this code
else:
	do this code

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.

if value == another_value:
	do this code
elif value == a_different_value:
	do this code
else:
	do this code

Now, let’s use this in our example.

Back Story:

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

Solution:

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

cow_ages = [1,1,2,4,2,4,2,6,7,3,4,6,2,,1,7,7,4,2]
old_cows = 0
young_cows = 0
for cow in cow_ages:
	#check what the item is
	if cow < 5:
		old_cows += 1 #note: += adds the value to the variable, it's basically variable = variable + 1. It adds a number to a variable without resetting the value of a variable
	else:
		young_cows += 1
# now we can print our results!
print(old_cows)
print(young_cows)

Explanation

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:

def myFunction():
	print(“This is a cool 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 a function:
myFunction()

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.

Back Story

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.

Solution:

def age(years):
	m = years / 12
	return m

number = input("How old is the cow in years: ")
year = int(number)
months = age(year)
print(months)

Explanation

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:

#get input from the user
num = input(‘Please give me a number:  ‘)

try:
	int(num)
	print("Yay, this is a number!")
#and if num cannot be converted into a number
except:
	print("Hey! That isn't a number.")

Try and except are great for error handling, which basically means knowing if an error happens of if something isn’t working.

Modules

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 import nameofimport
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: import math
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: math.sqrt()

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:

import time
print("Hi there")
time.sleep(3) #this will make it wait three seconds before continueing
print("This will print three seconds later")

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 os.system(‘clear’)

import os
os.system('clear')

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:

import random
my_list = ['one', 'two', 'three']
random_item = random.choice(my_list) # chooeses a random item from the list
random_number = random.randint(1,10) # Will pick a random integer from the range of the first number to the second number. 

These aren’t the only modules in python though, there are thousands of others that are really awesome!

Cool Games!

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.

import random

Now, let’s get ourselves a random number from 1, to 10

import random
number = random.randint(1,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

import random
number = random.randint(1,10)
win = False
while win == False:
	#We'll put our code here

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

while win == False:
	guess = int(input("Guess my number!")) #make sure to use int() to turn it into a number and not a string!
	if guess == number:
		print("You got it!")
		win = True
	#now let's use elif to see if their next guess needs to be higher or lower
	elif guess > number:
		print("Nope, that's too high!")
	elif guess < number:
		print("Nope, that too low!"

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!

import random
number = random.randint(1,10)
win = False
points = 5

while win == False:
	guess = int(input("Guess my number!")) #make sure to use int() to turn it into a number and not a string!
	if guess == number:
		print("You got it!")
		print("You got: " + str(points) + " points") 
		win = True
	#now let's use elif to see if their next guess needs to be higher or lower
	elif guess > number:
		print("Nope, that's too high!")
	elif guess < number:
		print("Nope, that too low!"	
	points -= 1 # -= is like += but the opposite, it removes not adds

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!

import random
import time #let's add time to the mix
import os #os as well
number = random.randint(1,10)
win = False
points = 5

while win == False:
	os.system('clear') # clear the screen
	guess = int(input("Guess my number!")) #make sure to use int() to turn it into a number and not a string!
	if guess == number:
		print("You got it!")
		print("You got: " + str(points) + " points") 
		win = True
	#now let's use elif to see if their next guess needs to be higher or lower
	elif guess > number:
		print("Nope, that's too high!")
	elif guess < number:
		print("Nope, that too low!"	
	points -= 1 # -= is like += but the opposite, it removes not adds
	time.sleep(2) # give them a little bit of time before clearing the screen so it doesn't erase the text right away

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.

import os
import random

list1 = ['sit on a couch', 'do a handstand', 'jump up and down', 'demonstrate yoga', 'act like Darth Vader is choking you', 'do a pushup', 'lay down', 'put on a hat', 'drink a cup of water', 'touch the wall']
list2 = ['while picking you nose', 'while holding you nose', 'while singing', 'while tapping your head', 'while singing jinglebells', 'while drinking water', 'while laughing', 'while clapping your hands', 'while stomping your feet']
list3 = ['your mom', 'your best freind', 'the wall', 'a cat', 'a keyboard', 'your neighbor', 'a sock']

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

while True:
	#clear the screen
	os.system('clear')
	#generate the dare
	print(random.choice(list1) + ' ' + random.choice(list2) + ' infront of ' + random.choice(list3)
	input("Do you want another dare? Hit [enter] for yes")

And there you go, now you have a cool dare generator

Monster Battle

Requirements: More complicated coding, functions, random, os
Difficulty: Medium

Building a monster battle game is really fun, and here’s how to do it.
We’ll start by created some variables

import random
import os

life = 100
coins = 10
weapon_damage = 3
monsters_defeated = 0

Now let’s start by creating a battle function

def battle():
	enemy_life = random.randint(1,50)
	enemy_damage = random.randint(1,10)
	battling = True
	while battling == True:
		print("Life: " + str(life)) #remember to convert it to a string
		print("You attack the monster and deal " + str(weapon_damage) + " damage!")
		enemy_life -= weapon_damage
		print("Enemy attacks you and deals " + str(enemy_damage) + " damage!")
	

Now we need to check whether or not we died after that attack

def battle():
	enemy_life = random.randint(1,50)
	enemy_damage = random.randint(1,10)
	battling = True
	while battling == True:
		os.system('clear')
		print("Life: " + str(life)) #remember to convert it to a string
		print("You attack the monster and deal " + str(weapon_damage) + " damage!")
		enemy_life -= weapon_damage
		print("Enemy attacks you and deals " + str(enemy_damage) + " damage!")
		if life <= 0:
			print("You have been defeated...")
			print("In your career you killed " + str(monsters_defeated) + " monsters")
			exit()
		elif enemy_life <= 0:
			print("You defeated enemy!")
			coins += 10
			monsters_defeated += 1
			break
		else:
			input("Press [enter] to continue fighting")

Alright, now that we have that battle function done, let’s build the beginnings of our game

playing = True
while playing == True:
	print("[1] Fight")
	print("[2] Upgrade Weapon")
	choice = input()
	if choice == '1':
		battle()
	elif choice == '2':
		#check if player has enough coins
		if coins >= 10:
			print("You upgraded your weapon!")
			damage += 1
			coins -= 10
		else:
			print("You need more coins!")
	else:
		print("Hey, that wasn't an option, please choose one or two"

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)

import sys
import time
def slow_print(value):
	for char in value:
		sys.stdout.write(char)
		sys.stdout.flush()
		time.sleep(.05) #sleeps this amount of time between printing letters
	print()	

# example

slow_print("Hello World!")

Colored Text

black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
magenta = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"
that_pass = 'JonathanLevi'
bright_black = "\033[0;90m"
bright_red = "\033[0;91m"
bright_green = "\033[0;92m"
bright_yellow = "\033[0;93m"
bright_blue = "\033[0;94m"
bright_magenta = "\033[0;95m"
bright_cyan = "\033[0;96m"
bright_white = "\033[0;97m"

# example

print(red + 'Cool red text!')
print(green + 'And now it's green!')
slow_print(bright_cyan + 'it works with slow print as well!')

Reading and writing to text files in python

# write to a file
with open('myfile.txt', 'w') as file:
	file.write("This will be written to the file!")

# read from a file
with open('myfile.txt', 'r') as file:
	data = file.read()
	print(data)
	# will print what was written above

# add to file
with open('myfile.txt', 'a+') as file:
	file.write("This data will be appended to the file!")

#you can also write to python files!
with open('main.py', 'a+') as file:
	file.write("""\nprint("Hello World!")""") #\n means drop a new line

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)

You are viewing a single comment. View All
Bookie0 (5099)

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 print or comments? idk.