Learn Python With Dhawal - 18 - Interacting with Python on terminal


In this chapter we will learn to interact with python as it actually is, in its default form to understand how the language functions at a basic level. Since we are already quite familiar with Jupyter and writing basic level codes right now. We have to get a deeper understanding of how our commands actually are executed before we move ahead and start working on much deeper concepts.

1. Getting Started :


1. 1 Open Python Terminal :

  1. If you already know how to open terminal or command prompt then you can skip to next part.
  2. First way to open python terminal ( for anaconda python ) is to search in your windows for anaconda prompt. Clicking on it, it'll open a terminal for you.
  3. Another way to access the terminal is to open Anaconda Navigator -> Command Shell
  4. Another way would be simply opening up a terminal ( this method will work only if you are working with Ubuntu which has a default python installed already, or if you have added your python path into system path variables )
1.2 Start with Python :

Once you've opened up your choice of terminal/s just try this command to check if the installation works as expected.

Input :

python --version
  
Output :

Python 3.7.6

Next, as we move ahead, you can try a single print statement as we had done in the first exercise. But before that we have to start Python so that we can begin interacting with python in the terminal, in its native format.

Input :

python


Output :

Python 3.7.6 (default, Jan  8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

Note : >>> denotes the line where you have to give input. Pressing enter will show you the output to get executed in python.

Input :

print("hello world!")

Output :

hello world!

Try yourself : 

Try using it like a calculator and give it inputs like 2+5, 5*4, 4/2, etc. and see what's the output. Does it give any error? If yes, try finding out why? and if no, know the reason why it works the way it does?

1.3 Taking Input into variables 

Just like the usual method, you can either declare a variable with a value or take input from the user. We will learn both from the example below.

Code :


>>> a=10
>>> b=input("Enter a value to be divided by 10")
Enter a value to be divided by 102


As you can see from the example above, a=10 makes a variable a with value 10. Next when you take input into b, the statement appears as prompt which you've written and then a cursor blinks next to it without a space. For the proper format to get input you'd need to format the statement properly like shown below.

>>> b = input("Enter a value to be divided by 10:\n")
Enter a value to be divided by 10:
3
>>>

Next try dividing a with b and store the result in a newly created variable c, see what you get.

>>> c = b/a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'
>>>

This is because you need to convert first the input into the int as shown in the example below.

>>> b = int(input("Enter a value to be divided by 10:\n"))
Enter a value to be divided by 10:
3
>>> c = b/a
>>> print(c)
0.3
>>>

If you noticed, you won't get output like Jupyter-notebook when after operation you'd get a result but here you'd have to print to see the output.

>>> c
0.3
>>>

If you just type the variable name like this then too you can get output. But this only works in the terminal as a single step input not in the python programs with a lot of collective statements.

2. Diving Deep Into Functional Programming.


1. Creating Functions :

Before you read ahead, I'd like you to give creating function a try yourself.  Once you have 

>>> def myfunc():
...     print("Hello world!")
...
>>> myfunc()
Hello world!
>>> myfunc
<function myfunc at 0x000001E8B62E8168>
>>>

Here as you can see, you need to put 4 spaces as tab to have the indentation which you were getting by default inside the jupyter notebook. Apart from that if you just write function name, you'd find the location of the function in the memory space. Try out experimenting with the functions as you like.

2. Write a Program and execute it from terminal.

Now, I assume you'd be quite familiar with the terminal and how to write code using it. Next I'd like you to learn is that how to make a python script and execute it from terminal.

1. Write a Python Script


  1. Open a Notepad, Notepad++,Gedit, Nano, Vim, or IDLE if you're using random python distribution or if you are fancy enough to use IDE like Visual Studio Code, PyCharm or even Spyder ( comes within Anaconda distribution ) then surely you can but that would just go against of our purpose of running a script from terminal. But I'd recommend sticking with Notepad, or any other such simple text editor for the beginning.
  2. Create a new file and save it with the extension '.py'. It means it's not a normal text file but rather a python script.
  3. Enter the code ( basically whatever program that you want to run ) and save and exit.
2. Executing the Python Script

Here, it gets a bit tricky as there are various types of shells and various configuring ways to run a python code. Navigating to the folder is a huge task here therefore I'd stick to a very direct and layman approach. You can explore around and gather information from the internet to learn more on how to use different shells.

  1. Open anaconda powershell prompt or whatever terminal you're using python with. Then use the command below to navigate to the folder where your file is located.
    cd<space>Location_of_the_Folder_in_your_system.
    example : cd Desktop
  2. To execute the script just type the following command.
    python<space>FileName.py
    example : python Helloworld.py
3. Extra tips in navigating to folder.

Since I have used Linux ( ubuntu) and Windows, I can guide a shortcut way to do the same thing, but do these shortcuts with a pinch of salt. Google and confirm before you execute any shell commands.

  1. Go to the folder using file explorer and press shift and right click ( for windows) or just right click ( for ubuntu ) to get a menu. In that menu look for any option which says open terminal here or  open powershell prompt here click on it to open a new window there.
  2. Try running the python --version  command first to see if python works in that shell.
  3. If it doesn't work and If you're running Anaconda Distribution of Python use command 'conda init' followed by the name of that shell. It'll be powershell or terminal for windows depending on what you're using or bash for linux. ( if you have added it to the path )
  4. If you want to navigate to a folder to execute a file then you'd need to cd to that address. you can copy the folder address from the location bar in the explorer and then just paste it with cd command in the terminal window.

With this Now I hope you understand why we always used jupyter notebook or even things like other IDE to execute things in a simpler manner. These things would just waste time and add complexity to the procedure and get in the way of actual coding.

This was very important as from next chapter onwards I'd be working on Visual Studio Code. As in Next chapter we'd learn to use packages, create our own package and a few other things before we move on to the UI creation part of the system.


<< PREVIOUS CHAPTER || NEXT CHAPTER >> --INDEX--


~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~

Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Review: Tales of Demons and Gods



Tales of Demons and Gods by Mad Snail
My rating: 5 of 5 stars
Link : https://www.wuxiaworld.com/novel/tales-of-demons-and-gods#


Book Description : 

Killed by a Sage Emperor and reborn as his 13 year old self, Nie Li was given a second chance at life. A second chance to change everything, save his loved ones and his beloved city. He shall once again battle with the Sage Emperor to avenge his death. With the vast knowledge he accumulated in his previous life, he shall have a new starting point. Although he started as the weakest, without a doubt, he will climb the steps towards the strongest.

Cultivating the strongest cultivation technique, wielding the strongest demon spirits, he shall reach the pinnacle of Martial Arts. Enmities of the past will be settled in this new lifetime.

“Since I’m back, then in this lifetime, I shall become the King of Gods that dominates everything. Let everything else tremble beneath my feet!”  


Note :  I read this book on Wuxiaworld, hence if the original book source differs, feel free to comment down and it'd update the information.

Let me begin this with a piece of warning. This book already has 485 chapters and possibly more if someone reads this review later. It's an ongoing book on Wuxiaworld with a new chapter published every month. So that being only major con, if you can let that 'ongoing' tag go and enjoy the book's already uploaded chapters then this review will be worth reading for you.

So, I was just randomly looking for some new good stuff to watch and stumbled upon anime version of this series. The anime was of 5 mins each, like seriously?! Phew! Anyway, I still enjoyed the anime so much I decided to take a look if it was based on some book. So guess what? I googled and stumbled upon link to the goodness of the textual realm. ( I am someone who prefers books over movies :P ). Anyway, I decided to get reading from where the story had stopped in anime and damn! I enjoyed this one so much I decided to give it a review even when this one is an ongoing book and the chapter rate is horrible at one chap per month. ( If you know me, you'd know how much of a big deal it is for me to get reading onto such a book.) Well, to be fair enough, 485 chapters are a good enough amount to read hence, I started reading.

Where do I begin with? If I want to summarise it in one line then you can say it is like a 'Rajnikanth' movie story. The character building, world building is super complex and amazing. I loved the new concepts. Even after being a fantasy, everything was really well built and everything had a really good logical reasoning. It was really hard to find issues in the plot unless I really start being a crappy person and nit picked on everything. I'd say just give this book a try. Only huge con being you'd have to wait very long for the updates.

The plot is fantasy based with a lot of teen fiction, gamer, spiritual influence over it. It's most probably adventure based plotline in terms of how the story progresses. I won't reveal much about the story and I'd just recommend reading it. I wish the anime was much longer in terms of duration and was released faster. I can only hope though because even though I read this, I'd really want to see the visualisations. I'd recommend watching those episodes before watching as it'll give you an actual idea of how things are in this universe as the descriptions aren't really strong point of this story.

One more thing that I noticed was that the author was probably getting stagnant with the plot ideas as everything felt recursive. Although there were minor changes here and there but the major plotline after 300 chapters started to feel the same. Remember, I said 'same' not 'boring'. Well, I ended up reading all 485 chapters in less than 3 days and it was a great read. Especially when there's quarantine emphasis all around you.

Link : https://www.wuxiaworld.com/novel/tales-of-demons-and-gods#

Note : If you want to download and read in your kindle, here's the link. I don't support rampant piracy but well you should know what should be done and what shouldn't be done. So here's the link : https://www.asianovel.com/series/tales-of-demons-and-gods




Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Secret To A Happy Life



There are a myriad of books, lectures, podcasts and what not which just go on preaching the secrets of a happy life. For a moment, we take a deep breath and take everything the person or the book mentioned into consideration. Later, possibly just a few hours later or at the max a day past that moment we are back on our usual self.

Then we just sit down and crib about almost everything in the world. We barely realise that we are missing one very simple thing.
अति सर्वत्र वर्जयेत् 
The above is quoted is from a sanskrit text. You might be aware of its the origins if you are well read. It just means that everything suits in limits. A simplest edible item can poison you if taken more than what's required. We do the very same mistake every time. People who want to get fit will eat only veggies, or maybe just eat green leafy stuff like barn animals all the time. Why not take a balanced diet approach? People who often are proud of their work become workaholics, myself was one at sometime in past. Keeping things in the limits isn't a task. Rather knowing what your limits are is the one gigantic task.

There's no one way solution for this, as everyone has their own limits. You have to find out the borderline post whence you start taking stress. Again, let me remind you, pushing yourselves a little for growth is needed but don't push too much ending up breaking yourself. Alongside, stop compensating for your efforts. It took a lot from you to get up and get going by compensating and making yourselves feel good will just roll back on your efforts.

Most easily available example would be a person who works out daily with a goal to get fit and lose some weight. Later on, just as a method to self appraisal she ends up eating cakes and other junk to make herself feel good and motivate for the next day. That happens with little to no realisation that you just nullified your own efforts.

If you see, this formula of limiting things comes into every example like spending too much, saving too much ( being stingy ), happy too much, sad too much.. like this 'too much' is the thing actually causing issues rather than individual instances.

All of this happens because of desire to grow. To grow we constantly push ourselves and others most of the times getting ahead of our capacities. For a moment or two it might just work all well but in a longer run it everything just falls down head on. It causes nothing but issues mostly mental but several times the issues dive into the materialistic world as well.



Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Wondered why you look better or worse in pictures than mirrors? - How selfie cams make you feel good.



I was using my gcam to click some shots and then I ended up taking a selfie later on with a friend. Now, my friend looked a bit weird in the selfie and I started wondering there must be something wrong with my selfie skills.

To be totally honest, I felt I look better than her in pictures, just joking. When I took some normal candid shots from rear camera they appeared fine but selfie look was a bit weird. For a moment, I thought there must be something seriously wrong with my selfie skills. But then I wondered if that's the case then how can I look good and she was looking weird.

I started googling next. Now, if you know me well, I love experimenting and this gave me a literally brain fuck moment. During physics lectures, I had learnt that mirrors don't show the true self. It was something that was already in front of me and I never realised it.

Some of you might think what's the big deal, it's just a selfie right? Well wrong, think of yourself getting ready by looking in mirror and you make yourself look just perfect in the mirror, think you're good to go and when you click pictures at some party, they're just ultimate weird. I'd use the term weird as I don't wanna go into ugly vs beautiful classification. It's just different.

The fun fact was my friend was already well aware of it. She just said,"That's why we (girls) always ask others to click or get a candid shot more than selfies." At that moment, I really felt dumb.

Now, I researched a lot after this revelation on the internet. I also messed with almost every other camera setting and a few apps. The brain fuck moment wasn't here. It's fine, we look weird in mirrors or real depending on your choice of the perception you think about yourself. But, I kinda felt scammed a little when I had a realisation.

When you think you're looking good and click yourself with your average selfie cam app. I used gcam and always wondered why it looks so weird in selfies even though the selfie preview looked great? I started researching and this is what I found.

If you think you look really good in photos then you are kinda sorted. Selfies are not your thing and you prefer someone clicking you over you clicking with a selfie cam. Then you are looking at the real you.

As Everyone Sees Me
This picture shows how I might be looking to you in real life. But the fun fact is that for you this might be normal. But for me it's a surprise. I don't see myself like this ever in mirror. The second picture shows how I look at myself in the mirror. Mostly as this is a selfie, there are many things I'd like to throw some light on later but this is simple fact.

As I see myself in mirror

If you want to see how you appear to others, just go the selfie camera, make the option to click the mirrored selfies off and click. Now, the irritating thing I encountered here as while you still have options to click real selfies and mirrored, there's no way to get a real selfie preview.

Each and every single selfie camera in this world shows you a mirrored selfie preview
The clicked images might just differ as later after clicking the software flips is to show the real image as per your chosen setting.

Now, I dived deep into this and this trickery, is traced back to the first days in selfie world. When the first selfie camera made appearance in the world. Apple decided to make iphone show mirrored selfies so as people feel nice and comfortable clicking themselves as much as they want. Later on the removed the mirror mode but the preview still gives you a mirrored image, even when post clicking the selfie turns up real image.

I got annoyed at the fact that in the world of UI and UX designs we are taught to follow WYSIWYG (What You See Is What You Get) principles. But here in the reality there's a whole new level of scam going on.

Every social media app, shows you unreal selves. that's why something they look horrible in selfies or others think opposite. But here's a little catch. The selfies aren't still exactly showing you real you even if you turn off the mirrored selfie mode off. The camera due to close angles and the way you click, just makes it look more weird than you might appear in reality. Although the weird context increase it's still somewhat true.

I still wonder, why every selfie camera in the world shows us mirrored previews. Why not just let us see how the picture will turn out to be? Isn't that the actual use of previews?
The answers I found were, it's to aid you in placing camera better. You might turn left in real and camera will move right. So to undo this counter steering the previews are still mirrored while pictures you take are real.

The fact that they haven't bothered yet to undo this age old system is because to make user comfy to use the system as well as that taking a selfie from a close angle might be actually not so real much. The focal length plays an important role in how we perceive the objects hence the idea of clicking mirrored selfies all the time might not be a totally absurd one.

In the end, a selfie should encourage you to click more and upload more and then send complimentary comments for the device. There's no concern regarding it getting artificial day by day.

Isn't this a whole lot of messy confusion and looks like a lot of thinking to be done upon?

Why not even a single camera for selfies shows you true previews and by default gives you options to click true images of yourselves? Why every social media is hell bent to make you feel good?

I'd really love to know your thoughts on this. Please do comment.




Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Review: Time of Contempt



Time of Contempt by Andrzej Sapkowski
My rating: 3 of 5 stars
Link : https://amzn.to/2ODkj6t


Book Description : 

Geralt the Witcher has fought monsters and demons across the land, but even he may not be prepared for what is happening to his world. The kings and armies are maneuvering for position, each fearing invasion from across the river, each fearing their neighbours more. Intrigue, dissent and rebellion are on all sides.

The Elves and other non-humans are still suffering under decades of repression, and growing numbers join the commando units hidden deep in the forest, striking at will and then dissolving into the trees. The Magicians are fighting amongst themselves, some in the pay of the kings, some sympathetic to the elves.

And against this backdrop of fear and contempt Geralt and his lover Yennefer must protect Ciri, orphaned heir and sought by all sides. For the prophecy rests on her, and whether she lives or dies she has the power to save the world - or perhaps end it..  




After reading previous books, this book I really don't know why felt like a huge filler. There was barely any story progress here. It was same annoying confusing story telling going on here. By far the nomenclature of everything has annoyed me the most. I feel that would be more of a personal preference.

Ciri is on her journey, Geralt is on his journey, Yennefer feels like is forced in between along with a ton of characters. I don't know what dryads and elves are doing. Dandelion is as usual lucky one who is saved from every situation without any scratches.

I am really doubtful whether I'll pick up books further in this series. I really want to know what happens ahead after the wonderful introduction of Geralt but here it feels overloaded with ciri.

I really would not recommend this book unless and until you want to finish reading this series before Netflix adaptations come out.

Link : https://amzn.to/2ODkj6t



Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Learn Python With Dhawal - 17 - Handling Errors and using Exceptions


Previously, we learnt about File handling. Did you try something else apart from the course instruction program? If you have, there'll be a fair chance that you must have encountered some sort of errors. Debugging for errors is one thing that we always have to do as a precaution. But what if there are case scenarios where there's some issue with a portion of code, but that code might be important or you can still run the program successfully after failure of one particular method.

Error Handling

Imagine there's a calculator program and you want to take input amounts from the users, but the user didn't give any input or say there was a failure in catching input or maybe wrong input was given. What would you do? In the previous coding examples that we have done, they program will simply throw an error and would stop it's execution.

In some scenarios we can handle complete halt of execution but imagine a code written to run atomic cooling plants or power plants or even hospital ventilation systems or say power grid? Running into some stupid error might result in complete halt of the execution and might result in huge losses of both life and finance.

To handle errors programmers often build some mechanisms but it's not possible that we can always have a mechanism in place. So to counteract with such situations we have something called Error handling mechanisms. We use exceptions to just get past around some situations still making the code finish it's execution and turn get into a stable state.

For example : Imagine you wrote a code for running a banking application. There was a power loss and before that you had sent the message to send the money from account A to B, but in midst, before the message could reach B, there was a power failure. Now the A would assume that he has sent the money but B will still be waiting for money. This can result in chaos if that happened at a larger level. (I know there will be database management here, but just giving an example, so don't overthink). To counteract such cases, we create a kind of a failsafe mechanism. There we create an exception.

What is an Exception?

Just like the name suggests, we give error situation an exception and allow the code to run further. It's like giving it an excuse to continue without total halt of the system. Continuing from the same above example of a banking scenario.

Now, after the power has been restored, we had built in an exception inside the program. If something like that had happened and we received no acknowledgement from B about receiving the money, we would reinstate the balance amount in A's account and then sent the money again or just inform the details about the failure to the server manager and user stating about the failure of the transaction.

Further it would depend on the build of the system to either resend the request or cancel the transaction altogether.

Using Exceptions in Real time Code.

Imagine in the previous file handling program. You wrote a code to open a file and read it. Now, if the file didn't exist, you'd get an error and program execution would be halted. Now, we can write a code that if the file previously mentioned don't exist, we can give user an option to create a new file and then read the it using the program. We do it with the help of the 'try....catch/except' blocks. Where 'try' is used to try a particular code and 'catch/except' is used to mention incase the code inside the 'try' block failed execution. There's also an option of a default code block which can be called either 'default/finally' this block of code is executed in all case scenarios irrespective of the execution of try and catch blocks.

Syntax : 

try :
    statement1
    statement2
except nameOfError:
    statement3
    statement4
finally :
    statement5
    statement6

Here, inside the try block you'd write all the code that you have doubt about having a failure. Now with the except block you can counter all the errors at once or counter exceptions depending on their type. If you don't mention the name of the error you want that particular block of except code to handle then it'll be used in all case scenarios of failure. It might not be smart as at times knowing what's the issue can be a lot more helpful and can be remedied. For example, if user didn't enter their name then you can use default name temporarily and then alert user about it or if you are using a calculator program then you can use 0 or 1 depending on what the previous operation was and alert the user about data input failure.

You can also add an 'else' block here to be executed in a scenario where no errors have occurred. Not sure where this would be useful but it's a handy thing to know. Now before we begin actual coding, I want you to try the name of the error where file is not been found. Open a new python file, write a code to just open a desired file but which doesn't exist. See the output and copy the error name and save it somewhere just incase for our code.

Input :

import os
try :
    f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","r")

except  FileNotFoundError:
    print ("The desired file is not found, we will create one for you instead.")
    f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","a+")
    print("A new file is created")
    f.write("Hello World!")
    print("Message is written in it.")
finally:
    f.seek(0)
    print("The cursor is moved to beginning of file")
    print(f.read())
    print("The message is read")
    f.close()
    print("File is closed")
    os.remove("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt")
    print("the file is been deleted")
    
   
Output :


  1. The desired file is not found, we will create one for you instead.
  2. A new file is created
  3. Message is written in it.
  4. The cursor is moved to beginning of file
  5. Hello World!
  6. The message is read
  7. File is closed
  8. the file is been deleted
Explanation :

Now, I have tweaked this code a little bit. In previous chapter we were using directly appending mode to read-write a file. But if we are just reading a file and not bothered about writing it. This is the error handling mechanism we can use. Here, we have previously found out the 'FileNotFoundError' is the one we want to handle and leaving the other errors aside for later.

We use the try block and put the read file statement inside it. But when that reading a file gives an error which we have previously expected, we already had corrected exception kept in place for it. So the instead of programming blindly for every possible exception, we targeted a thing that we could remedy.

We just created a file, wrote into it and rest is the standard procedure as we know from the previous program.

Note : We can use console log statements instead of printing the states but this is for the further advanced chapters. For now, we have used print statements as a part of logging mechanism to know what's happening in the program.

Input :

try :
    a=int(input("Divide 10 by : "))
    b=10
    a=b/a
    print(a)
except ZeroDivisionError :
    print("You can't divide by zero, enter a valid number again")
    a=int(input("Divide 10 by : "))
    b=10
    a=b/a
    print(a)
except Exception as e:
    print("Some error occured\nError Description : "+str(e))
finally:
    print("Sorry, run the program again")

Output :


  1. Divide 10 by : 
  2. Some error occured
  3. Error Description : invalid literal for int() with base 10: ''
  4. Sorry, run the program again
Explanation : 

Here we have added a parameter to catch other errors than the ones we had previously planned for. Here when someone forgets to enter and just presses enter, it'll catch the particular exception and then display the error without stopping the execution of your code. We just create an object of the main 'Exception' class as 'e' and then use it to catch the errors. We later just print the description of error and finish execution of code without any errors technically.

Input :

Here we just added an if statement inside out try block after the input statement to give an error if someone entered a negative number in the previous code.

try :
    a=int(input("Divide 10 by : "))
    if (a<0):
        raise Exception("Enter anything else please!")
    b=10
    a=b/a
    print(a)



Output :


  1. Divide 10 by : -10
  2. Some error occured
  3. Error Description : Enter anything else please!
  4. Sorry, run the program again

Explanation :

Now, there will be times when you want to raise/throw exceptions of your own in certain cases, for example say while sending amount in a bank transaction, it shouldn't be negative. You can't send someone -100₹ or -100$ per say. That would be a joke and a disaster if someone finds that bug out. So in such case scenarios we write custom exceptions. To raise/throw a custom exception, we have a keyword 'raise' here in python. We will write a conditional statement and depending on that we will decide whether to throw/raise an exception or not. We can throw/raise any exception we want, here I have raised a custom exception but you can find out exceptions of your choice and deploy them as your wish and will.

With this I hope you had grasped all the basics about exceptions and how to handle them if you come across them during your coding  adventures. Feel free to try out some custom exceptions and experiment around a bit here and there.




<< PREVIOUS CHAPTER || NEXT CHAPTER >> --INDEX--


~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~


Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Learn Python With Dhawal - 16 - File Input and Output


I know I have been slow with the updates but I have been working on an idea to build a project for this little course book of mine. I had to sort through a lot of ideas on what to make the project on to keep it simple, fun and yet covering all the major aspects of a proper application development.

Then I realised I haven't posted about how to read write a file yet. So before we jump on the bigger projects, here are a few basics more here and there to finish. So let's begin.

File Handling

File handling is one of the most primitive and basic tasks that you should know to perform if you want to move ahead into application development using python. As the title suggests there's not much mumbo jumbo to learn on the coding spectrum but here, we have to cover up a lot on the theory part.

File permissions

Before we move ahead and start operating on a file. We need to know what are the file permissions and how to deal with them.

There are mainly 3 types of file permissions :

I am using the word 'mainly' because the words indicating the permission or some custom permissions might arise depending on what you've been working on. But here we would go with the vanilla ones.


  1. Read : This permission as it says, allows one to read the file.
  2. Write : This permission allows one to write the file.
  3. Read and Write or Append : The name of this permission can be seen different depending on the systems you are using but it simply allows one to access and write the content in the file.

File Operation Modes :

Here we have just like the permissions we have 3 modes in basic to perform various operations on the files.


  1. Read : When you open a file in this mode, you can read the contents of the file. This mode will give you error if the file you want to read doesn't exist.
  2. Write : When you open a file in this mode, you can write your desired content in the file. But be careful while opening a file in this mode as when you open the file in write mode, the previous content of the file gets deleted. The new content of the file will be whatever you entered after the opening the file. This will create a new file if the file you specified doesn't exist.
  3. Append : When you open the file in this mode, you can write your desired content in the file. The difference here is that if your file previously contained anything, it won't be deleted and the new content will be just written after where the previous content ends. If your file didn't have anything written inside then it will just write down new lines as you enter them. This will create a new file if the file you specified doesn't exist.
File Operations :

Open : As the name suggests, this is used to open the file to start working on it. If the name of the file you point at doesn't exist, it might throw an error or create one depending upon the mode you used to operate on the file.
Close : This is very important step, as most forget to close the file after operating on it. If you don't close the file after operating on it, it might cause errors in file or make the file entirely unusable or might just not save the content you had entered.
Create : This will be for creating a file.
Delete : This will be for deleting a file.


File Handling in Python

Now, above we discussed basics of file handling. Each language has its own way of handling files. Here we will discuss actual operations and modes in python to perform various file operations.

Mode Function
r Read the file, default value if you don't specify the mode.
w Write file, creates a new file if the mentioned file doesn't exist. Also, if existing file contains anything, that would be deleted.
a Write file, creates a new file if the mentioned file doesn't exist. Also, if the existing file contains anything, it would continue writing where the previous content ends.
x Create a new file and opens it, returns error if file already exists.
tOpens file in text mode, default value
b Opens file in binary mode. It's useful for images.

Open : This method uses two parameters, one is the location of the file in your storage and second is mode you want to open the file in.

Syntax :  open("fileaddress.extension", "Mode you want to open your file in")
example - f = open("demofile.txt","r"). This will open a file in read mode. Here, f is the file object created to operate on the file. Python follows OOPS concepts, hence we have to create object of file to use it.

Close : This method uses no parameters or arguments.

Syntax :  "fileObjectName".close()
example - f.close()

Input

import os
# First we will create a file.
f = open("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt","a+")
print("A new text file is created and opened in append+ mode")
# Writing in the file
f.write("Hello World! This is my first created file")
print("Message is written in file")
# Reading the written text
print("This is the position of cursor in the file : "+str(f.tell()))
f.seek(0)
print("We changed the cursor position to beginning,so now we can read the file.")
print(f.readline())
print("Message is read")
# Closing the file
f.close()   
print("File is closed")
# Delete the file
os.remove("C:/Users/joshidhawal/Documents/Git/learn-python-with-dhawal/testfile.txt")
print("File deleted")

Output

  1. A new text file is created and opened in append+ mode
  2. Message is written in file
  3. This is the position of cursor in the file : 42
  4. We changed the cursor position to beginning,so now we can read the file.
  5. Hello World! This is my first created file
  6. Message is read
  7. File is closed
  8. File deleted


Explanation :

First we create and open the file. Now if we just had to create the file we could've used the 'x' permission to create the file. We can add '+' to add more functionality. You can read more about the file operation modes by clicking here.

But here we used 'a+' as the file operation mode, meaning we are opening it as an append mode and allowing some more permissions to it. We are also printing the state of the file operations after each operation is performed. This is not needed but it can be used as a method of debugging or some sort of confirmation that the particular operation is been performed. Since Python is an interpreted language, all the print statements followed by the operation will indicated that the particular operation is been performed successfully.

Next we use the 'write' method to write into the file. After that we seek the current position of the cursor in the file. Now, remember that if you have to write again, it'll start writing after the previous position as you haven't closed the file yet. So if you wished to read whatever you've written, you'd have to get the cursor back on the the starting position.

Hence to do that we have used 'tell' method to show the current cursor position followed by using 'seek' method to move the cursor to the file beginning. Hence then we could read the message that we had written in the file. We read the content using the 'readline()' method since it's only one line. If we wanted to read the whole file and there was content of multiple lines or say maybe a paragraph we would be using 'read' method instead.

We close the file after performing the operations using 'close' method. Now the next step we take is totally optional and for educational info. At times you don't want to keep a particular file or delete it. If you run this program it won't give you any error as it is using append mode. But say, if you wanted to use create mode and then just leave file as it is and there was some file with the same name which you had created previously, you'd have to delete it.

So to delete the file we have created, we import the 'os' package and then use it to remove the file we had created.

~*~*~*~

This program gave you idea about how to perform most basic file operations using python. To know more you can refer the linked python official documentations or just try out yourself by experimenting and googling. It always helps to search and find out new tricks.

Try out yourself :

Write a program to create a file if not in existence. If it exists, open it and start writing information where the previous content had finished. At the end it should give read the whole file again. It should ask if you want to keep the changes or not. If yes, the previous message should be saved and file should be closed or else the file should be reverted to it's previous state.

<< PREVIOUS CHAPTER || NEXT CHAPTER >> --INDEX--


~*~*~*~

This series is totally authored by me (Dhawal Joshi). Any similarities found on the text, or codes or anything is purely accidental. All the sources of reference will be mentioned, linked and will be given the proper credits. If I miss anything or there's anything wrong, feel free to comment or send me an email and I'll try to edit it out. I am not a Python expert, I am sharing whatever I have learnt on my own and with a few sources around to refer from which will be mentioned. Also feel free to share this series with others so most can benefit out of it.

~*~*~*~




Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Review : The Forgotten Army - Amazon Originals



The Forgotten Army
My Rating : 5 of 5 stars
Link : https://amzn.to/3aWpaJJ


About : The Forgotten Army' is the dynamic story of Lt. Sodhi and his daredevil band of men and women who fought a heroic battle for the independence of India as part of the Indian National Army which was forged out of British defeat in Singapore during WWII and led by the charismatic, indomitable Indian leader Netaji Subhash Chandra Bose.


The story-telling happens here from the POV of a soldier. I'd have loved to see more about how the things had actually worked out but this is a good account as well. The story here is extremely well presented. They masked the story with layers. The main layer telling the story of the Azad Hind Sena or the Indian National Army as they say in english. Secondary layer being the love story of soldier and his female companion.

Now, I'd try to keep this as low in spoilers as possible but since this is an already well established historical account there'd be hardly any portions accounted as spoilers for this series. Well, yes there's a dual storytelling happening in the series. Each episode shorter than your Netflix series( telling this because this would affect your binging habits) is equally rich in content even being short. They have named it 'Season 1' so I am hoping there'd be some upcoming future seasons in production line.

Coming back to the story, I loved it. It was a great dramatic mixture with the historical accounts. I felt I was kinda back in that era. The cinematography is really amazing and the war scenes are well shot. There's drama but its like that perfect amount of salt in food, not too much and not too less. Although, as I said in the first line of the review itself, I would've loved it more if there was more part on story of how Netaji joined INA or took command of it. There are bare bone glimpses of it.

Now, if you don't want to read a rant you can skip this paragraph. I have so many bones to pick with the people who did injustice to these people. Here, I feel Japanese army was much better in comparison to our own people. It was a shock to find out that after independence none if these soldiers were taken into real indian army, neither they were provided with any compensation or pension. Like, how ungrateful can you be? These people laid the foundation of freedom and their actions were neither remembered nor they were given enough credit? Their existence just remained to a paragraph in the history textbooks ( at least in the ones when I had done my schooling ). There's a memorial in Singapore and they are barely even remembered here in India? What kind of a sick joke is that?

Nevermind, the rant would never suffice but surely, the history is history and as the soldier said in the series when his grandson asked, ' what did you get doing all this?' his answer was, ' That depends on your generation. We did what we had to do, now you'll decide whether you'd cherish it or let it go in vain.'

It's a must watch series which I'd surely recommend. Brilliant cinematography, amazingly emotional soundtracks and a honest story.




Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Review: Harry Potter and the Deathly Hallows



Harry Potter and the Deathly Hallows by J.K. Rowling
My rating: 4 of 5 stars
Link : https://amzn.to/2O4QM87


Book Description : 

Harry Potter is leaving Privet Drive for the last time. But as he climbs into the sidecar of Hagrid’s motorbike and they take to the skies, he knows Lord Voldemort and the Death Eaters will not be far behind.

The protective charm that has kept him safe until now is broken. But the Dark Lord is breathing fear into everything he loves. And he knows he can’t keep hiding.

To stop Voldemort, Harry knows he must find the remaining Horcruxes and destroy them.

He will have to face his enemy in one final battle.  




There's a lot of book which makes it super had and confusing at the same time to write a review about.

There's a lot of plot on-going here. A lot od details and well certainly I feel this was somewhat better than movie counterparts. Although, I felt some scenes were too hyped up where everyone was almost overpowered and then suddenly powerless at the same time. It was a weird sense of conundrum.

One point is when Harry becomes the master of death after dumbledore. I enjoyed the backstory about dumbledore and how both he and voldemort wanted to master the death but voldermort chose dark arts and dumbledore went after the hallows.

That part I felt was seriously over powered but it was kinda enjoyable. There was lack of excitement until the climax and mostly it was okay but can get boring as well, depends on person reading.

Although, I feel this book was a fitting conclusion to the series. I wish there was more part on what happened after this huge war. It shows harry and ron's kids going to Hogwarts but there's not more information on it. I would've loved more on that part.

I feel the aftermath of a mayhem is more important in a story than the end of mayhem itself. It was there but wasn't satisfactory.

I would recommend it since its the last book in HP series. There's quite nonsense which you can skip if you want in the book but, can be fun if you want to dive deep about the life of Dumbledore.

Link : https://amzn.to/2O4QM87



Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :

Review: Harry Potter and the Half-Blood Prince



Harry Potter and the Half-Blood Prince by J.K. Rowling
My rating: 4 of 5 stars
Link : https://amzn.to/2SvTTEJ


Book Description : 

When Harry Potter and the Half-Blood Prince opens, the war against Voldemort has begun. The Wizarding world has split down the middle, and as the casualties mount, the effects even spill over onto the Muggles. Dumbledore is away from Hogwarts for long periods, and the Order of the Phoenix has suffered grievous losses. And yet, as in all wars, life goes on.

Harry, Ron, and Hermione, having passed their O.W.L. level exams, start on their specialist N.E.W.T. courses. Sixth-year students learn to Apparate, losing a few eyebrows in the process. Teenagers flirt and fight and fall in love. Harry becomes captain of the Gryffindor Quidditch team, while Draco Malfoy pursues his own dark ends. And classes are as fascinating and confounding as ever, as Harry receives some extraordinary help in Potions from the mysterious Half-Blood Prince.

Most importantly, Dumbledore and Harry work together to uncover the full and complex story of a boy once named Tom Riddle—the boy who became Lord Voldemort. Like Harry, he was the son of one Muggle-born and one Wizarding parent, raised unloved, and a speaker of Parseltongue. But the similarities end there, as the teenaged Riddle became deeply interested in the Dark objects known as Horcruxes: objects in which a wizard can hide part of his soul, if he dares splinter that soul through murder.

Harry must use all the tools at his disposal to draw a final secret out of one of Riddle’s teachers, the sly Potions professor Horace Slughorn. Finally Harry and Dumbledore hold the key to the Dark Lord’s weaknesses... until a shocking reversal exposes Dumbledore’s own vulnerabilities, and casts Harry’s—and Hogwarts’s—future in shadow.  




This was a really good read. I really don't have much to comment on this part of the series. The story progressed and dived deep into the life of the main antagonist. It gives an interesting insight although into the life around hogwarts.

It was very interesting to know the backstory of how did voldemort rose into the power that he had at that time when Harry was in hogwarts.

There was action in the end of the story while most of the other portions were well balanced and enjoyable.

Some portions did feel unnecessary but I don't mind as they didn't stretch out for that long. I felt really bad when dumbledore was killed. But it was kind of expected as if Harry had to take up the lead than the current leader had to be stepped down. Considering dumbledore the master magician and owner of the elder wand, it would have been stupid to just sideline him without killing. They indeed killed of the character but it didn't felt stupid. There was ample of background and reasoning to make it good.

There was interesting twist in Ginny-Harry and Hermione-Ron coupling. I enjoyed it and felt it was well deserved.

I'd recommend it to read for sure.

Link : https://amzn.to/2SvTTEJ



Do comment and share your thoughts about it! I'd love to know what do you think. Also, I'd keep updating it quite often so do follow the Website to get all the updates by clicking here.

Also, a minor headsup.... Obsessed is free to read on Kindle Unlimited! Do check it out. I'd be glad to read your reviews!
Share :