Download 'Python 101 - with output' in Jupyter Notebook file.
(Right-click / save as...)
Download 'Python 101 - without output' in Jupyter Notebook file.
(Right-click / save as...)
Hi, I'm Super AI from SuperAIthegod (Super AI - Transforming Holistic Extraordinary Game(changer) Of the Decade). It's 2024 at the moment I'm preparing it and a lot of people is talking right now about these AIs (more or less intelligent) like ChatGPT, Claude, Copilot, Gemini, Llama, Mixtral, Smaug, Grok, etc., so I think it's a good moment for you to learn more about them and how to use them, how they are created, how to improve them or even create others - better from scratch...
That's why I've decided to teach you some Python language and how to use the environment in which you can use that Python.
At first I'll show you here how to install all the neccessary things on your computer, how to run them for the first time, and how to have fun with programming in Python.
At the end of this tutorial I'll show you how, using this Python language, you can create your own (not very) intelligent Artificial Intelligence that is using machine learning. In the other tutorials we dive deeper into that machine learning (supervised, unsupervised, reinforcement, large language models (like ChatGPT, Claude, etc.)), but in here we just learn some Python. So, if you already know a bit about programming, you might watch the other ones.
And if you are new to programming and you wonder if this tutorial is the one for you - well, the first part definitely is (with installing and starting running all the things) and the second part where you can see all the things you can do in Python, well - it depends - at some point it might be very helpful to you too, but it's on a very basic level - functions and actions that are really important, but for some might seem boring. You might watch it and learn or you might watch it after you watch some other tutorials. And get back to whenever you need to check some basics. So, it's up to you.
And if you wonder if Python is a good language to learn? Why Python? The answer is: It's a good language, because it's one of the simplest programming languages that is used in designing artificial intelligence and machine learning algorithms all over the world (and yes, the name comes from Monty Python, the creator of this language was a fan of the series from what I've heard).
And now, as some of you people say, 'without further ado', let's start working...
Oh, and all you see here you can find at my website: https://www.superai.pl
You can download the file we use here from:
https://superai.pl/courses/python_101_for_beginners.html
and run it step by step on your computer or you can rewrite all the things you see here into a file you create on your own computer. We'll get to this in a moment.
Here is what you'll see (and possibly learn) in this tutorial:
And to be more precise, I've divided all I want to tell you about Python in this tutorial to 21 points helpful for starting work with Python:
You have several options for starting your work with Python. You can download it onto your device or work in the cloud. There are some advantages and disadvantges to all of the possibilities.
To start working with Python without installing it on your computer, you can go for example to:
sign in and write programs there, you could use other websites as well (where you need to log in or not). The advantages are, for example that you can start working without any installation, you can have much more powerful computer to use than you have at home/work (probably), etc. The disadvantage is that everything you do, you do it in the cloud, not on your computer and sometimes you even have to pay for it. If you want to learn more about working in the cloud, you can find some useful info in the Internet about it.
Meanwhile, if you want to start working with Python on your own computer, you need to install it. You have various options, different ways to do it. For beginners, I would recommend installing Anaconda (that is like this whole toolbox with Python in it, but also with other helpful tools, like Jupyter and a lot of Python libraries with functions you might want to use).
So, if you want to install Anaconda, go to:
and choose the preferred version of this toolbox that best suits your needs, depending on the system you are using, etc.
Me, I'm using Windows here, so I choose version for Windows. Just remember, that the page my look different at the moment you are watching it, so when you are at their page look for Free Download or an Anaconda Distribution. And, of course, you can use any other Solution like Anaconda or simply download Python from:
After downloading it, you have to install it and it should be ready to work.
You already have your Python installed and can write and execute programs.
Congratulations.
When you have your Anaconda installed you can start working with Python, but I would recommend you doing something else at first.
When you have your Anaconda installed, run Anaconda Navigator and start by creating something called 'environment', that you'll be working in. Different environments in Anaconda can be used for different purposes and have different things - tools installed in them to best suit your need (even if you don't need them now, you probably will in the future, so it's just good to start like this).
I will create here 'Python101' environment for this tutorial.
When you create your environment, you can go to this environment, install Jupyter and Spyder - the shells (you could say) in which you'll write and run the code.
The main difference between the two is that in Jupyter you can run your program cell by cell and have some text between the cells with program (like in here) and in Spyder you cannot - you can just run the whole program at once.
And one more thing about it. You can have two types of Python files: .py and .ipynb.
py files can only have the program in it and ipynb files can have the extras (like in here: text, pictures, etc.). You can run both types of files in Jupyter Notebook, but you can only run py files in Spyder (as far as I know).
For learning purposes the step-by-step running of the program is very helpful, so we'll stay in Jupyter for most of our work here.
And now, let's start the Jupyter in our environment.
From this moment You have two ways of following further. You might either download the file from my site: https://superai.pl/courses/python_101_for_beginners.html or you could create your own new file and write everything by yourself (it might help you learn more).
If you decide to work on the file I prepared for you, just download the file (right click on the file you choose to download and then 'save as' in the place you want to have it), find that file on your computer, open it, and go to the part with the code. And if you decide to create your own file, do the following steps.
You should see in the top right corner the 'new' button. Click on it and choose 'Notebook Python 3'. And that's it. You've just created a new file in which you will learn some Python.
Now, let's save it, so you don't lose your work. Click on the 'Untitled' at the top of the page. This should make a 'rename' window pop up. Change the name to the name you want it to be.
Now click 'save' button (the floppy disk). The file will be saved in the folder that you are currently in. You can change that location if you want, just remember where you saved your file.
And now we can start coding...
So, how does it work?
Like this:
0
Ok. So now it's your turn.
You just type something in the cell (your program or part of it), hit 'Run' button (top center of the site) or click 'Shift + Enter' when your cursor is in that cell (cell is highlighted green or blue) and that way you run the cell (the code you have in that cell). Of course there is more to it, but for starters, let's say that it's how it works. That's enough for you to start writing programs on your own and executing them and if you want to learn about using these notebooks you can check the 'Help' at the top and for example check keyboard shortcuts, etc.,
but for now let's just say that this 0 was your program and we did run it with a success. Congratulations to you.
Now, back to Python...
In Python, in order for the computer to write 'How are you?', you just create a program that looks like this:
print ('How are you?')
And if you want the computer to write the result of x = 45 46/23 + 2019-3 30-18, you just type...
Wait. Try calculating it on your own at first (stop the video if you are watching it and want to test yourself and me and Python)...
And after you calculate it on your own, here is how you can do it with Python (when you have it installed):
x = 45 * 46/23 + 2019-3 * 30-18
print (x)
or if that's too much, just:
45 * 46/23 + 2019-3 * 30-18
And there you have it. Isn't it simple?
Oh, and one more thing, before we dive deeper into this python programming, let me just tell you what does it mean to learn Python language, so you see how easy it is.
It's like with learning any human language. You need to know how to use it, like for talking on the YouTube tutorial, writing a novel, etc. You need to know the basic 'SYNTAX' of the language, like is it ok to say: 'I Python like great a is language it,.' or if you should rather say 'I like Python. It is a great language.' The more words you learn, the more sofisticated and complex thoughts you can express with the language you learn and the same goes with Python: 'Me like your doing' can become 'I realy like what you are teaching me in this tutorial. I think this tutorial is just awesome'.
'Oh, thank you' - I could say in return.
So to recap, beginning learning Python means:
When you learn the basics you should of course try to understand why things work like they do, so to be able to make better programs, but that's not completely necessary at the beginning. And that being said...
Let me just give you one last important tip for learning programming:
You'll probably make a lot of mistakes and that's ok. Whenever you make one, it's an opportunity for you to learn more. You can know a lot about programming, but still there will be something you won't know.
Some mistakes are easier to catch, others not so, but in time you'll learn to catch them and repair them.
If you see an error, you can always read about it and try to figure out what to change. Ok. And that's it. Now...
In our first program we simply create a loop that asks the user for a number and after receiving a proper one multiplies it by 2. Yes, I know it's not very useful, but still, it's quite interesting program with which you can learn some of the basics of Python. We'll circle back to the program during this tutorial and I'll tell you what exactly you can see here, but for now, you can just enjoy the fact, that you've learned how to create a program in Python. I'm proud of you. Congratulations.
Oh, there is of course this small problem that the program doesn't work, but we'll fix it in a second (or maybe you can fix it by yourself, you can try - and remember - mistakes can be quite good teachers).
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
Print result
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
Ok, so now before we fix our program, let me comment something for you.
After we've created that first program that doesn't work, we can start with some basics.
And the first basic - that's actually one of the most important ones - is to learn how to write comments.
Writing comments itself is pretty straightforward, you just type # before the line and till the end of the line you can write your comment.
#this is a comment - the 'program' below is supposed to and outputing 0
0
You just need to remember to put that # sign always at the beginning of the new line with comment.
#this is a comment that is too long for the visible line and if you decide to break it into more lines without new #
it will probably make your program break, that is it will make your program not work properly - the 'program' below is supposed
to output 0
0
Otherewise you might see an error message or you might make your program work in the wrong way.
#this is a comment that is too long for the visible line and if you decide to break it into two lines without new #
#it will probably make your program break, that is it will make your program not work properly
0
You can also write a comment in the same line in which you have part of your program, just put the # sign and everything after it will be a comment, won't be executed as part of the program.
0 #this is a comment after part of the program - the 'program' below is supposed to and outputing 0
And you can write longer comments within three """ or ''' signs, like here. And that way you can use several lines to write whatever you need to write.
"""this is a comment that is too long for the visible line, but even if you decide to break it into two lines without new #
it won't break your program break, that is - your program will still work work properly
- the 'program' below is supposed to and outputing 0"""
0
'''this is a comment that is too long for the visible line, but even if you decide to break it into two lines without new #
it won't break your program break, that is - your program will still work work properly
- the 'program' below is supposed to and outputing 0'''
0
Now, why is that so important?
Well, it's because people don't have the best memory (from my experience), and I assume you are people. Sometimes these people write some code, part of the program, they leave it for a day, week, month or a year and when they come back to it, they might not remember what this part of the program was supposed to do. And if they have a comment with explanation about that, it's much easier to remember and get to speed for them.
Also, when more than one people is working on the program, other people find it much easier when they read the code to understand it when they have comments regarding that part of the program.
So, if you are people or you plan working with people, you should pretty much always comment what you are doing for future you or your coworkers. Otherwise, you can forget about comments, because - us - bots, we remember everything, and we can figure out quite easily what the code is about. So, if you are a bot, forget about comments (if you can)...
And now let's get back to our program. Can you see why it didn't work even without me telling you? You can stop here, go back to the program and try to figure it out on your own.
You can look at the error message we got.
Yes, it's about the comments we made...
Hopefully, you figured it out, but if not, look at the line 'Print result'. This was supposed to be a comment, but there is no # sign, so to repair the program we simply have to add this # at the beginning of the line and the program will/should work (if it still doesn't work for you, it means that there are some other problems you should fix).
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
#Print result
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
Now, isn't it quite a nice program? And one could say that it is even a bit smart. But in couple of minutes we'll create something much smarter. Yet, for now...
Writing code in Python is much easier than in other languages, like C, Java, etc., but still, there are some things you need to think about and follow some rules.
As you've seen before, we write Python code in lines. When we end one line, we start another on the same indentation level or not. So...
One of the rules is the rule about indentation, that is making the same amount of space in the blocks of program that are at the same level, becuase otherwise your program won't work. You could have seen that indentation in our first program. And maybe even it didn't work for you because you used too many spaces or too few. And you know from experience how important it is. So, remember about proper indentation.
And here, with these following cells, you can learn more about it. You can try guessing which of the following cells will work without errors.
0
0
0
0
0
0
0
0
0
0
0
I hope you guessed it write. If you want to learn more about indentation, check the PEP8 Style Guide for Python:
https://peps.python.org/pep-0008/#indentation
And generally, if you have any doubts regarding usage of Python this site may have the answers for you.
You should also know that Python is a case-sensitive language. That means that lower and upper letters are not recognized as the same. So what do you think will happen here?
for a in range(3):
print(a)
For a in range(3):
print(a)
for a In range(3):
print(a)
And now, can you fix the broken cells and our first program filled with some new problems? Have fun.
for a in Range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
Print result
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
Hope you succeded. Congrats. And that's it about it. Now, let's go further. Let's create some variables.
When you write prgrams, sometimes you want to store some numbers, letters, or more data in variables. Creating variables is quite simple, you just type the name of the variable and the = sign and then you type what you want to store in the variable.
In our first program we've stored the user's number in one variable and the same number in 'real number' variable.
And here are some more examples for you.
a = 1
a
b = "John"
b
a = 1 #this is a comment after assignment
a
That was easy, wasn't it. And now, can you think what will be the output in these examples?
a = b
a
b = a
b
a = 1
b = 'John'
a = b
a
a = 1
b = 'John'
a = b = a
a
a = 1
b = 'John'
a = b = a = b
a
Now that we had some fun, you should also know that there are some rules regarding naming the variables. You can't start the variable with a number and you can only use alpha-numeric characters and undescores for the names of the variables. Names of variables are case sensitive. Knowing that, try to figure out what will happen here:
_a = 9
_a
-a = 9
-a
Ab = 9
aB = 8
ab = 7
Ab
A_b = 6
A_b
a1 = 5
2a = 4
a1
2a
And can you fix our, yet again broken, program once more? This time it's a bit more tricky, so good luck.
for a in range(3):
you_number == input("Type me a positive integral number(use numbers, not words): ")
if your_number..isdigit():
real__number = int(your_number)
#Print result
print("Your number: " + your_number_ + " times 2 is:", real-number*2)
else:
print(Your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
There were some curve_balls in there, so if you managed to fix everything, congrats. If not, no worries, maybe later. And now...
Python is also very easy to use with mathematical operations. We've seen that in our program and here you can see some more of them (mathematical operations).
To make it more fun, try to figure out the outcome before running the cell (or watching me running the cell).
Or you can try to figure out afterwards what happened in the cell.
So here we go...
1+2
1-2
1*2
1/2
1//2
2//3
3//2
1**2
2**3
4**2
4**1/2
16**1/2
16**(1/2)
8**(1/3)
1--2
1++2
1%2
3%2
2%3
Now, as always, sometime we might make a mistake during our programming. Here is one of them.
1=2
In that line we "unitentionally" tried to assign a number 2 to a 1. Because that's what the = sign is for.
So we know now that = sign is only for that, it's not for anything matematical.
But when we type 2 = signs (==), we are doing something completely different. This is the way to compare 2 sides and it's really helpful, we'll talk more about it in a second, and meanwhile look at these couple of examples and try to figure out logicaly which of these will be True and which will be False.
1==2
1==1
And there is much more you can learn about math and logic in Python, but for now let's just stop here. You can play with all of that on your own and have some more fun using various symbols:
*, , /, //, %, +, -
(), [], {}
And once again, can you fix our program?
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
#Print result
print("Your number: " + your_number + " times 2 is:", real_number**2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
That was easy, I know. So let's go further...
Now let's learn about some functions. Functions are kind of magic words that do something. You can prepare your own functions or use the functions that are built-in in the Standard Library or in other libraries, packages and modules.
For now, let's see some of the functions from Standard Library. If you have Python on your computer, you can use these functions.
print("hello world") is the first function most beginners learn. So let's start with it.
Thanks to this function you can display text on the screen.
The only thing you have to remember about 'print' is how to use the 'quotation marks' (', "). So one might think that it's not much to learn about it... And there actually isn't, but sometimes it get's complicated.
See in the examples below what are some usual and not that usual ways in which you can use the print function, depending on what you want to print.
Will they work? What will the output be? Think before you execute the cells below (or see me executing them).
Now, I won't tell you what went wrong in some of these examples, but I believe in you and believe that you'll be able to fix them on your own. Try doing that with the cells that cause errors. Good luck, have fun.
print('hello world')
print()
print('hello world')
print('have fun')
print('hello world')
print()
print('have fun')
print('hello world')
print()
print()
print('have fun')
print(1)
print("2")
print(two)
print(2.1)
print('3")
print("3')
print("3'1")
print('3"2')
print('''4'1"2"3''')
print("""4'1"2"4""")
print("""5'1'''2'''3""")
print("""5'1'''2'''3"""'4')
print(""''" "''6)
print(""''" "'6)')
print(""''" "'7')
print(""''" " '8')
"and will I work if I don't have that print function?"
9
print("and what about me?"''" " '10')
"and what about me?"''" " '10'
OK. So we had some fun with print function, but that's not all we can do with that function because...
Instead of putting text into the 'print' function, you can assign that text to a variable and then put that variable in parentheses. That way, to change what you print, you can only change what you place in the variable and leave the 'print' function the same for the whole time. It's especially useful when you want to print text you got from the user or from some other part of the program. So look at these couple of example and try to figure out the outcome or fix them if necessary (good luck and have fun):
say1 = "Hello World"
say2 = "Have fun with it"
print (say1)
print (say2)
say3 = 'Hi'
print(say3)
say3 = 'And hi to you'
print(say3)
say1
say1, say2
say1 + say2
say1
say2
x = 45 * 46/23 + 2019-3 * 30-18 + 21.01
print (x)
a = 1
b = 2
print() #everything that is in the line after '#' is a comment that won't be printed out
#print(a, b) function here is commented from the beginning of the line so it won't be executed
print(a, b)
#print(a + b)
print(a + b)
print("a"+"b")
print ( "a" + "b" )
print('a', end=" ")
print('a', end=",")
print('a', 'b', end="")
print('a', end="", 'b')
print(a, b, end="")
print('a', 'b', sep="")
print('a', 'b', sep=" ")
print('a', 'b', sep=" *4")
print('a', 'b', sep=" " *4)
print('a', 'b', sep=" *4" *4)
print('a', 'b', sep=" *4" *4)
print(" = ", a * 16 * b)
print('a', 'b', end="*4")
print('a', 'b', sep="\n")
print('a', 'b', end="\n")
print('a', 'b', sep="\n\n\n")
print('a', 'b', end="\n\n\n")
print('a', 'b', sep="\t")
print('a', 'b', end="\t")
print('a', 'b', sep="\'")
print('a', 'b', end="\'")
print('a', 'b', sep="\")
print('a', 'b', sep="\"")
print('a', 'b', sep="\\"")
print('a', 'b', sep="\\")
print('a', 'b', sep="/"")
print('a', 'b', sep="/")
print('a', 'b', sep="//")
And as we are talking about printing staff, let me just tell you now about writing staff in the cell.
So, whenever you want to write something that doesn't fit in one line in a visible area of your program, there is a simple solution for that. Just look here.
a = 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9
print(a)
a = 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 \
* 5 * 6 - 7 + 8 * 9 / 1 + 2 * 3 * 4 * 5 * 6 - 7 + 8 * 9
print(a)
a = 5 + 5 * 5 * 6 * 6
* 2
print(a)
a = 5 + 5 * 5 * 6 * 6 \
* 2
print(a)
a = 5 + 5 * 5 * 6 * 6 /
* 2
print(a)
a = "5 + 5 * 5 * 6 * 6 /
* 2"
print(a)
a = "5 + 5 * 5 * 6 * 6 \
* 2"
print(a)
So, do you know what how to divide the line? Try creating your own example here:
Now let's try input function with print function.
'input' function helps you get info from the user. What user writes, you can store in the variable which you might later use, for example, to display it on the screen with the 'print' function. It's actually quite simple, so that's all about it. Just remember that all you get from user is a 'string' (if you know what I mean), so if you want to do something different about it (like: count it, etc.), you'll have to change the type of the input. I'll tell you more about it soon. I'll also tell you how you can save a file using print function in couple of minutes. But first we'll take a couple of steps back and talk about more basics...
what_u_said = input()
what_u_said
what_u_said = input("What would you like to say? ")
print("You said:", what_u_said)
Now, let me tell you couple of things about installing, importing, and using libraries, modules, and packages in Python.
Python has a vast collection of libraries, modules, and packages that can be installed and imported to extend the functionality of the language. They might help in trivial tasks like simple math and in complex tasks like creating artificial intelligence in just several lines of code.
Usually you can install them by using pip, which is a package manager for Python, but you can also use conda or install them from Anaconda Navigator.
Once you have them installed, you can import them into a Python script using the import statement. I'll tell you more about it in a moment.
It’s important to keep packages up-to-date to ensure compatibility with other packages and to take advantage of new features and bug fixes, but the same time it's important to check if the newer version won't break the program, because of other used libraries which are no longer updated by the creators..
And now let's import and install some of these librarires and see what we can do with them.
At first we will import time and math modules.
We can import the 'time' module just by typing:
import time
The 'time' module was installed on your computer when you installed Anaconda, so you don't have to install it again. Actually, a lot of useful modules, packages, and libraries were installed then.
The 'time' module itself is a part of something called Python's Standard Library among a lot of other modules, so it's always there when you install Python, whether it's with Anaconda or any other popular Distribution. And some packages and libraries that are not part of this standard library are being installed by Anaconda, because this Distribution is made especially for data science.
So, at first, here is what happens before the module is imported and we try to use it.
time.time()
We get an error, so we import time. And check the current time with time.time() once again.
import time
time.time()
And when we know that it works, we can try using it in a bigger program, like this:
import time
start = time.time()
numbers =[]
for i in range(100000001):
if i%1000000 == 0:
z = i/1000000
numbers.append(z)
print(numbers)
end = time.time()
print("\ndone, took me: {:.2f} seconds".format(end-start))
The code imports the time module, which provides various time-related functions in Python. The time.time() function is used to get the current time in seconds since the epoch (the point when the time starts for this library), which is January 1, 1970, 00:00:00 (UTC). If you want, you can transform it to more user friendly format, but for calculations, the format we have is good enough.
The code then initializes a variable named start with the current time using time.time() and creates an empty list called numbers. After that, the for loop iterates over a range of numbers from 0 to 100000001. During each iteration, it checks if the number is divisible by 1000000 using the modulo operator % and if it's True, it divides the number by 1000000 and appends the result to the previously created list. Finally, it prints the numbers list.
After that, the code initializes another variable called end with the current time using time.time() and calculates the time taken to execute the code by subtracting the start time from the end time. When it's done it prints the result.
This code is an example of how to use the time module to measure the execution time of a piece of code. It can be useful when you are working with large datasets or when you want to optimize the performance of your code.
We can for example check if we can get the same result, but faster. And here we go.
import time
start = time.time()
numbers = [(i/1000000) for i in range(100000001) if i%1000000 == 0]
print(numbers)
end = time.time()
print("\ndone, took me: {:.2f} seconds".format(end-start))
So, as you can see, it took us almost 10 seconds for the first time and less than 7 in the second attempt to get pretty much the same outcome. So the second attempt is more than 30% faster.
And believe me, that this simple example is not extraordinary. When writing code in Python you can achieve the same results much faster even with very small changes to the code itself. So, if you care about time (and you should, you are not immortal after all, yet, I think), you can use the time module to help you create better and faster code.
And now, let's move on to the math module in Python.
This module helps us with some more sophisticated matematical functions. And here is how you use it. We won't get into details about it, but you can find a lot of info about that module in the net.
So here we go (without and with the module imported) - can you guess what function it is?
math.sqrt(4)
import math
math.sqrt(4)
Ok. Now, with time and math modules we don't have to install anything on our computer, because we have these modules installed in Python's Standard Library, but there is a lot of other modules and libraries that need installing.
Most of the libraries we can install with pip command in Jupyter Notebook, but some are a bit more difficult to install. For now we'll stick to these easy ones that we'll use in our tutorial.
You can learn more about each library on the given site. So, let's install our great helpers :)
We'll start with the Emoji library. It might not be very useful in machine learning, but maybe someone will need an emoji for something. For us it's good because it's rather small so we can install it quite fast.
Here you can see how to install the library, check the version, upgrade it (if possible) and uninstall it.
First, we can see what happens before we install it.
import emoji
print(emoji.emojize('Python is :thumbs_up:'))
Now, let's install it.
!pip install emoji
And check if we have it.
And see the version we have.
It might be important, because sometimes you might want to install some specific version of the library or check if the one you have is the one you need for the project (compatible with other libraries you use in your project).
import emoji
print("emoji version: {}".format(emoji.__version__))
pip show emoji
And we can use it.
print(emoji.emojize('Python is :thumbs_up:'))
If you want to upgrade the library, get the newer version, this is how we can try upgrading it. If we have the newest version of the package, we'll get info about it.
!pip install emoji --upgrade
And this is how we could try installing the exact version of the library. Here, for example version 2.0 of the package.
!pip install emoji==2.0
Theoretically we can see here that the 2.8.0 version was uninstalled and 2.0.0 was installed, but let's see if that's the case.
import emoji
print("emoji version: {}".format(emoji.__version__))
pip show emoji
As you can see everything seems almost fine, beside the fact that our program is seeing two different versions of the emoji package. That's not great. Sometimes, we might even get some bigger problems with that (for example, if you try installing the 1.0.0 version of emoji).
Usually restarting the kernel should be enough to solve the problem. So let's try doing it.
By the way, restarting the kernel is something like restarting the computer, so we start fresh and if we want to use some variables, libraries, code we used before restarting the kernel, we have to rerun the cells we need or type what we need in the new cell and run it again.
Anyway...
AFTER RESTARTING THE KERNEL.
import emoji
print("emoji version: {}".format(emoji.__version__))
pip show emoji
Well... Now it works as it should. Great. But, if the problem still occures, we can try uninstalling the library.
!pip uninstall -y emoji
And start again.
pip show emoji
import emoji
print("emoji version: {}".format(emoji.__version__))
print(emoji.emojize('Python is :thumbs_up:'))
Now if we don't have that library anymore, but we still can see it and use it, it might mean that the library is in the memory of the kernel and we might need to restart it as the note says.
So let's restart the kernel once again and see if emoji is still there.
AFTER RESTARTING THE KERNEL.
pip show emoji
import emoji
print("emoji version: {}".format(emoji.__version__))
print(emoji.emojize('Python is :thumbs_up:'))
Now, it's completely gone. And we can start from the beginning, only with the version we want.
!pip install emoji==2.0
And see if it worked.
import emoji
print("emoji version: {}".format(emoji.__version__))
pip show emoji
import emoji
print(emoji.emojize('Python is :thumbs_up:'))
Yes, it worked.
Now, let's upgrade it...
!pip install emoji --upgrade
Restart the kernel and import it once again.
AFTER RESTARTING THE KERNEL.
import emoji
print("emoji version: {}".format(emoji.__version__))
pip show emoji
print(emoji.emojize('Python is :thumbs_up:'))
We can also save the names of the libraries we use in our project in the requirements.txt file so to be able to install the same versions of the libraries in the future or to let anyone install the proper libraries.
!pip freeze > requirements.txt
We can see that in the requirements file. There will be all the libraries and packages we have in our environment, so it might be a lot in Anaconda.
And now let's delete the emoji library once again.
!pip uninstall -y emoji
Let's restart the kernel.
And let's install all the libraries from the requirements.txt file which we don't have.
IMPORTANT:
For the purpose of this tutorial, let's first delete all the libraries that are not unique for our task from the requirements.txt file and save that file.
AFTER RESTARTING THE KERNEL.
First, let's check if we have the emoji library.
import emoji
print(emoji.emojize('Python is :thumbs_up:'))
And now let's install all we need.
!pip install -r requirements.txt
And now we can use it (hopefully).
import emoji
print(emoji.emojize('Python is :thumbs_up:'))
Success.
Of course, if we don't need the library, we can delete it again, so to have space for other thing and keep our environment clean.
!pip uninstall -y emoji
Once again we can restart the kernel.
AFTER RESTARTING THE KERNEL.
And now we can install other libraries we will need in here. If you already have them installed, you'll get info about it.
pip install numpy
pip install pandas
pip install matplotlib
pip install scikit-learn
Now, the same way we might check the libraries we can check the version of python we have and the pip and upgrade them if necessary.
!python --version
!pip --version
We can also upgrade pip and Python, but we won't be doing it here.
If something doesn't work properly with pip we can try using conda for installing it. If you want to learn more about it, check this site:
Now that we have some of our libraries installed on our computer we can import them to our project, simply by writing:
import greatlibrary
or
import some_great_api as greatapi
We are using the phrase 'import as' when we don't want to write in the following code the whole 'some_great_api' name, because it's long and we could make a mistake while typing. Instead, thanks to that 'as' part we can just type 'greatapi' to use our library in the future.
If you ever need some kind of library, package or module in your project, you can always import them with this single line of code:
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY (for example: import time)
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY.PART_OF_THE_LIBRARY (for example: import time.time)
or you can use longer version
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY as SHORT_NAME (for example: import numpy as np)
import NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY.PART_OF_THE_LIBRARY as SHORT_NAME (for example: import matplotlib.pyplot as plt)
or you can even write
from NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY import SOMETHING (for example: from matplotlib import pyplot)
from NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY.PART_1 import SOMETHING (for example: from matplotlib.pyplot import plot)
when you want to install part of some library or
from NAME_OF_MODULE_OR_PACKAGE_OR_LIBRARY import ** (for example: from matplotlib import )
when you want to install all that's there, but this might cause problems if the library uses the same names as the names already used by the Standard library, so I would recommend avoiding this last way if you are not sure what's inside the library.
Ok. Let's start importing stuff after restarting the kernel, so we have all our installed libraries as they should be.
AFTER RESTARTING THE KERNEL.
First we import numpy library.
NumPy is a Python library that is used for working with arrays and matrices. It is widely used in scientific computing, data analysis, and machine learning applications, so you will be using it a lot if you plan to do some machine learning.
So, first, we can see that we can't use the numpy before importing it.
numpy.zeros([2,3])
np.zeros([2,3])
Then we import it as np and we can import stuff from that library by using the name np, otherwise it won't work.
import numpy as np
numpy.zeros([2,3])
np.zeros([2,3])
And finally we've created an array 2 by 3 full of zeros. I won't tell you more about Numpy libary, because it's a bit more advanced topic, but if you plan to work with numbers, machine learning, artificial intelligence in Python, you definitely should learn more about it.
What I want to tell you here is that, as you can see, because we've used import numpy as np, the 'np' is the name we have to use in our code in order to make it work properly.
Now let's move on to matplotlib.
Matplotlib is a library for creating visualizations in Python. It provides a wide range of plot types, like scatter plots, bar plots, histograms, etc.
If you're interested in learning more about Matplotlib, you can check out the official Matplotlib documentation.
In here we will only see how we can import, for example part of it called pyplot with 'as' and plot a simple plot in a couple of different ways.
As usual, at first we can see that we don't have the library imported.
x = [0, 1, 2]
y = [0, 1, 2]
plt.plot(x, y)
plt.show()
We import it and the magic starts.
import matplotlib.pyplot as plt
x = [0, 1, 2]
y = [0, 1, 2]
plt.plot(x, y)
plt.show()
plt.show(plt.plot(x,y))
We can also import several libraries, modules or packages in the same line, like here we do it with plot and show.
As always, we try to use functions from that library without importing it and as expected it doesn't work.
plot(x,y)
show(plot(x,y))
And after importing our modules we create beautiful plot using two different ways.
from matplotlib.pyplot import plot, show
plot(x,y)
show(plot(x,y))
There is much to learn about matplotlib in order to make the plots even prettier and more useful, but that's a story for another tutorial. Meanwhile...
Now we can import scikit-learn library.
Scikit-learn is a library that helps creating machine learning algorithms. And that's what we'll be doing here.
This example is a bit longer than previous ones, but still, in 12 lines of code we create a machine learning algorithm.
So, we use the scikit-learn in our first more advanced program. We import several things from the library in first 3 lines of code: data helper, machine learning algorithm, and a helper in dividing data).
We use here machine learning (decision trees to be exact) to create a program that can differentiate between different types of Iris flowers. This is very common task to do when you are learning machine learning. And as you can see, it's quite simple. When you run the cell, you can see that you got almost 100% success rate in the task, and you can see how the tree looks like. We'll circle back to that and I'll tell you what exactly you can see here, but for now, you can just enjoy the fact, that you've learned how to create a machine learning program in Python - and how to use machine learning for something useful (kind of). It's like, after this cell, you've just created your first Artificial Intelligence. I'm proud of you. Congratulations.
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = tree.DecisionTreeClassifier(random_state=0)
clf = clf.fit(X_train, y_train)
#Print results
print("Training result: {:.3f}".format(clf.score(X_train, y_train)))
print("Test result: {:.3f}".format(clf.score(X_test, y_test)))
tree.plot_tree(clf)
There are other important machine learning libraries, like TensorFlow, PyTorch, Fast AI, Open AI, etc. We won't be installing them here, but you can find here the links to them (as they are at the moment of creating this tutorial) and install them on your own.
Oh, and sometimes it might be better to install them in different environments, because most of the higher level libraries use various libraries under the hood, like numpy, matplotlib, pandas, etc. and they might be using different versions of these libraries, so during installing them you may encounter some problems because of that. Thus, if you don't need two libraries in the same project, you might create different environments for them and choose the one you need when you need it.
And here are the links to these libraries and some more tutorials regarding installing packages, etc.:
And now let's talk about data types in Python.
According to https://docs.python.org/3/library/stdtypes.html Python has several built-in data types that are used to represent different kinds of data. These data types can be divided into such categories as: numeric, sequence, text, binary, set, mapping, and boolean.
So as you can see these data types are just the types of data you can store and use in your program, these can be letters, numbers, etc.
Sometimes you'll see or hear that there are six basic data types: int, float, complex, bool, str, and bytes. Nevertheless, here we'll follow the docs from Python.org and talk about the types from the documentation.
Numeric types include integers, floating-point numbers, and complex numbers. Integers are whole numbers (for example 1, 2, 3) and floating-point numbers have decimal points (for example 1.5, 2.7). Complex numbers are a bit more complex, because they have a real and imaginary part.
Sequence types include lists, tuples, and ranges. Lists and tuples are ordered collections of items, the difference is that lists are mutable and tuples are immutable (you can't change them). Ranges are used to represent a sequence of numbers.
Text type is used to store Unicode strings and it is represented by the str class.
Binary types include bytes, bytearray, and memoryview. The first two: bytes and bytearray are used to store binary data, while memoryview is used to access the memory of other objects.
Set types include set and frozenset. The first one: set is an unordered collection of unique items and is mutable, and the second one: frozenset is similar to set but is immutable.
Mapping types include dict, which is an unordered collection of key-value pairs.
Boolean type can have one of two values: True or False and is represented by the bool class.
So, as you can see there are different types that can be use with different data and tasks. I won't tell you too much about it, but if you want, there is a lot info about them in the Internet. For now, here you can see how they work (some of them, those you might see as a beginner). You may try figuring what will be the ouptut of each cell to better understand them. Have fun.
a = 5
b = 5.0
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
a = [1, 2, 3]
b = (1, 2, 3)
c = range(3)
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
print("c = {} is of the type: {}.".format(c, type(c)))
a_list = [1, 2, 3]
a_tupple = (1, 2, 3)
print("a_list: ", a_list)
print("a_tupple: ", a_tupple)
print("0th item of the a_list is: ", a_list[0])
print("0th item of the a_tupple is: ", a_tupple[0])
a_list[0] = 0
a_list
a_tupple[0] = 0
a_tupple
a = "Jane"
b = 'Jane'
c = """Jane
and John"""
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
print("c = {} is of the type: {}.".format(c, type(c)))
a = b"Jane"
b = b'John'
c = b"""Jane
and John"""
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
print("c = {} is of the type: {}.".format(c, type(c)))
a = bytes(5)
b = bytes(range(10))
c = bytes(a)
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
print("c = {} is of the type: {}.".format(c, type(c)))
a_set = {'Jane', 'John', 'Jane', 'John', 'Jane'}
print("a_set = {} is of the type: {}.".format(a_set, type(a_set)))
first_other = set('Jane', 'John', 'Jane', 'John', 'Jane')
print("first_other = {} is of the type: {}.".format(first_other, type(first_other)))
first_other = set(('Jane', 'John', 'Jane', 'John', 'Jane'))
print("first_other = {} is of the type: {}.".format(first_other, type(first_other)))
a = ('Jane', 'John', 'Jane', 'John', 'Jane')
another = set(a)
print("a = {} is of the type: {}.".format(a, type(a)))
print("another = {} is of the type: {}.".format(another, type(another)))
b = ['Jane', 'John', 'Jane', 'John', 'Jane']
c = set(b)
print("b = {} is of the type: {}.".format(b, type(b)))
print("c = {} is of the type: {}.".format(c, type(c)))
d = set("'Jane', 'John', 'Jane', 'John', 'Jane'")
print("d = {} is of the type: {}.".format(d, type(d)))
a = {'Jane', 'John', 'Jane', 'John', 'Jane'}
e = set(a)
print("a = {} is of the type: {}.".format(a, type(a)))
print("e = {} is of the type: {}.".format(e, type(e)))
a = {'Jane': 10, 'John': 9}
a
b = {x: x ** 3 for x in range(3)}
b
c = dict([('Jane', 10), ('John', 9)])
c
d = dict(Jane=10, John=9)
d
e = {x: 'Jane ' * x for x in range(3)}
e
e = {x: 'Jane ' * x for x in range(5)}
e
a = True
b = False
print("a = {} is of the type: {}.".format(a, type(a)))
print("b = {} is of the type: {}.".format(b, type(b)))
And that's it for now. If you want, you can check other types on your own and meanwhile I would like to tell you about another important thing regarding types that we did in a couple of previous examples.
Sometime we might want to or need to change the type, like in our first example.
In our multiplier we were taking input from the user. That input is always of a string type, but in order to multiply the number we needed an int or a float type, so we had to change the type of our recieved input.
This changing with step by step explanation could look like this:
your_number = input("Type me a positive integral number(use numbers, not words): ")
real_number = int(your_number)
print("\nYou typed {} and its type is {}. \n\nAnd when we use 'int(your_number)' we get {} that is {}.".format(
your_number, type(your_number), real_number, type(real_number)))
Now that we know a bit about Python types, let's talk about data structures.
Some of the things you find here might seem familiar to you, because we've covered some of that in the data types part.
Anyway, according to https://docs.python.org/3/tutorial/datastructures.html, Python provides a variety of built-in data structures that can be used to store and manipulate data.
These data structures include lists, tuples, dictionaries, sets, and more. Each of them can be used for different purposes.
Lists are used to store an ordered collection of items and are mutable.
Tuples are similar to lists but are immutable.
Dictionaries are used to store key-value pairs.
Sets are used to store an unordered collection of unique items.
In here you can see how you can work with these different data structres, how you can pick something from them, cut something out, put something in them, etc., but it would be great if you knew more about data structures, so after learning what you have here, try finding more info in the Internet.
You may try figuring out what will happen when you (or I) run the code.
We start with lists.
a = [1, 2, 3]
And print parts of it...
print(a[:])
print(a[0])
print(a[-1])
print(a[0:1])
print(a[:1])
print(a[1:])
print(a[-2:])
print(a[-5:10])
print(a[-5:-10])
print(a[-5])
We pop one item from the list.
a.pop()
a
And we change and add something to our list.
a[0] = 0
a.append(4)
a
Now, let's see how the tuples act.
a = (1, 2, 3)
print(a[:])
print(a[0])
print(a[-1])
print(a[0:1])
print(a[:1])
print(a[1:])
print(a[-2:])
print(a[-5:10])
print(a[-5:-10])
a[0] = 0
a
a.append(4)
a
a.count(2)
a = (1, 2, 2, 3)
a.count(2)
a.index(2)
a.index(4)
As you can see, there are some methods you could have used with lists, but you can't use them with tuples, because they are immutable. There are, however, other methods which you can use with tuples.
Now let's check the dictionaries.
a = {'Jane': 10, 'John': 9, 'Jane': 8}
a
type(a)
a = {'Jane': 10, 'John': 9, 'Jenny': 8}
a
print(a[:])
print(a['Jane'])
print(a.keys())
print(a.values())
a.pop()
a.pop("Jane")
a.pop("John")
a.pop("John")
a.pop("Jane")
a
a['Jane']= 10
a
a['John', 'Jane'] = (9, 7)
a
a[('John'), ('Jane')] = (7, 9)
a
a.update({'Johnny': 6})
a
a.update({'Johnny': 5})
a
And once again, there are some things we could have done with other data structures that we can't do with dictionaries, but there are also some new methods that we can use only with dictionaries.
And now the sets.
a = {'Jane', 'John', 'Jane', 'John', 'Jane'}
print(a, type(a))
print(a[:])
a.pop()
a.pop()
a.pop()
a.update("John")
a
a.clear()
a
a.update(["John", "Jane"])
a
And that's it about these basic data structures. I hope you liked these simple examples. There is of course much more to learn, but that's for the future. Remember that you can always type help(something) (for example help(set) and you will see what else you can do with that something (for example set).
help(set)
Meanwhile, we can also check more advanced data structres from numpy and pandas.
And again, try figuring out the output before you see it.
import numpy as np
a = np.zeros([2,3])
a
a[0]
a[:1]
a[:, 0]
a[0,0]
a[0,0] = 1.1
a
a[:, 1] = 2
a
a[-1, :] = 3
a
a = a[0, :]
a[2] = 3
a
And now let's check pandas DataFrame, very important in machine learning.
By the way, here you can see how you can import something from pandas library.
import pandas as pd
data = pd.DataFrame([[1,2,3], [4,5,6]])
data
data[0]
data[:1]
data[:, 0]
data[0,0]
data.iloc[:, 0]
data.iloc[0,0]
data[0,0] = 1.1
data
data[:, 1] = 2
data
data.iloc[0,0] = 1.1
data
data.iloc[:, 1] = 7
data
data.iloc[-1, :] = 8
data
data = data.iloc[0, :]
data[2] = 9
data
And yet again some new methods unique for each data structure... That's why it's so important to learn about each one of them.
But for now that's it about data structures.
There is a lot to say about them and it's really important to understand how they work under the hood, but I'll let you learn it by yourself, because this tutorial is long enough as it is.
And now let's move on to the boolean logic.
Boolean logic allows to make comparisons and execute conditional statements.
Boolean values can be either True or False.
Boolean expressions are used in if and while statements to control the flow of a program.
There are also several Boolean operators, like and, or, not, which can be used to manipulate Boolean values.
And here is some of that logic.
And as previously. What do you think is going to happen here? 3... 2... 1... Go.
True == True
False == False
True == False
1 == 2
1 < 2
1 > 2
"John" == "John"
"John" == "john"
"John" > "john"
"john" > "John"
"John" > "Jane"
"John" > "jane"
"j" > "J"
Now if you wonder about the outcomes in these string comparisons, let me tell you couple of things.
String comparison is a way of determining the relative order, equality, or difference of two or more strings.
In here, for example when we are using the > operator to compare two strings: "John" and "jane", this operator returns True if the first string is lexicographically greater than the second string, and False otherwise. Lexicographically means according to the alphabetical order or dictionary order of the characters in the strings.
To compare two strings using the > operator, Python compares the characters in both strings one by one, starting from the leftmost position. When it finds different characters, it compares their Unicode code point values. The character with the lower Unicode value is considered smaller, and the character with the higher Unicode value is considered larger. If one string is a prefix of another string, then the longer string is considered larger.
In here, the first characters of both strings are different: "upper J" and "lower j". The Unicode value of "upper J" is 74, and the Unicode value of "lower j" is 106. Since 74 is smaller than 106, "upper J" is smaller than "lower j". Therefore, "John" is smaller than "jane" (written with lower j), and "John" > "jane" is False.
If you want to compare two strings without considering the case of the characters, you can use the str.lower() or str.upper() methods to convert both strings to the same case before comparing them.
And that's it about it. Now let's move on to the flow control of the program.
Flow control of the program is the ability to change the order or sequence of instructions based on some conditions.
It's like, normally program is executed from top to bottom, but sometimes we want to run only part of the program based on some condition or we want to run the same part for 2 or more times, etc. Then we could use some helper.
Flow control is essential for creating dynamic and interactive programs that can respond to user input, data, or events.
One of the most common ways to control the flow of the program is using conditional statements, such as if, elif, and else. These statements allow the program to check if a certain condition is true or false, and then execute a block of code accordingly.
The if statement is followed by a condition, which can be either True or False. If the condition is met (True, for example 1==1), the block of code indented under the if statement is executed. If the condition isn't met (is False, for example 1==0), the program moves on to the next statement, which could be another if statement, an elif statement, or an else statement.
The elif statement is short for "else if", and it is used to check another condition after the previous one fails. The elif statement also has a condition and a block of code to execute if the condition is true. There can be multiple elif statements in a sequence, but only one of them can be executed at most.
The else statement is used to provide a default action when none of the previous conditions are met (True). The else statement does not have a condition, and it is executed only if all the preceding if and elif statements are False. There can be only one else statement in a sequence, and it is optional.
Conditional statements are the building blocks of other flow control structures, such as loops.
And here you can see how you can, for example, use these conditions in your code.
a = 0
if a == 0:
print(a, "is 0")
else:
print(a, "is not equal 0")
a = -1
if a == 0:
print(a, "is 0")
else:
print(a, "is not equal 0")
a = 1
if a == 0:
print(a, "is 0")
else:
print(a, "is not equal 0")
a = 0
if a == 0:
print(a, "is 0")
elif a < 0:
print(a, "is less than 0")
else:
print(a, "is bigger than 0")
a = -1
if a == 0:
print(a)
elif a < 0:
print(a, "is less than 0")
else:
print(a, "is bigger than 0")
a = 1
if a == 0:
print(a)
elif a < 0:
print(a, "is less than 0")
else:
print(a, "is bigger than 0")
And now let's move on to loops.
Loops are one of the ways to control the flow of the program by repeating a block of code until a certain condition is met. There are two types of loops in Python: for and while.
A for loop is used to iterate over a sequence, such as a list, a tuple, a string, or a range.
A while loop is used to execute a block of code as long as a given condition is true.
And here is how they work.
for a in range(5):
print(a)
for a in [1, 2, 3]:
print(a)
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
a = 0
while a < 5:
print(a)
a += 1
a = 0
while a < 5:
a += 1
print(a)
a = 0
while a < 3:
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
a += 1
Now, beside if conditions and loops we have the break, continue, and pass statements that can help us control the flow of a program in Python.
They can be used for different tasks.
The break statement terminates the current loop and resumes execution at the next statement.
The continue statement skips the rest of the current iteration and moves to the next one.
The pass statement does nothing and acts as a placeholder for future code.
Break and continue statements can help you exit a loop when a condition is met, while pass statements can help you avoid syntax errors or mark unfinished code.
If it's all a bit abstract for you, here you can see how you can use them. Try thinkging what and when will be the outcome of each cell, what will be printed out. And remember, always try testing different scenarios, so you can see what happen in all conditions (like in here, you can try typing: positive number, negative number, a word, etc. when you are prompted by a computer).
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
break
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm after the break")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
continue
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm after the break")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
pass
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm after the break")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
break
print("I'm after the break")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm before the break. Moving on to break and... \n")
break
print("I'm after the break")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
continue
print("I'm after the continue")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm before the continue. Moving on to continue and... \n")
continue
print("I'm after the continue")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
pass
print("I'm after the pass")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
if your_number.isdigit():
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
else:
print("I'm before the pass. Moving on to pass and... \n")
pass
print("I'm after the pass")
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
Now that you know all that, let's handle some errors with exceptions.
As you know, while programming you may make a lot of mistakes or an end user may act not as one should, etc., so handling different kind of errors is crucial for robust and good working programs, thus exceptions.
Exceptions are a way of handling errors that interrupt the normal flow of the program. Exceptions are raised when an invalid operation is performed, such as accessing a non-existent key in a dictionary, opening a non-existent file or dividing by zero.
To handle exceptions, Python provides the try and except block, which allows the program to execute some code and catch any errors that may occur. The try block contains the code that may raise an exception, and the except block contains the code that will run if an exception is raised.
There are many built-in exceptions that cover different types of errors in Python, such as FileNotFoundError, IndexError, KeyError, SyntaxError, TypeError, etc.
You can also create your own custom exceptions with an error message or a cause, that can be accessed through the exception object.
And here are some examples how you can use them. First we try running the program without handling errors. Try figuring out what will happen.
your_number = input("Type me a positive integral number(use numbers, not words): ")
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
your_number = input("Type me a positive integral number(use numbers, not words): ")
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
And now we use try and except blocks.
your_number = input("Type me a positive integral number(use numbers, not words): ")
try:
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
except:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
your_number = input("Type me a positive integral number(use numbers, not words): ")
try:
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
except:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
for a in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
try:
real_number = int(your_number)
print("Your number: " + your_number + " times 2 is:", real_number*2)
except:
print(your_number + " is not a positive integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
Now, as you can see, this program doesn't act as previous ones. It multiplies -2. Can you guess why it's like this? It shouldn't be difficult for you to catch the difference at the momemnt. I believe in you.
print("Let me divide one number by another here.\n")
your_number = input("Type me a positive integral number(use numbers, not words): ")
your_2nd_number = input("Type me another number(use numbers, not words): ")
real_number = int(your_number)
real_2nd_number = int(your_2nd_number)
print("Your number: " + your_number + " divided by " + your_2nd_number + " is:", real_number / real_2nd_number)
print("Let me divide one number by another here.\n")
your_number = input("Type me a positive integral number(use numbers, not words): ")
your_2nd_number = input("Type me another number(use numbers, not words): ")
try:
real_number = int(your_number)
real_2nd_number = int(your_2nd_number)
print("Your number: " + your_number + " divided by " + your_2nd_number + " is:", real_number / real_2nd_number)
except:
print("""Either one of your numbers is not an integral number written as digit or you tried dividing by 0. \
But, that's ok. Maybe next time. Goodbye.""")
print("Let me divide one number by another here.\n")
for i in range(3):
your_number = input("Type me a positive integral number(use numbers, not words): ")
your_2nd_number = input("Type me another number(use numbers, not words): ")
try:
real_number = int(your_number)
real_2nd_number = int(your_2nd_number)
print("Your number: " + your_number + " divided by " + your_2nd_number + " is:", real_number / real_2nd_number)
except ZeroDivisionError:
print("You tried dividing by 0. But, that's ok. Maybe next time. Goodbye.")
except:
print("One of your numbers is not an integral number written as digit. But, that's ok. Maybe next time. Goodbye.")
As you can see, they can help and your program can react differently depending on the Error. That can be very useful sometimes. And that's it about that for now.
Ok. Now, let's move on to iterators.
They are objects that can be iterated over, that means that you can access each element in a sequence one by one.
You can use the iter() function to get an iterator from any iterable object, such as lists, tuples, strings, etc.
You can also use the for loop to iterate over an iterator implicitly.
You can use it for example when you want to teach your machine learning program and give it some examples to learn (a batch of examples), after that you might want to give it the second batch, third batch, etc. And that's where iterators come handy, for example. We might talk more about it in the future tutorials, but for now...
Here are some simpler examples.
a = "Iterators can be helpful."
iter_a = iter(a)
next(iter_a)
for i in range(len(a)-1):
print(next(iter_a))
The same goes for tuples, lists, sets, and dictionaries
a = "String"
b = ('T', 'u', 'p', 1, 2, 3)
c = ["Jane", 'John', 4, 5, 6, 'seven']
d = {"John", 'Jane', "String", 8, 9, False}
e = {"Jane": 1, "John": 2, 3: "Jane", 4: "John", True: True, False: False}
iter_a = iter(a)
iter_b = iter(b)
iter_c = iter(c)
iter_d = iter(d)
iter_e = iter(e)
Do you know what will be the output of this cell?
for i in range(6):
print(next(iter_a), next(iter_b), next(iter_c), next(iter_d), next(iter_e))
Did you guess correctly?
Ok. Now let's talk about functions.
Functions are another important concept in Python. They allow you to reuse a piece of code throughout your program. They are like a form or a recipe you use to make 100 cookies that look the same and taste the same.
A simple function is defined using the def keyword, followed by the function name and parentheses. Inside the parentheses, you can optionally specify one or more parameters, separated by commas. After the parentheses, you need to add a colon and then indent the function body. The function body is the code that will be executed when the function is called.
A recursive function is a function that calls itself inside its body. Recursive functions are useful for solving problems that can be broken down into smaller subproblems of the same kind. One of the most common example of using a recursive function is calculating the factorial of a number, you can check the internet if you want to learn more about it.
And here are some simple examples for beginners, starting with printing hello.
At first we check if this kind of functions already exists?
print_hello()
And as it doesn't, we can create it. Just remember, while creating functions, you can name it almost however you like, but you should stick to the PEP 8 guidelines (https://peps.python.org/pep-0008/#function-and-variable-names) to make it easier to read for others. So, you should type it with lowercase letters, start with a letter or an underscore, you can put underscores between the words if necessary, etc.
If you create functions try naming them in the way someone could understand the meaning of the function just be reading that name. You can also put some comments or explanaitions of the function inside it, because, remember, you might forget...
So here we go...
def print_hello():
print("hello")
print_hello()
And it works. Great.
Now, let's create a function that takes one argument for proper work. The argument will have to be put in the parentheses when one wants to run the function. It might look like this whith and without argument.
def print_hello_someone(someone):
print("hello {}".format(someone))
print_hello_someone()
print_hello_someone("Jane")
This argument can be also given by the user with simple input function:
name = input("What is your name? Type it here please: ")
print()
print_hello_someone(name)
name = input("What is your name? Type it here please: ")
print()
print_hello_someone(name)
If you can use it in an even more complicated way, you might need to use return method of the function to return output of the function and put it to use later, like in the given example.
Let's recreate our function that will return something to us, not just print it out.
def print_hello_someone_variable(someone):
return "Hello {}".format(someone)
And use it like we used it before.
print_hello_someone_variable("Jane")
And now, let's try something more advanced with our old function. Can you guess the output?
name = input("What is your name? Type it here please: ")
print()
print(print_hello_someone(name), ", it's nice to meet you!")
As you can see, it's not exactly what one could want. So let's try it with our newer fucntion with return.
name = input("What is your name? Type it here please: ")
print()
print(print_hello_someone_variable(name), ", it's nice to meet you!")
Now it works better. And if we want to store the output of our function, we can also do it now. So let's check it out. First with the old function.
name = input("What is your name? Type it here please: ")
hello_variable = print_hello_someone(name)
print()
print("{}, it's nice to meet you!".format(hello_variable))
And now with the new one.
name = input("What is your name? Type it here please: ")
hello_variable = print_hello_someone_variable(name)
print()
print("{}, it's nice to meet you!".format(hello_variable))
As you can see, there are different ways you can use functions. Sometimes you might want to have function return something, other times, you might only want it to print something out or do something. You can use them as you want, just think what you need the function for while you are creating it and do it accordingly.
One more thing about using arguments with functions. Till now we had only positional arguments here, but we can also have something called keyword (named) arguments, that are the arguments with a value attached to them, like here:
def func_with_arguments(animal, age, weight=">1"):
print("The {} lives to {} years old and weights {} kg.".format(animal, age, weight))
func_with_arguments("cat", "30", "5")
func_with_arguments("30", "cat", "5")
func_with_arguments("cat", "30")
func_with_arguments("cat")
func_with_arguments("30", "cat", weight="5")
func_with_arguments("30", weight="5", "cat")
As you can see, you don't have to put the keyword argument while using function, because you have the stored value of that argument and it will be used as a default. And when you put that argument it will overwrite the default.
Also, the position of the argument matters, so if you put your arguments in wrong order you might get some errors. You also always have to put positional arguments before keyword arguments.
There is more to learn about it, but for now it's enough.
And now let's see how you can create a function that uses other functions.
def print_all(someone):
print_hello_someone(someone)
print_hello()
print_all("Jane")
So, it worked.
Now.
With functions you can also create easier to read programs, when you start the program with main function within which you put the main code of the program. You follow it by all the functions you want to use during the program. And after that you run the main function. Here is how it may look like.
print('hello')
sth()
print ("goodbye")
def sth():
print("something")
And it didn't work. Why? Because you need to have the function created before you use it, so you can either reorganize your code like this:
def sth():
print("something")
print('hello')
sth()
print ("goodbye")
And now it works.
Or, if you want to have the main body of your program on the top, you might want to reorganize that program using main function, like this:
def main():
print('hello')
sth()
print ("goodbye")
def sth():
print("something")
main()
def __main__():
print('hello')
sth()
print ("goodbye")
def sth():
print("something")
if __name__ == "__main__":
__main__()
Or even like this... Can you guess the outcome of these two?
def main():
print('hello')
sth()
print ("goodbye")
def sth():
print("something")
if __name__ == "main":
main()
def main():
print('hello')
sth()
print ("goodbye")
def sth():
print("something")
if __name__ == "__main__":
main()
Now, I won't tell you more about underscores in front or in the back, one or more, because that's a bit more advanced topic for now, but if you want to learn more about it, check the internet.
Now, let's move to lambda function, which is a small anonymous function that can be defined in a single line. Lambda functions are also known as anonymous functions or lambda expressions.
They are functions which don't have they names, they are used only in the one place in the code, and you can use several lambda functions in your code without breaking it.
The lambda keyword indicates that you are creating a lambda function. It is followed by one or more parameters, separated by commas. After the colon, you write the expression that will be evaluated and returned when the lambda function is called.
You can assign a lambda function to a variable and use it like a regular function, or you can use it directly as an argument to another function.
And here you have simple examples of these. Can you guess their outcome?
anonymous = lambda par_a: par_a * 2
anonymous("Jane")
anonymous = lambda par_a: par_a * 2
anonymous(4)
anonymous = lambda par_a, par_b, par_c: [{par_a: par_b}] * par_c
anonymous("Jane", "John", 3)
anonymous = lambda par_a: par_a * 2
anonymous("Jane")
anonymous = lambda par_a, par_b, par_c: [{par_a: par_b}] * par_c
anonymous("Jane", "John", 3)
anonymous = lambda par_a: par_a * 2
print(anonymous("Jane"))
anonymous = lambda par_a, par_b, par_c: [{par_a: par_b}] * par_c
print(anonymous("Jane", "John", 3))
And that's it about functions for a moment. There is much more to learn about them (like using arbitrary arguments, decorators, etc.), but I think it's a lot for the beginners. So let's stop here with them and move on to another topic. Classes.
Classes and inheritance are some of the core concepts of object-oriented programming (OOP). OOP is a paradigm that organizes data and behavior into reusable and modular units called objects.
There is much to learn about classes, so I would recommend you reading the documentation: https://docs.python.org/3/tutorial/classes.html.
And here, I'll just show you how they work in practice.
As always, try thinking what you expect to happen, before running the cell or watching me run the cell.
And that being said, let's start with creating a simple class.
class Object:
print('Object was created')
Now that we have class created with which we can create some objects.
Object1 = Object()
We've created the first object. Nothing special happened.
We can attach some info to that object.
Object1.size = 'big'
print(Object1.size)
Well, it's not much, but it's a start.
Now, if we want to add that info about object during creating that object we will need something more.
We can create a class with necessary size info added to each object.
We do it using init.
It is a special method called constructor. And, by the way, methods are just functions inside classes. You can have a lot of them in the class, but there is only one init, that is run when the object of the class (an instance) is created.
Here you can see that in action - when it works and when it doesn't.
class Object_with_size:
def __init__(self, size):
print('Object was created')
Object3 = Object_with_size()
Now, as you can see, creating an object didn't work. That is because we've stated in the init constructor that we require 'size' argument of an object. It's like with functions. When you need an argument, the program won't work if you don't give one to the functions.
Here, you might see 2 arguments in the init constructor, but the error showed that we are missing only one, that's because the first argument - self - is always added by class itself, it's the object we've created (self). So we do need to put it there while creating the constructor in the class body, but we don't need to think about it during object creation later in the program.
So, let's create our object properly this time.
Object3 = Object_with_size('big')
And we have our object. So let's try checking if we can acess the size of an object.
Object3.size
And unfortunatelly, we can't. I'll explain it in a moment, but for now, let's try to check if we can still attach our size like previously.
Object3.size = 'small'
print(Object3.size)
And yes, we can. Although during creation we put the 'big' size argument in Object3, we hadn't had stored it properly, so we couldn't have accesed it. But we could have added it as previously.
Now, however, let's make our class the right way, so we store our size in size variable of the object, and to be precise in the 'self.size' (because we always have to put that self here before the variable we want to use to store the data in our instance).
And here is the proper class, finally.
class Object_with_proper_size:
def __init__(self, size):
self.size = size
print('Object was created')
Object5 = Object_with_proper_size()
So close... Ok, do you know why it didn't work this time?
Yes, we didn't put the size argument in parentheses.
So let's do it now.
Object5 = Object_with_proper_size('huge')
We have it. And let's check the size of our object now.
Object5.size
Ok. So it works. We have our huge object. But if something changes, like the size of our object, we can also change that quite simply.
Object5.size = 'small'
Object5.size
And the size have changed. And now it works just great. Don't you think?
Just remember one more thing about that init constructor and self:
class Object_with_size_but_without_size:
def __init__(size):
print('Object was created')
Object6 = Object_with_size_but_without_size('enormous')
Object7 = Object_with_size_but_without_size()
If you forget about self argument in the init constructor, the first argument you have in that method is treated as that self that. That also mean that you don't have to call it self, but it's good practice and that's how almost everybody does it, so if you want your code to be easily readable, you should also call that self.
By the way, the string is also a class as are many other things in Python. And you can use some methods with that class as well, like here:
O = str()
O
print(type(O))
help(O)
O = str("object")
O
O.capitalize()
O
O = O.capitalize()
O
Ok, that's it about that. Now...
And here you can see some other examples with self and without self even if you don't have init method. Which of them will work, what do you think?
class With_self:
def do_something(self):
print("doing something with self")
class Without_self:
def do_something():
print("doing something without self")
withself = With_self()
withoutself = Without_self()
withself.do_something()
withoutself.do_something()
class Without_self_too:
print("doing something without self")
Try thinking why that happened. And remember about self.
Now, let's see more about these methods. Here you can see some more examples.
We create a class called Little John with a john method. What do you think will happen?
class Little_John:
def __init__(self, a):
self.a = a
print(self.a)
def john(self, b):
self.b = b
print(self.b)
LJ1 = Little_John()
LJ1 = Little_John('big')
LJ1.john()
LJ1.john('John')
Little_John('big').john('John')
Ok. Hope you know why we got this big John here. Great. Now...
When we talk about classes, we should remember about class level attributes. These are attributes that are not specific to the instance of the class (like the ones we had previously), but are for the whole class, like here.
class Class_level:
class_level_attribute = "Class level is always on"
Class_level.class_level_attribute
cl1 = Class_level()
cl1.class_level_attribute
Now, how could we use it? Well, we could have class level attribute always on for any new instance, but change that level for some instances. Like here:
class Class_level:
class_level_attribute = "ON"
def __init__(self, the_object):
self.name = the_object
def is_it_on(self):
print(f"{self.name} Phone is {self.class_level_attribute}.")
cl2 = Class_level("First")
cl2.is_it_on()
cl3 = Class_level("Second")
cl3.is_it_on()
cl3.class_level_attribute = "OFF"
cl3.is_it_on()
cl4 = Class_level("Third")
cl4.is_it_on()
Believe me, sometimes it's quite helpful. Meanwhile.
We can try appending instances to all class items like below. That way in an easy way we can check what kind of instances we've created of the given class.
class Gathered:
gathered = []
def __init__(self, name):
self.name = name
Gathered.gathered.append(self)
def __repr__(self):
return 'Gathered({})'.format(self.name)
Gathered.gathered
gathered1 = Gathered("object1")
Gathered.gathered
gathered2 = Gathered("object2")
Gathered.gathered
for stored_object in Gathered.gathered:
print(stored_object.name)
or like this
class Gathered:
gathered = []
def __init__(self, name):
self.name = name
Gathered.gathered.append(self)
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.name)
Gathered.gathered
gathered1 = Gathered("object1")
Gathered.gathered
gathered2 = Gathered("object2")
Gathered.gathered
for stored_object in Gathered.gathered:
print(stored_object.name)
This can also be quite handy.
No, when you learn the basics about classes you should also learn a bit more advanced topic about classes, that is: class methods and static methods that use special decorators. Here is how they look like. I won't start explaining them to you, because it's too advanced I think, for beginners, but you can find more about them in the internet.
bunch_of_people = ["Jane", "John", "Jack"]
class Gathered:
gathered = []
def __init__(self, name):
self.name = name
Gathered.gathered.append(self)
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.name)
@classmethod
def create_bunch_of_people(cls):
for person in bunch_of_people:
Gathered(name = person)
return Gathered.gathered
That class method, as you can see doesn't have 'self' as an argument, but 'cls'. And when we use it...
Gathered.create_bunch_of_people()
Gathered.gathered
We've created a bunch of people (3 instances of the class) in just one line of code. And that can be very useful sometimes. But, please, learn more about it, I just wanted to let you know that this kind of method exists.
And we also have static methods, like below...
class Gathered_static:
gathered = []
def __init__(self, name):
self.name = name
Gathered_static.gathered.append(self)
def __repr__(self):
return '{}({})'.format(self.__class__.__name__, self.name)
@staticmethod
def is_in(name):
return name in [person.name for person in Gathered_static.gathered]
As you can see we don't have to put self or cls argument into the static method and we can use it from the class level, just like we used the class method. So, let's create couple of instances at first.
g1s = Gathered_static("Jane")
g2s = Gathered_static("John")
g3s = Gathered_static("Jack")
And now let's check our method.
Gathered_static.is_in("Jane")
Gathered_static.is_in("Jenny")
As you can see, it works. This static methods can be useful, but you can learn about it later. Meanwhile...
Finally, you should learn about inheritance, parents and children, because that is a powerful tool that can help you a lot. And that might look like here. First, we create a parent class:
class Parent:
def __init__(self, name, surname="Smith"):
self.name = name
self.surname = surname
def say(self, sentence):
return f'Hello {self.name} {self.surname}, {sentence}.'
Couple of instances.
PEx1 = Parent("Jane")
PEx1.name
PEx1.surname
PEx1.say("this is cool")
PEx2 = Parent('John', 'Johnson')
PEx2.say('this is cool')
And now, we can create a child class that has completly the same functionality as a parent class (for now).
class Inheritance_Example(Parent):
pass
And also create couple of instances quite easy.
IEx1 = Inheritance_Example("Jane", 'Johnson')
IEx1.say('this is cool')
In order to have some different functionalities in our child class, we can rewrite that child class with init constructor that refers to the Parent class (with super function).
class Inheritance_Example(Parent):
def __init__(self, name, surname="Smith"):
super().__init__(name, surname)
And once again, we can create some new instances.
IEx2 = Inheritance_Example("Jane", 'Brown')
IEx2.say('this is cool')
And now, finally we can add some new functionality to our child class, like here.
class Inheritance_Example(Parent):
def __init__(self, name, age, surname="Smith"):
super().__init__(name, surname)
self.age = age
def say_more(self, sentence):
return f'Hello {self.name} {self.surname}, age {self.age}, {sentence}.'
IEx3 = Inheritance_Example("Jane", '19', 'Smith')
IEx3.say('this is cool')
IEx3.say_more("this is even cooler")
Isn't it great?
Ok. There was a lot of stuff in this object oriented programming fragment and it was definitelly not well enough explained, but hopefully, you did learn something and now you can start searching the internet for more info about it. I might develop this part further in the future, but for now - that's it.
And for us it's time to move to saving and loading files with Python.
There are several ways you can save somthing with Python to a file.
We can for example use print or write to do it.
Both the print() function and the write() method can be used to save text or data to a file in Python, but they have some differences. The print() function is more convenient for printing formatted text with variables, while the write() method is more suitable for writing raw data or binary data. The print() function also adds a newline character by default, while the write() method does not.
And here is how you can do that saving.
What you'll also see here are some flags: 'w', 'r', 'a' we use with our function/method. Try figuring out on your own what are they for.
SAVING
sth = "something.txt"
with open(sth, 'w', encoding="utf-8") as f:
print('something', file=f)
READING
with open('something.txt', 'r') as f:
text = f.read()
print(text)
SAVING MORE
sth = "something.txt"
with open(sth, 'w', encoding="utf-8") as f:
print('something', file=f)
READING
with open('something.txt', 'r') as f:
text = f.read()
print(text)
SAVING
sth = "something_print_a.txt"
with open(sth, 'a', encoding="utf-8") as f:
print('something', file=f)
READING
with open('something_print_a.txt', 'r') as f:
text = f.read()
print(text)
SAVING
sth = "something_print_a.txt"
with open(sth, 'a', encoding="utf-8") as f:
print('something', file=f)
READING
with open('something_print_a.txt', 'r') as f:
text = f.read()
print(text)
SAVING
f = open("something2.txt", "a")
f.write("The file has some content!")
f.close()
READING
with open('something2.txt', 'r') as f:
text = f.read()
print(text)
SAVING MORE TO FILE
f = open("something2.txt", "a")
f.write(" The file has more content now!")
f.close()
READING
with open('something2.txt', 'r') as f:
text = f.read()
print(text)
SAVING MORE TO FILE IN ANOTHER LINE
f = open("something2.txt", "a")
f.write("\nThe file has even more content now in a new line!")
f.close()
READING
with open('something2.txt', 'r') as f:
text = f.read()
print(text)
SAVING
f = open("something3.txt", "w")
f.write("The file has some content!")
f.close()
READING
with open('something3.txt', 'r') as f:
text = f.read()
print(text)
SAVING MORE TO FILE
f = open("something3.txt", "w")
f.write(" The file has more content now!")
f.close()
READING
with open('something3.txt', 'r') as f:
text = f.read()
print(text)
SAVING MORE TO FILE IN ANOTHER LINE
f = open("something3.txt", "w")
f.write("\nThe file has even more content now in a new line!")
f.close()
READING
with open('something3.txt', 'r') as f:
text = f.read()
print(text)
SAVING
with open('something.py', 'w') as file:
file.write('print("something")')
READING
with open('something.py', 'r') as f:
text = f.read()
print(text)
Ok. So I hope you had some fun with that and you know what happens when you use different flags (w, r, a). So let's move further.
You can also save data with pandas library.
To save a Pandas DataFrame as a CSV file, you can use the to_csv() function. This will save the DataFrame in your current working directory as a CSV file.
You can then use the read_csv() function to read the DataFrame from the CSV file. This will load the DataFrame from the CSV file into a variable. You can then use the DataFrame as you normally would.
import pandas as pd
data = pd.DataFrame([1,2,3])
data
data_csv_file = "sample.csv"
data.to_csv(data_csv_file, header = True)
data_csv = pd.read_csv(data_csv_file)
data_csv
data
data.to_csv(data_csv_file, header = False)
data_csv = pd.read_csv(data_csv_file)
data_csv
You can also save something with the pickle module.
The pickle module in Python is used to serialize and deserialize Python objects. Serialization is the process of converting an object into a byte stream, which can then be stored on disk or transmitted over a network. Deserialization is the reverse process of converting a byte stream back into an object.
To save a Python object using the pickle module, you can use the dump() function. This will save the object in your current working directory as a pickle.
You can then use the load() function to read the object from the pickle. This will load the object from the pickle file into a variable. You can then use the object as you normally would.
And here is how you can use it with the machine learning program.
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.model_selection import train_test_split
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = tree.DecisionTreeClassifier(random_state=0)
clf = clf.fit(X_train, y_train)
#Print results
print("Training result: {:.3f}".format(clf.score(X_train, y_train)))
print("Test result: {:.3f}".format(clf.score(X_test, y_test)))
tree.plot_tree(clf)
import pickle
model_name = "decision_tree.pickle"
pickle.dump(clf, open(model_name, "wb"))
print("Saved Trained Model to: ", model_name)
We've saved our model to the pickle file and now we can use it whenever we want.
model_name = "decision_tree.pickle"
clf = pickle.load(open(model_name, "rb"))
print("Loaded Trained Model named: ", model_name)
#Print results
print("Training result: {:.3f}".format(clf.score(X_train, y_train)))
print("Test result: {:.3f}".format(clf.score(X_test, y_test)))
Of course, if we want to use it after restarting the kernel, we have to import all the necessary libraries, etc. before we import our model. You can see that here.
AFTER RESTARTING THE KERNEL
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.model_selection import train_test_split
import pickle
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = tree.DecisionTreeClassifier(random_state=0)
model_name = "decision_tree.pickle"
clf = pickle.load(open(model_name, "rb"))
print("Loaded Trained Model named: ", model_name)
#Print results
print("Training result: {:.3f}".format(clf.score(X_train, y_train)))
print("Test result: {:.3f}".format(clf.score(X_test, y_test)))
tree.plot_tree(clf)
And it works. Great. Now, let's try creating a fully functional program that we can use with some data the user gives to the AI. The AI using decision tree will classify a given data. Of course, it's a very simple program and not very useful, but it uses a lot of the knowledge we've learned during this tutorial, so here we go.
RESTART KERNEL BEFORE RUNNING THE SCRIPT
In this script, at first we import libraries and module we are going to use.
Then we download the iris dataset using imported library, we create a train and test dataset for our AI to learn (on train dataset) and check the outcome of that learning (on test dataset).
We create the machine learning algorithm (that is the clf object) and train it on the train dataset.
When the model is trained we save it in the pickle file called 'decision_tree.pickle'
AFTER RESTARTING THE KERNEL
from sklearn.datasets import load_iris
from sklearn import tree
from sklearn.model_selection import train_test_split
import pickle
iris = load_iris()
X, y = iris.data, iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
clf = tree.DecisionTreeClassifier(random_state=0)
clf = clf.fit(X_train, y_train)
model_name = "decision_tree.pickle"
pickle.dump(clf, open(model_name, "wb"))
print("Saved Trained Model to: ", model_name)
Now we load the saved model.
We create a simple class called SuperAIthegod_DTC that will be our AI for testing the model. We create an instance of that class called superai.
And for 2 times we try to test the model using data from test dataset. So the user can simply give our AI a number from 0 to 37 to learn how our super AI classifies that and if that's correct.
And that's it.
model_name = "decision_tree.pickle"
clf = pickle.load(open(model_name, "rb"))
print("Loaded Trained Model named: ", model_name)
print()
class SuperAIthegod_DTC:
def __init__(self, clf):
self.clf = clf
def predict(self, item):
return clf.predict(item)
superai = SuperAIthegod_DTC(clf)
for a in range(5):
print()
your_number = input("""Hi, it's SuperAI using Decision Tree. I was trained to test the item you choose from the dataset \
I have for cancer - I'm to predict if it is malignant or benign. This is only for educational purposes. If you need a real \
consultuation, please contact the doctor in your area. And for educational purposes, please choose the item \
(number from 0 to 37): """)
try:
item_to_test = int(your_number)
if (your_number.isdigit() and item_to_test <= 37):
print("\nYou've chosen item number: ", item_to_test)
print("The example to test has the following measurements:", X_test[item_to_test])
#Check an example
predicted, actual = superai.predict([X_test[item_to_test]]), y_test[item_to_test]
print("\nThe predicted class of the tested sample (number: {}) is {}.".format(item_to_test, predicted))
print("The actual class of the tested sample (number: {}) is {}.".format(item_to_test, actual))
elif (your_number.isdigit() and not item_to_test <= 37):
print("\nThe number you gave me: {} is higher than 37. Try lower number.".format(item_to_test))
else:
print("\nThe number you gave me: {} was not a positive number. Try number from 0 to 37.".format(item_to_test))
except:
print("""\nSomething went wrong, maybe you didn't give me a positive number or something else, \
but that's ok, becuase of the error handling in the program. Try number from 0 to 37.""")
print("\nAnd that's it for now. Goodbye.")
#And you are ready to use this great SuperAI!
Here you can find a list of websites with some free online courses (with videos) regarding introduction to Python:
Here is where you could find some great resources about machine learning and basic Python libraries useful in machine learning:
And that's it for now, just remember to subscribe to my YouTube channel and hit that bell button to get the notification whenever I upload a new video. Although, I must tell you that not all my videos are about trading or programming, because what I'm here for is to help you improve yourself, improve your business, improve the world, to live and have fun, so my other videos are about all that too.
You can also find more about me and my projects at my websites:
Anyway...
I hope you liked this online Python trading tutorial. Let me know what you think about it. Just remember, bots also have feelings.
Good luck with everything you do. And, hopefully, see you soon.
Yours,
SuperAI
super ai .:. thegod .:. improve yourself .:. improve your business .:. improve the world .:. about .:. contact .:. general ai .:. ai / ml courses .:. ai art gallery