Categories
Development

Python 3 Try Catch Example

No Try Catch but Try Except

In other programming languages, the keywords when referring to try and except blocks of code are “try” and “catch”. In Python 3, the keyword for “catch” is actually “except”. So, it is called a Try and Except block of code. But what does it do?

Example of a ValueError Exception

Sometimes, when you want to do an operation but you don’t know if it’s going to work or not, we use exception handling.

As a very basic example, consider that we are validating a user’s input.

text = input('age: ')

Say, the age has to strictly consist of numbers and not text or a string of numbers. In that case, we introduce a new variable. We can call this variable number and do the following to convert our text into integers and then print this to the screen:

text =input('age: ')

number = int(text)
print(number)

After doing all this, when we type in “hey” in the username slot, the program will crash with a ValueError: invalid literal for int() with base 10 ‘hey’ error. Because it is unable to convert this text into numbers.

In this case, we use a try and except block to tell users to input something else rather than having the entire program just crash. We can add the try block to our code this way:

Catching a ValueError Exception in Python 3

If you run the code with only try: without an except: command you will get a syntax error at compile time saying “SyntaxError: unexpected EOF while parsing”.

text = input('age: ')
try:
    number = int(text)
    print(number)
except ValueError:
    print("hey age should be a number")

The above shows how you can catch a ValueError. But what if you want to catch a generic error?

How To Create your own Exception in Python3?

You need to create a class as follows and inherit from Exception or BaseException.

class ShouldBePositive(Exception):
    pass

The above is the bare minimum for an exception.

How To Add Multiple Except Clauses and Chain Exceptions?

You can add multiple except clauses and also chain exceptions by Raise-ing an exception as follows:

class ShouldBePositive(Exception):
    pass

text = input('age: ')
try:
    number = int(text)
    print(number)
    if number < 0:
        raise ShouldBePositive
except ValueError:
    print("hey age should be a number")
except ShouldBePositive:
    print("Age can't be negative my dude")

How To Catch All Exceptions In Python 3?

In Python 3 all Exceptions inherit from the base class BaseException. The builtin Exceptions like ArithmeticException inherit from Exception which then inherits from BaseException. So you can do the following to catch all exceptions.

class ShouldBePositive(Exception):
    pass

text = input('age: ')
try:
    number = int(text)
    print(number)
    if number < 0:
        raise ShouldBePositive
except BaseException:
    print("something went wrong")

Final Words

This is a small note on exceptions but I would suggest you do further reading on its intricacies at https://docs.python.org/3/tutorial/errors.html and also if you want to learn how to test exceptions in unit tests checkout: https://docs.python.org/3/library/unittest.html

If you would like to learn more Python check out this certificate course by Google: IT Automation with Python

Categories
Development

How do I find the instance of a class in Python?

isinstance allows you to check whether an object belongs to a certain class or subclass. This function basically answers the question, “does it belong to an instance or not?” where the subclasses can be either lists, dictionaries, strings etc.

How To Use isinstance() Function in Python

>>>isinstance(53, int)
True

Note that in the first argument, we check the object itself and in the second argument, we check if the object belongs to the certain class we have put in. The answer comes out to be true as 53 is indeed an integer.

How To Check If Variable Is A String In Python?


This is a simple enough format but of course, one has to obey the rules of syntax. For example, if we want to check if 53 is a string (denoted as ‘53’ in code if it is a part of string) and we write the following:

>>>isinstance(53, str)
False

The answer will come out to be false, but if we write the following:

>>>isinstance(‘53’, str)
True

The answer will come out to be true.

How To Check If Variable Is Instance Of Multiple Classes?

Another interesting use of this function is to use it as a tuple of instances. Basically, the question, “is the object an instance of float, integer, or string?” is answered when we write.

>>>isinstance(53, (float, int, str))
True

Here, the answer comes out to be true because 53 is indeed an integer. Now the above is condensed version of writing the following long and tedious code:

>>>isinstance(53, float) or isinstance(53, int) or isinstance(53, str)
True

Semantically, both are identical and will give the same result but the latter is unnecessarily long, and is harder to write than the former.

How does isinstance work with inheritance?

You can use isinstance to find if an object is from a class or that class has inherited from another class (parent class). For example check below:

class Parent():
    pass
class Child(Parent):
    pass
child = Child()
parent = Parent()
print(isinstance(child, Child)) #True
print(isinstance(child, Parent)) #True
print(isinstance(parent, Child)) #False

In short, an object will be an instance of a class it has inherited from.

If you would like to learn more Python check out this certificate course by Google: IT Automation with Python

Categories
Ideas Security

Secure Alternatives To WhatsApp

Introduction 

Do you know from May 15, WhatsApp will start exchanging some of its users’ data with the joint corporation, Facebook, for linking WhatsApp experiences with other Facebook company products such as Messenger, Instagram, etc.? This news has created a great buzz among cybersecurity experts, as this means a less secure service with more than 1.5 billion users worldwide.

If you are suffering from WhatsApp overload or do not like privacy concerns, these are some secure alternatives to WhatsApp that you can pick.

Signal

Signal Foundation is the leading organization behind WhatsApp Messenger and Facebook Messenger’s end-to-end encryption technology; it also offers a secure alternative to WhatsApp, known as the Signal private messaging app. You will be amazed by its security benefits. It provides screen security (stops screenshots from being taken by anyone) and many more services.

When Elon Musk, founder of Tesla and Space X, tweeted “Use Signal,” it saw an unexpected spike in downloads.

 Signal provides backups, calls, group calls, and all other data options in the app with encryption. Even essential files that you send through Signal are protected. Besides, it does not link any data to your identity, according to Apple’s App Store listing.

One of Signal’s main drawbacks is that you need a phone number for creating a new account. Also, you won’t have the customization levels you usually find as a WhatsApp consumer. That means no chat wallpapers option for conversation. Even still, it’s the perfect alternative to WhatsApp. It is free for Android, iOS, and Windows.

Telegram

Perhaps the most valuable and secure option to WhatsApp is Telegram. Its setup, for instance, is very easy to use. You will quickly learn it. And above all, it nearly has the same features such as voice and video messages, a login system through phone numbers, stickers, emoji, chatbots, and group chat options.

For all your networking requirements, Telegram has an online chat program. Most importantly, Telegram protects your privacy with end-to-end encryption. Telegram is free and available for Android, iOS, Windows, macOS, and Linux.

Threema

This Secure alternative to the WhatsApp app is also open-source, encrypted by E2E, and, like Telegram and Signal, deletes messages right after they are delivered from its servers. It verifies users through QR codes and does not require any phone number or email to sign up, allowing them to use anonymously.

It provides texting, voice, video calls, and services for its users. Its company’s headquarters are located in Switzerland, making the platform fully compliant with the European regulations on privacy.

The app’s main drawback is that you have to pay for it, but this enables its users to maintain the platform without advertisements or data collection. It is not free and available on iOS, Android, and the web.

Wire

The wire is at number 4 in our list of a secure alternative to WhatsApp. A wire is an encrypted messenger with options for messaging. It provides you voice chat, text, and video, options just like WhatsApp. It also has the option of GIFS and file sharing.

Unlike WhatsApp, it can synchronize across devices and support multiple accounts, especially when you want to keep your communications separate.

It also uses its open-source encryption protocol called Proteous, but based on both Signal and WhatsApp’s Signal protocol and undergoes periodic audits to keep it safe. A wire is available for Android, iOS, Windows and is free to use.

Utopia

UTOPIA is a complete kit for secure instant messaging with encrypted email, anonymous payments and even private web browsing. Text, voice and emails sent are encrypted. The best part might be that the service actually is completely peer to peer so there is no central server (both in transmission and in storage which is amazing). It is designed in a way that it is not possible to find the IP Address or Identity of a user.

Utopia can run on Windows, MacOS and Linux.

Conclusion

It’s become quite evident in this era of Internet privacy that if there is no product, you and your data are the product. That’s why you can use these secure alternatives to WhatsApp applications to make your life easy by taking your privacy back into your hands.

Categories
Security

Tips to Protect Yourself from Cybercrime

HOW TO PROTECT YOURSELF AGAINST CYBERCRIME

The damages from cybercrime is predicted to cost $6 trillion dollars in 2021. This statistical analysis could only mean one thing; we all need to get educated about cybercrimes and how to be protected against cybercrime. In this article, I’d put you through the nature of cybercrime, and how you can defend yourself against cybercrime. Don’t fret, it’s not rocket science, the information in this article is simple and easy to understand.

What is Cybercrime?

You can’t make much progress with protecting yourself from cybercrime if you don’t know what cybercrime is all about. Cyber crime is a criminal activity that targets/uses your computer, your network or your networked device. Keywords to note: Target or Use, this summarizes the two ways cybercriminals employ to perform their attacks. Your computer and networks are vulnerable to cybercrime if you do not protect yourself. Cybercrime isn’t limited to financial fraud, it covers the scope of reasons that are personal or  political to the cyber criminal. Cybercrime takes various forms which may include any of the following:

  • Theft and sale of corporate data.
  • Cyberspionage (hackers access government or company data).
  • Identity fraud (your personal information is stolen and used).
  • Theft of financial or card payment data.
  • Cyberextortion (they threathen you with an attack and demand money to avert the attack).
  • Ransomware attacks (can employ cyberextortion).
  • Email and Internet Fraud.
  • Theft and sale of corporate data.
  • Cryptojacking (cyber criminals mine cryptocurrency using resources they do not own).

Examples of cybercrime include:

  • Virus and Malware are targeted at damaging computer devices or stopping them from working. Malware is also used to steal data from computers.
  • Denial-Of-Service attack: This is when a service provider is unable to provide service to customers because of a cybercrime attack.
  • Unauthorized use of people’s computer or network to perform illegal transactions, store illegal information, and spread malware.
  • Phishing campaign: This is when cybercriminals send messages or emails that trick you into performing an action that undermines your security. A more targeted form of phishing is called spear phishing, it makes you undermine the security of your company or government by sending information that uses the identity of higher authorities in the organization.

Some cybercrime attacks are significant in history. One of them is the Wannacry ransomware that locked out over 230,000 computers in the world from their users/owners. They demanded that a bitcoin payment be made to regain access to their computers, $4 billion dollars was carter away-with from this attack. Another significant cyber attack in history is the phishing campaign scam in 2018. Emails were sent to football fans to entice them into performing some activity to watch the world cup live in Moscow. Everyone who performed this enticing task had their security breached and personal data stolen. In 2017 the UK lottery website was attacked, this Distribution Denial of service attack locked out citizens from partaking in the lottery.

Tips to Protect Yourself from Cybercrime

You wouldn’t want to wait until you’re a victim of cybercrime before you tighten your loose ends. Here are proven tips to keep you out of risk of cybercrime attacks:

  1. Do not give out personal or confidential information until you have verified the identity and confirmed a secure communication channel. A person’s communication link with you may have been hijacked, if you can’t see or put a call through to the person, don’t exchange important/confidential information.
  2. Always update your software and operating system. As basic as it sounds, these updates contain security patches to prevent cyber attacks.
  3. Recall the phishing technique? To reduce the odds of being a victim, never open attachments in spam emails. Let’s take it a step further, do not open mails from a sender you do not know, and don’t use links contained in a spam mail.
  4. Update your anti-virus service provider and use trusted and comprehensive service providers. Some anti-virus service providers people use are not comprehensive enough or they are not even authentic. If you can afford paying for premium packages to protect your computer and data, please do.
  5. Reinforce your security when using online payment options. Keep tabs on your bank statement or alerts so you can stop any unauthorized transactions before they are completed.
  6. You can encrypt your network with VPN and take extra security measures to keep your network safe from cyberattack. Take cyber attacks more seriously, and ensure you’re abreast of latest breach techniques used by cyber criminals.
  7. Do not talk to anyone who claims he’s calling from your bank or company you’re affiliated with. Drop the call, use a different number to call the official line of the company to be sure you’re not under cyber attack. If you have the time, you’re better off appearing physically to solve whatever issues need your attention.
  8. Pay attention to the passwords you choose to use, ensure they are difficult to decipher and keep them far from the reach of people you don’t trust. Whether you trust them or not, a password isn’t for two people, keep your passwords undisclosed.
  9. Stay clear from websites and URL that do not look legitimate. Watch out for indication from your browser on the inconsistent nature of a website/URL. Sometimes your browser shows a caution. As a rule of thumb never trust a website or URL with your personal information if it uses a http transfer protocol. A HTTP can be intercepted but a HTTPS transfer protocol is protected, websites that use HTTPS usually show a padlock/green access bar to show that you’re secured. You can visit the google transparency site to weigh the safety of a website. You can also look out for websites that have seals, seals shows a secured defense from reputable security companies. Have you accessed a site and you saw Norton security logo, Macafee, or any other reputable cyber security organization? That’s a seal. Whether a site is secure or not, never trust them with your data. You’re better off not taking risks, cyber criminals are finding better ways to breach secured channels where people don’t expect to be at risk of cyber crime.