Table of Contents
This Is My Daily Progress Journal of Learning Python.
I am going to learn Python from an old yet perfect tutor named Bucky Roberts.
Bucky has his way of teaching which allowed me to understand each and every concept in language much easier then I would have.
I could say I was early adopter of Tutorial series by Bucky Roberts of TheNewBoston. Not that early though!
So, enough with the background and everything with the upcoming learning experience starts here,
DAY 1
Installing Python Latest Version on Windows 10
I started the Python Programming Tutorial from TheNewBoston Youtube Channel.
The very first tutorial was about installation of Python.
I downloaded the latest version 3.8.4 for Windows.
While installation, I tick marked on ‘adding python to environment variable’. This will help me later in running my saved Python programs in command window as a standalone application.
Finally, I opened the IDLE Python (Integrated Development Environment for Python) by going to the start menu and clicking on the icon.
Bucky gave a teaser about how to print “Hello World”.
In his video, which is way too older than the Youtube upload date. He was using Python 2.6.1 version.
But since I was using the latest one, the syntax has changed.
So when he showed how to print hello world. I tried it too, on my side.
print "Hello, World!"
I got a SyntaxError!
So, I got curious and found that in the latest version of Python, one need to also add parenthesis like this-
print ("Hello, World")
By above code I got the result showing – Hello, World!
The first tutorial ends here.
Performing Simple Math Calculations in Python
On the same day I checked the second tutorial since first one was quite simple and quick.
I definately need a time gap to understand each and every concept carefully. So I will be breaking down with maximum 2-4 tutorials a day.
In the second video tutorial, Bucky was telling about how to play with numbers and Math.
At first, I tried basic addition, substraction, multiplication and division operators.
It is easiest to do that in Python.
All you have to do is type one number then math operator and finally other number.
2+2
6-3
7*5
18/3
Once pressed enter, they yield the answer.
But in the case of division, I got surprised.
Bucky told that you will get integer as a result if you divide integer. But, if you use decimal numbers then only you will get decimal number or what we call a float.
For example,
>>> 21/7
This should only result 3 as an answer.
NO!
In the latest version of Python, things have changed.
Now even if you type integer you will get a decimal answer. Like this –
21/7 will give 3.0 as result.
I learnt this from the comment section of that video.
If you use decimal numbers then you will get decimal answer.
Some examples,
12.0/3
30/3.0
21/7.
14.0/.5
Now comes another maths operator named Modulus.
We learnt this in early classes that modulus results remainder. When we divide two numbers and they are not completely divisible then remainder is left. That is what modulus does. Here is the example,
>>>9%4
1
You can also use decimal numbers with modulus operator.
Last but not the least comes the exponent operator.
What it does is, it multiply a certain number, a certain number of times.
For example, if we want the number 5 to be multiplied by 5, 3 times. So normally this is what we do – 5x5x5
But using exponent you don’t have to write that way.
You can simply type this –
>>> 5**3
125
You will get the result for 5x5x5.
You can also do this with negative numbers.
Variables and Input Function
Quoting Bucky, variable is like placeholder. You can store value in it temporarily.
Suppose I want to create a variable “x” and feed a value to it.
>>> x = 5
>>> print (x)
5
As you can see I provided a value to the variable and performed a print function. The result of the print revealed the answer.
Now does it look dumb? Yes, it does! ๐ But if you think about a bigger picture, variables are a bless in disguise.
Let’s try to add a number to the above variable x.
>>> x + 2
5
Now let’s take another variable y and assign a value to it and finally perform calculation between both x and y variable.
>>> y = 7
>>> x + y
12
I think this is easy as it looks. Let’s move on to the variable for which user will input the value.
Input Function:
Let’s take a variable g and ask user to enter the value,
>>> g = input("Enter the number: ")
Enter the number: 15
The input function is a built-in Python function which allows the end user to enter the value.
That value is then stored in the variable.
Now comes the fun part:
What happens if I add a number with the variable g?
For example,
>>> g + 10
TypeError: can only concatenate str (not "int") to str
It should return the value of 15 + 10 = 25 right? No!
In the new version of Python the input value is treated as a string or character. Hence, we cannot add a string to an integer.
I learnt this from the comment section of the video that you need to specify int function in order to make it an integer.
So if I type this,
>>> g = int(input("Enter the number: "))
>>> Enter the number: 15
>>> g + 10
25
Now it will work and the calculation will be executed.
That’s all for the DAY 1 of Python learning experience.
DAY 2
Importing Module
This is the second day of my learning Python. Today I started with 4th video on Modules and functions.
I have already learnt about input function earlier, but let’s look at few more.
Earlier I tried exponent operator which helps in multiplying a number n number of times.
For example: If I want to multiply 5, 3 times then generally I would write 555. In other words, 5 to the power of 3.
But I learnt that in Python I can simply use exponent operator. Like this 5**3 and this will yield the same result.
But is there any built-in function for exponent? Yes, there is.
It is represented as – pow(number,its power)
>>> pow(5,3)
125
There is another function for finding the absolute value. That is, how much distance a number is from zero.
It is represented as – abs(number)
>>> abs(-18.0)
18.0
Module Function:
Modules are the group of built-in functions.
One cannot use a function inside a module without importing the module first.
So if I want to find the floor value of a number I cannot directly type the floor function and expect a result.
Python wouldn’t recognize floor function without importing its relavant module.
Let’s do that:
To import a math module, type this –
import math
Now I can use each and every function defined under math module like floor function, sqrt function & more.
Once imported, function can be used. But there is a way to write that function. I cannot simply write this – floor(18.7)
I have to write –
>>> math.floor(18.7)
18
to get the result.
So proper representation of a function inside a module is –
module.function(values)
Let’s try it for square root, which will be defined as –
>>> math.sqrt(81)
9.0
Square root of 81 is returning 9.0 (decimal number).
Assigning Variable to the Module
To avoid using the whole module.function(values), I can now use the benefit of assigning a variable.
To do that, define a variable x and assign the value as the module function code.
x = math.floor()
So, now the x will be treated as a standalone function which will result in the floor value of the number.
>>> x(18.7)
18
So instead of typing entire math module, assigning variable can be done.
Now comes the 5th video on how to save your Python file and create your own standalone program.
Saving a Python File and Running the Program
Here comes the fun part.
Finally, I can create my own standalone Python program and run it. Isn’t that exciting?
In order to save Python file let’s first create one.
Go to File option in the menu. Then click on New File. A new window will appear.
Let’s print something.
print ("Hello world, this is me")
Now comes the part of saving this file. Go to File under menu and click on Save option.
File name should end with the extension .py
So I named my first file as - first.py
Time to execute this program.
Remember to always save the file before executing it.
There are two ways to run the program. One is by going to Run menu and then Run Module.
This will open a new window with the output.
Another method is by pressing Ctrl + F5 on keyboard.
But wait! There is always another one. ๐
I can also double click on my saved file first.py to open the standalone program with the output.
Let’s create another file and this time lets take user’s input.
I created a new file and wrote this inside –
x = input("Enter your name: ")
print ("Hey, " + x)
input("Press <enter>")
This is a simple program that asks user their name and print Hey, with their name.
But wait, why did I used the last line in above code?
I have to use it in order to hold the screen. What does that mean?
When I double click on my Python file, program window will open. It will ask for my name and the window will be closed almost immediately since it has nothing else to do after saying Hey.
The output for above code will be –
Enter your name: Bucky
Hey, Bucky
Press <enter>
Now as you can see the window is not closing and asking user to enter. Once I press enter, or infact any key, the window will close.
I have to use this line in all of my upcoming programs.
That’s all for the DAY 2 of Python programming experience.
DAY 3
String, Escape Character & Join
Welcome to the day 3 of Python Basics.
I have already used string earlier. Let’s deep dive into string by first printing a normal group of characters.
>>> "hello world, this is mark"
'hello world, this is mark'
As you can see it simply printed the string as is.
What if their is a conjunction between our text?
>>> 'He's a doctor'
SyntaxError: invalid syntax
Got an error since Python is unable to detect which single quote is the ending quote. But we can always use double quote outside and single quote inside to get the desired output.
But what if we need to add double quote inside?
Here comes the escape character to the rescue.
Escape Character:
Escape Clause or Character is used when their is a conjunction or quotes involved within a group of texts that needed to be printed.
Let’s make is easier by trying few examples-
>>> 'he\'s a doctor'
"he's a doctor"
>>> "bucky said, \"hello world\" to them"
'bucky said, "hello world" to them'
Both examples uses a backward slash which tells Python to ignore this quote and move on to the next.
Here is how you can store string in variable-
>>> x = "Bucky "
>>> y = "Roberts"
Adding strings together is known as concatenation. Here is an example –
>>> x + y
"Bucky Roberts"
I have to use + sign to concatenate 2 or more strings together.
Now comes the video 7 which covers more on Strings.
As I learnt earlier that concatenation between a string and an integer returns an error meesage.
But what if we ask user to input an integer value and later show a group of texts with that integer?
For that, I have to convert the number into string.
There were 3 ways to do it but from Python version 3 and above only 2 ways are left.
str(number) or repr(number)
Both of them does the same job of converting a number to string.
Here is the example-
>>> num = str(18)
>>> print ("bucky is " + num)
bucky is 18
>>> num = 2
>>> print ("That boy is " + repr(num))
That boy is 2
That’s it for the Day 3.
DAY 4
List & Sequence
The raw_input function is no longer supported from Python 3 and above.
So I skipped through the video 8.
Let’s learn about List in Python.
List is a group of strings. For example-
>>> family = ['mom','dad','bro','sis','dog']
Here the family is the variable which stores list of strings.
In python the list elements are assigned number starting from ZERO (0).
So in the above list the element mom is 0, dad is 1, and so on.
It is useful for indexing.
Suppose I want to find which element is present at 3.
>>> family[3]
'sis'
The answer is sis.
But, what if the list is too long?
For that, the list elements are assigned two numbers.
One counting from front i.e., from 0 and other counting from back i.e., from -1
So let’s find an element from back,
>>> family[-2]
'sis'
As you can see sis is at -2 by counting from back of the list.
Not only list but string can also be indexed in this way.
Sting can also be a sequence. Confused?
Example will clear it,
>>> 'bucky'[3]
'k'
>>> 'bucky'[-2]
'k'
So each character of the string is also assigned 2 number just like list elements.
DAY 5
List Slicing
Slicing is a performed to extract list elements.
I have to first create a variable and store a list in it.
>>> example = [0,1,2,3,4,5,6,7,8,9]
Now I will perform slicing on this list.
In order to slice, I need to follow this format –
variable[Starting Point:Ending Point]
Starting Point: is the first element which I want to extract.
Ending Point: is the element in the list which itself is excluded but every element before it is extracted.
Let’s see with an example,
>>> example[4:8]
[4, 5, 6, 7]
Starting element 4 is included in the list and everything before ending point 8 is included in the output.
Another example,
>>> example[4:9]
[4, 5, 6, 7, 8]
What if I want to extract complete list starting from 4?
>>> example[4:10]
[4, 5, 6, 7, 8, 9]
Now, suppose my list is too long. So I can even extract from back side of the list.
But to do that I have to follow the negative rule as I did earlier with sequence.
>>> example[-5:]
[5, 6, 7, 8, 9]
If I look from the back, the element 5 comes at -5 location. Hence, it was included in the output.
I left the ending point blank to extract complete list starting from -5 location.
Let’s take another example of empty point. But, this time from front of the list.
>>> example[:7]
[0, 1, 2, 3, 4, 5, 6]
If I want whole list stored in the element then I have to keep both points empty while slicing.
>>> example[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Slicing elements from list can also have third point.
variable[Starting Point:EndingPoint:Skip Point]
Here Skip Point refers to the element I want to skip after each element extraction.
Example,
>>> example[1:8:2]
[1, 3, 5, 7]
So every 2nd element after the extracted element is sliced from the output.
If I want to extract and sort the output from backward then,
>>> example[10:0:-2]
[9, 7, 5, 3, 1]
>>> example[::-2]
[9, 7, 5, 3, 1]
>>> example[9:0:-2]
[9, 7, 5, 3, 1]
Keeping Starting Point as the ending elements and Ending Point as the starting elements with the combination of third point can print the list from backwards.
DAY 6
Editing Sequence & Finding Element in Variable
I have already performed concatenation on string. Lets try that on a sequence.
>>> [7,4,5]+[4,6,5]
[7, 4, 5, 4, 6, 5]
Yes, it works. Its better to store them seperately in a variable and perform concatenation on the variable.
Concatenation of string and list is not possible and will give Type error.
What happens if I perform multiplication on a string?
>>> 'bucky'*10
'buckybuckybuckybuckybuckybuckybuckybuckybuckybucky'
It simply printed the string 10 times.
But when I do the same with an integer it gives the actual multiplication as output.
How to print an integer, 10 times?
Enclose it with square brackets like this,
>>> [21]*10
[21, 21, 21, 21, 21, 21, 21, 21, 21, 21]
Now comes the in keyword. in is a built-in keyword in Python that finds element inside a string or list.
It provides 2 answers. One is True and other is False.
>>> name = 'buckyroberts'
>>> 'z' in name
False
>>> 'r' in name
True
Lets do the same with a list,
>>> family = ['mom','dad','bro','sis']
>>> 'sis' in family
True
>>> 'aunt' in family
False
That’s all in 11th Video of Python Basics.
DAY 7
Functions on List
In the 12th video tutorial on Python basics, Bucky deep dived into more functions that can be performed on a list.
Lets give them a try,
I defined a variable numbers and stored a list of elements in it.
>>> numbers = [2,54,1,45,6,12,62,134]
Now to find the length of this list, I need to use len function.
>>> len(numbers)
8
So, it counts how many elements are present in the list.
To find maximum or minimum value in the list,
>>> max(numbers)
134
>>> min(numbers)
1
Now suppose I want to convert a string into list. Then the list function comes into hand.
>>> list('bucky')
['b', 'u', 'c', 'k', 'y']
There are lots of application of doing this.
Lets get back to the numbers list and replace and element from it.
To replace an element, just assign the new element to the relevant index like this,
>>> numbers
[2, 54, 1, 45, 6, 12, 62, 134]
>>> numbers[3] = 77
>>> numbers
[2, 54, 1, 77, 6, 12, 62, 134]
So the element at index 3 which is 45 got replaced with 77.
I can also delete an element using del function.
>>> del numbers[3]
>>> numbers
[2, 54, 1, 6, 12, 62, 134]
The element at index 3 is now removed from the list.
DAY 8
List Slicing & List Function
Slicing can also be used to replace, add or delete elements from a list.
Lets create a list using list function,
>>> example = list('easyhoss')
>>> example
['e', 'a', 's', 'y', 'h', 'o', 's', 's']
Now to replace the elements “h o s s” with “b a b y”, slicing can be used this way-
>>> example[4:] = list('baby')
>>> example
['e', 'a', 's', 'y', 'b', 'a', 'b', 'y']
What it does is it starts from index 4 till end of the list and replaces it with the output of list function.
I can also replace bigger list,
>>> example[4:] = list('racecars')
>>> example
['e', 'a', 's', 'y', 'r', 'a', 'c', 'e', 'c', 'a', 'r', 's']
Now how to add elements to the list using slicing. Lets take an example variable,
>>> example = [7,8,9]
>>> example
[7, 8, 9]
Here is how I can add elements to it,
>>> example[1:1] = [3,3,3]
>>> example
[7, 3, 3, 3, 8, 9]
Here 1:1 indicates that it will add the defined elements just before the index 1.
Now comes the deletion part,
>>> example[1:5] = []
>>> example
[7, 9]
Just define the slicing with empty brackets and it will remove the desired elements.
Basics about Method
Method is a built-in function which is used to perform action on an object.
Here is how to define a method,
object.action()
Lets take an example,
>>> face = [21,18,30]
>>> face
[21, 18, 30]
Now I want to add an element to the end of this list,
>>> face.append(45)
>>> face
[21, 18, 30, 45]
Here face is the object and append is the action. What append does is it add an element to the end of a list.
But, it only adds one element to the end. What about multiple elements?
For that I have to use extend.
Here is an example,
>>> one = [1,2,3]
>>> one
[1, 2, 3]
>>> two = [4,5,6]
>>> two
[4, 5, 6]
>>> one.extend(two)
>>> one
[1, 2, 3, 4, 5, 6]
Here one is the object and extend is the action. It helps to add multiple elements at the same time to the end of the list.
Now how to count the number of times an element is repeated in a list.
>>> apples = ['i','love','apples','apples','now']
>>> apples
['i', 'love', 'apples', 'apples', 'now']
>>> apples.count('apples')
2
>>> apples.count('bow')
0
I created a variable apples and stored bunch of elements in it. Using count, I can count the number of times the element is repeated in the list.
So apples was repeated 2 times but bow was not present in the list, hence 0.
DAY 9
Few More Methods
Let’s look into more methods.
First one is the index method. It finds the first occurrence of an element in the list.
>>> say = ['hey','now','brown','cow']
>>> say
['hey', 'now', 'brown', 'cow']
>>> say.index('brown')
2
Starting from 0 then element brown is at 2. So the index method return 2 as the output.
What is I want to insert an element at a certain position?
For that insert method comes into handy.
>>> say.insert(2, 'hoss')
>>> say
['hey', 'now', 'hoss', 'brown', 'cow']
The insert method takes a arguments. One is the position where I want to insert the element and second is the element itself.
Now ofcourse I need to remove an element from the list.
For that pop method is present.
>>> say.pop(1)
'now'
>>> say
['hey', 'hoss', 'brown', 'cow']
The pop method takes one argument and that is the position of the element I want to pop out.
But the fun part is that pop method gives an output. The output is the element which I want to remove from the list.
There is another method to remove an element. Guess what, it is remove method.
>>> say.remove('brown')
>>> say
['hey', 'hoss', 'cow']
It takes the element as an argument.
Last but not the least, reverse method.
>>> say.reverse()
>>> say
['cow', 'hoss', 'hey']
As name suggests, it reverses the list and print it.
DAY 10
Sort & Tuple
Sort method is used for sorting elements in a list.
>>> new = [23,32,564,213,45,21]
>>> new.sort()
>>> new
[21, 23, 32, 45, 213, 564]
Sort method can also be used to sort the string. But the command changes.
>>> sorted('hellopythonbasics')
['a', 'b', 'c', 'e', 'h', 'h', 'i', 'l', 'l', 'n', 'o', 'o', 'p', 's', 's', 't', 'y']
Now comes the Tuple. Tuple is also like list but we cannot modify element inside tuple.
It is just used to return values back.
>>> 41,42,43,44
(41, 42, 43, 44)
Lets take a variable and store tuple in it.
>>> bucky = (32,33,43,54)
>>> bucky
(32, 33, 43, 54)
>>> bucky[2]
43
Tuple is just used to get our values back.
DAY 11
String Formatting
To format a string means, if I take a string and pass different values to it using different variables.
Lets take an example.
>>> bucky = "Hey there %s, hows your %s"
Here the %s is used for string.
Now lets create a variable which contains 2 arguments and fill those elements in the above string.
>>> varb = ('betty', 'foot')
>>> print (bucky % varb)
Hey there betty, hows your foot
So I created a variable varb and passed two arguments in it.
Then I used print function to pass the values inside the string.
I can do this multiple times with different inputs.
Now, lets try to find element in a string.
Remember, earlier I tried the same on list. This time it is for string.
>>> example = "Hey now bessie nice chops"
>>> example.find('bessie')
8
I have used find method to locate the index for the element bessie.
Here even the space is also counted as a position. Hence the output is 8.
DAY 12
Methods on String & Sequence
At first comes the join method. This is used to fill a sequence with a string.
>>> sequence = ['hey','there','bessie','hoss']
>>> sequence
['hey', 'there', 'bessie', 'hoss']
>>> glue = 'hoss'
>>> glue.join(sequence)
'heyhosstherehossbessiehosshoss'
The join method simply joined the string with the sequence after every element.
Now comes the lowercase or uppercase method.
As name suggests, it makes a string in lower or upper case.
>>> randstr = "i wish i Had NO sausage"
>>> randstr
'i wish i Had NO sausage'
>>> randstr.lower()
'i wish i had no sausage'
>>> randstr.upper()
'I WISH I HAD NO SAUSAGE'
I took a random string and put a random upper case in between. Then used lowercase and uppercase method on it.
Last but not the least, replace method.
It replaces a word in a string.
>>> truth = "I love old women"
>>> truth
'I love old women'
>>> truth.replace('women','men')
'I love old men'
Let me make this clear. This is what Bucky Roberts took as an example ๐
DAY 13
Dictionary and Relevant Methods
With Dictionary, I can use key or value to find the item.
It is denoted by curly brackets.
>>> book = {'Dad':'Bob','Mom':'Lisa','Bro':'Joe'}
>>> book
{'Dad': 'Bob', 'Mom': 'Lisa', 'Bro': 'Joe'}
The arguments are the key and value of it.
Let’s find the value using key.
>>> book['Dad']
'Bob'
>>> book['Mom']
'Lisa'
To find a value square brackets with key is used.
Not only string, but it can also take integer as an input.
>>> ages = {'Dad':42,'Mom':87}
>>> ages
{'Dad': 42, 'Mom': 87}
>>> ages['Dad']
42
These are called dictionary methods.
Now comes the clear method.
It helps in removing all items in a dictionary.
>>> book.clear()
>>> book
{}
All items from dictionary book is removed.
Another method is copy method. It copies one dictionary items to another.
>>> tuna = ages.copy()
>>> tuna
{'Dad': '42', 'Mom': '87'}
It copied ages items to tuna.
Last but not the least, has_key.
This one is removed from latest Python since in function is much more efficient and faster.
Look for timeit.
>>> 'Mom' in tuna
True
>>> 'Apples' in tuna
False
It returns true of false.
DAY 14
if Statement
Now comes the point where I will be making Python programs.
The first one is for “if” statement.
The if statement checks the condition. If its true then the indented codes after it gets executed.
Lets take an example. For that first create a New file and save it.
tuna = "fish"
if tuna == "fish":
print ("This is a fish alright")
Here if statement checks whether the condition is satisfied or not.
Since it is, the output will be printed.
== is used for checking the value.
Here print function is indented. In Python, indent has a great significance.
It will only give output for indented print statement. If indent is removed, I will get an error saying – “expected indented block”.
DAY 15
Else & Elif Statement and Nested if Statement
Earlier I learnt about if statment under which when a condition is true then the code inside if statement gets executed. But what to do if the condition is false?
There comes the else statement.
Else statement executes the false condition for if statement.
What if I want to check multiple conditions?
Then comes the elif statement which is exactly like if statement with a condition to check.
Lets take an example-
tuna = "fish"
if tuna == "bass":
print ("This is a fish alright")
elif tuna == "slamon":
print ("I hope i dont get SLAMonilla poision")
elif tuna == "fish":
print ("easy there tuna boat")
else:
print ("I don't know what this is")
Here I have if statement, 2 elif statment and else statement.
The 2nd elif statement satisfies the condition. Hence, the code inside that will be executed.
So the output will be – easy there tuna boat.
Nested if Statement:
As name suggests, it is the if statement inside the if statement.
So when a condition is satisfied for if statement, run another set of conditions.
thing = "animal"
animal = "cat"
if thing == "animal":
if animal == "cat":
print ("this is a cat")
else:
print ("i dont know what this animal is")
else:
print ("I dont know what this thing is")
OUTPUT: this is a cat
At first the condition for thing is checked. Since it is true then the if statement inside it was checked.
Since that is also correct. Hence, the desired output is printed.
DAY 16
Comparison Operators
There are many comparison operators like greater than, less than, equals to, etc.
>
<
<=
>=
!=
These can be used on integer number to check whether the condition satisfies or not.
is Operator:
It is quite similar to == but not exactly.
It does checks for whether to variables are equal or not but both variable should be same.
For example,
>>> one = [21,22,23]
>>> two = [21,22,23]
>>> one == two
True
>>> one is two
False
>>> one is one
True
Or if the one = two = [21,22,23] was defined then one is two would return True.
in Operator:
It is used to check whether the element is present in a string.
>>> pizza = "pizzahut"
>>> 's' in pizza
False
>>> 'p' in pizza
True
>>> if 'p' in pizza:
print ("p is present")
p is present
The comparison operators can also be used on strings.
>>> "dog" < "cat"
False
Here the Python is not telling us that dog is better than cat or something. It is just checking the first letter of the string and comparing it with alphabetical order.
>>> "d" < "c"
False
>>> "c" < "d"
True
and Operator:
It checks multiple conditions at once. It only returns output when all conditions are satisfied at the same time.
>>> example = 5
>>> if example > 3 and example < 10:
print ("Number is between 3 and 10")
Number is between 3 and 10
>>> if example > 3 and example < 4:
print ("x")
or Operator:
It also checks multiple conditions but at least one needs to be satisfied in order to give the output.
>>> if example > 3 or example < 4:
print ("this works")
this works
That’s it on comparison operators.
DAY 17
For & While Loop
Looping is used to execute a certain code n number of times without actually writing it n number of times.
While Loop:
While loop contains a condition which is checked until which the code will run. It also contains the loop condition.
>>> b = 1
>>> while b <= 10:
print (b)
b +=1
1
2
3
4
5
6
7
8
9
10
I created a variable b and assigned value 1 to it.
Then while loop checks the value of b until it is less than of equal to 10. Simultaneously value of b is incremented by 1.
For Loop:
For loop is used to loop object or sequence.
It contains a variable which is assigned different values one by one until the loop lasts.
>>> gl = ['bread','milk','meat','beef']
>>> gl
['bread', 'milk', 'meat', 'beef']
>>> for food in gl:
print ("i want " + food)
i want bread
i want milk
i want meat
i want beef
Here the variable food is one by one assigned the values of the list gl.
The print statement then prints each items in the list along with the pre-defined statement.
Another example can be for a dictionary where the only the element is assigned to the variable and not the value.
Infinite Loop & Break Statement
>>> while 1:
name = input("Enter name: ")
if name == "quit": break
Enter name: greg
Enter name: tom
Enter name: lisa
Enter name: bucky
Enter name: quit
This loop is always satisfied since 1 will always be true condition.
I have to use break statement to stop the loop.
When the name matched the desired name, the loop breaks.
DAY 18
Creating Your Own Function
Till now I have been using predefined functions in Python. Now its time to create my own function.
To create a function I need to first define it-
def FunctionName(parameter)
Once defined I can provide the instructions inside the function to run whenever it is called.
>>> def whatsup(x):
return 'whats up ' + x
>>> print (whatsup('tony'))
whats up tony
Not only string function but I can also create a math function.
For example addition function-
>>> def plusten(y):
return y+10
>>> print (plusten(44))
54
This function takes a value and adds 10 to it.
DAY 19
Parameters in Function
Default Parameters:
It is a parameter which is used when no parameter are passed through the function.
>>> def name(first='tom',last='smith'):
print ('%s %s' % (first, last))
>>> name()
tom smith
>>> name('bucky','roberts')
bucky roberts
As you can see, I provided the default value to the first and last variable.
If no value is passed through the name function then it returns the default predefined paramters.
If provided only one of the variable then it prints that variable and a default value for the other.
Multiple Parameters (Converting Parameters to Tuple):
If I want to store multiple value in a variable then I have to make use of tuple.
The element is defined as – *variable
It takes multiple parameters and stores it in a tuple.
>>> def list(*food):
print (food)
>>> list('apples','peaches','beef')
('apples', 'peaches', 'beef')
Converting Parameters to Dictionary:
Same as tuple, I can also convert parameters and store it in a dictionary.
It is defined as – **variable
>>> def cart(**items):
print (items)
>>> cart(apples=4,peaches=6,beef=60)
{'apples': 4, 'peaches': 6, 'beef': 60}
I can also combine tuple and dictionary in a single function.
>>> def profile(first, last, *ages, **items):
print (first, last)
print (ages)
print (items)
>>> profile('bucky','roberts', 32,43,76,65,76, bacon=4, saus=64)
bucky roberts
(32, 43, 76, 65, 76)
{'bacon': 4, 'saus': 64}
The Python automatically judges the nature of the parameter.
The first and second parameter is for the first and last variable.
The series of elements without = is stored in the tuple.
The series of parameters with = is stored inside the dictionary.
Gather Info from Tuple and Use it as Parameter:
>>> def example(a,b,c):
return a+b*c
>>> tuna=(5,7,3)
>>> example(*tuna)
26
That’s it for the parameters.
DAY 20
Python is OOP
Python is an Object Oriented Programming Language.
object.method()
Creating a Class:
Class is a blueprint for object.
class ClassName:
Creating a method inside class:
>>> class exampleClass:
eyes = "blue"
age = 22
def thisMethod(self):
return "Hey this method worked"
I created a class and added two variables and a method inside it.
Method inside class always contains first parameter as self.
Now let’s create object and use data from class.
>>> exampleObject = exampleClass()
>>> exampleObject.eyes
'blue'
>>> exampleObject.age
22
>>> exampleObject.thisMethod()
'Hey this method worked'
At first I defined object and assigned class with empty parameters to it.
Then I called the elements and method of the class using object.
Classes and Self
Self is a temporary placeholder for object.
>>> class className:
def createName(self, name):
self.name = name
def displayName(self):
return self.name
def saying(self):
print ("hello %s" % self.name)
I have created three method inside class.
Each method contains self as the first parameter which is just the placeholder for object that will be defined later.
>>> first = className()
>>> second = className()
>>> first.createName('bucky')
>>> second.createName('tony')
>>> first.displayName()
'bucky'
>>> first.saying()
hello bucky
>>> first.name
'bucky'
I created 2 objects and defined class with empty parameter to both objects.
Now I can utilize data inside class with object.
I called method and provided a parameter to it.
The second method simply prints the parameter. The third method prints the string Hello along with the name parameter.
DAY 21
Super & Sub Class
Its a simple concept.
One class inherits the traits of other class.
Child class inherits all data from Parent class.
>>> class parentClass:
var1 = "i am var1"
var2 = "i am var2"
>>>
>>> class childClass(parentClass):
pass
>>> parentObject = parentClass()
>>> parentObject.var1
'i am var1'
>>> childObject = childClass()
>>> childObject.var1
'i am var1'
Overwrite Variables in Sub Class:
Its just that inherit traits from parent class but overwrite some variable.
>>> class parent:
var1 = "bacon"
var2 = "snaausage"
>>> class child(parent):
var2 = "toast"
>>> pob = parent()
>>> cob = child()
>>> pob.var1
'bacon'
>>> pob.var2
'snaausage'
>>> cob.var1
'bacon'
>>> cob.var2
'toast'
Sub Class with Multiple Parent Classes:
A sub class that inherits traits from multiple super classes.
>>> class Mom:
var1 = "hey im mom"
>>> class Dad:
var2 = "hey there son im dad"
>>> class child(Mom,Dad):
var3 = "im a new variable"
>>> childObject = child()
>>> childObject.var1
'hey im mom'
>>> childObject.var2
'hey there son im dad'
>>> childObject.var3
'im a new variable'
Constructors
It is a way to initialize a method inside a class as soon as an object is created.
Earlier I have to call method in order to get output.
But now, as soon as object is assigned to the class, everything inside that method prints out.
>>> class new:
def __init__(self):
print ("This is a constructor")
print ("this also print out")
>>> newobt = new()
This is a constructor
this also print out
Here __init__ is a predefined method and name cannot be changed.
DAY 22
Importing Module
Module can be saved and later imported in Python for use.
To import a module the file must be saved in the Python folder in C drive.
Here is how you can import a module:
import module1
Here module1 is the file which I saved in Python folder as module1.py
The content of module1.py file is:
def testmod():
print ("this baby worked")
So now let’s import this module and call it.
>>> import module1
>>> module1.testmod()
this baby worked
Here instead of using object, I can directly call module as mentioned. For example: ModuleName.FunctionName()
Now what if I change some content in the module1.py file?
def testmod():
print ("this baby is fat")
Even if I have changed the content inside module1.py file the output will still be the old one since we have already imported the module with old data.
“You can only import module once per program.”
To print new data I have to close the IDLE and reopen and again import the module to get the desired result.
Reload Module
As we saw earlier that edited module required IDLE to reopen and again import the module.
But using reload we do not have to close IDLE again and again.
But from Python 3+, reload will only work after we import the imp module.
>>> import imp
>>> imp.reload(module1)
<module 'module1' from 'C:\\Users\\Invader\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\module1.py'>
This way we can reload the module which we edited and get output as desired.
DAY 23
Getting Module Info
There are many inbuilt functions inside module in Python. To know what are those we use dir function.
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
dir function list all of the modules available.
Now in order to know details about each and every items inside math module we can use help function.
>>> help(math)
This will list each module with their description or value.
Now how to know what does math module is about?
For that we use the __doc__ function.
>>> math.__doc__
'This module provides access to the mathematical functions\ndefined by the C standard.'
Working with Files
Before going ahead, let’s create a file name a.txt and store it in c drive.
We will be performing write and read functions on this file.
To write something inside a.txt file let take an object and equate it with open function.
Open function opens the file.
>>> fob = open('c:/test/a.txt','w')
open function takes 2 argument. One is the location of the file and other is the task we want to perform on it. w is for write and r is for read.
Let’s write something inside a.txt file.
>>> fob.write('hey now brown cow')
17
I have used write function and added a sentence inside it.
Here 17 is the bytes. Bytes can also be treated similar to characters.
Now we have to close the file in order to prevent memory leakage.
>>> fob.close()
Now if I open the text file a.txt in a notepad, it will have the text which I provided above.
Now how about read function.
>>> fob = open('c:/test/a.txt','r')
>>> fob.read(3)
'hey'
>>> fob.read()
' now brown cow'
>>> fob.close()
read function also takes one optional argument and that is bytes. Bytes can be seen as characters in a string.
Now what about multiple lines inside the text file.
For that we use readline for 1 line and readlines for all lines.
>>> fob = open('c:/test/a.txt','r')
>>> print (fob.readline())
hey now brown cow
>>> print (fob.readlines())
['line 1','line 2','line 3']
>>> fob.close()
The readlines function outputs the lines in list format.
Writing and Reading Files
Let’s write multiple lines in our a.txt file.
To do that we use writelines function.
>>> fob = open('c:/test/a.txt','w')
>>> fob.write('this is a new line\nthis is line 2\nthis is third line\nthis is the last and final line')
84
>>> fob.close()
Here \n is used to shift the text to next line.
Now, let’s read these lines.
>>> fob = open('c:/test/a.txt','r')
>>> listme = fob.readlines()
>>> listme
['this is a new line\n', 'this is line 2\n', 'this is third line\n', 'this is the last and final line']
>>> fob.close()
As you can see it printed each line inside a list. Here I stored the output of readlines inside listme list.
What about replacing a line with different sentence?
>>> listme[2] = "this is the REPLACED line"
>>> listme
['this is a new line\n', 'this is line 2\n', 'this is the REPLACED line', 'this is the last and final line']
>>> fob = open('c:/test/a.txt','w')
>>> fob.writelines(listme)
>>> fob.close()
To replace a line, firstly I replaced it inside the listme list.
But it doesn’t change the text inside original a.txt file.
To achieve that we will again open the file and pass the list as parameter inside writelines function.
This will then replace the line inside a.txt file.
That’s all for the Python Basics Tutorial.
Leave a Reply