Python Lesson 15: Exception Handling

Advertisements

Hello everybody,

Michael here, and today I thought I’d start a new series of Python lessons. In this post, I’ll cover exception handling in Python.

For those who are unfamiliar with exception handling in programming, it’s the process of handling errors that may arise in your code (I covered exception handling in Java in the post Java Lesson 12: Try-Catch & Exception Handling).

Exception handling in Python is quite similar to Java exception handling but instead of the try-catch statement that Java uses, Python uses try-except. Let’s see some Python exception handling in action:

try:
  print(4/0)
except:
  print("Divide by 0 error!")

Divide by 0 error!

In this simple error-handling example, I place the code I want to error-test in the try block and I place the exception I want to display in the except block.

What happens if the code has no errors? How should you handle this? Here’s how:

try:
    print(4/1)
except:
    print("Divide by 0 error!")
finally:
    print("Success!")

4.0
Success!

If the code in your try block doesn’t have any errors, you should include a finally block with code to execute the rest of the code. The finally block will execute regardless of the results of the try and except blocks so even if the try block caught an error and the except block gets executed, the finally block will still be executed.

Now, let’s see what happens when you don’t include a try-except block in your code:

print(4/0)

---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-9-4bf1a7e4a751> in <module>
----> 1 print(4/0)

ZeroDivisionError: division by zero

If you don’t have a try-except block in your code and the program has an error, the program simply crashes and throws an error. With a try-except block (or a try- except-finally block) in your code, you can catch errors that your program might raise and keep the program running regardless of how many errors it catches.

Now, what if there were several possible errors you wanted your code to catch? In Python, you can have as many except blocks as you want, but you’d need to put each possible error in it own except block. Here’s how to utilize several except statements in your code:

try:
    print(3.5/0)
except ZeroDivisionError:
    print("Divide by 0 error!")
except:
    print("No floats allowed")

Divide by 0 error!

In this example, I have a try block along with two except blocks. The first except block catches any divide by 0 errors (referred to in Python as ZeroDivisionErrors) that are found in the try block. If there are no divide by 0 errors, the second except block will run IF there are float values in either the dividend or the divisor (I didn’t configure any input validation in my code but you get the point).

Last but not least, is it possible for you to raise an exception based on a specific condition (like if something happens, raise an exception) ? Yes, and here’s an example of how to do so:

password = str(input("Please create a password: "))

if len(password) < 8:
    raise Exception("Please use 8 characters or more for your password!")

Please create a password: hola
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
<ipython-input-14-3ae89fecd594> in <module>
      2 
      3 if len(password) < 8:
----> 4     raise Exception("Please use 8 characters or more for your password!")

Exception: Please use 8 characters or more for your password!

In this example, the user is asked to create a password and if the password is less than 8 characters, an exception is thrown. Since the password I used for this example-hola-only has 4 characters, the exception was thrown with the custom message “Please use 8 characters or more for your password!”.

  • If you want to raise an exception based off of a specific condition, use an if statement with the raise keyword, not a try-except block.
  • You don’t necessarily need a corresponding else statement if you’re raising an exception from a condition, but you should use an else statement if you want a block of code to continue running if no error is thrown.

Python also has plenty of built-in exception types that you can throw based off a certain condition. Here’s an example of one of Python’s many built-in Exception types at work:


username = "employee1"
password = "companywifi"
​
usernameInput = str(input("Please input your username: "))
passwordInput = str(input("Please input your password: "))
​
if (usernameInput != username) & (passwordInput != password):
    raise PermissionError("Incorrect username and/or password!")
else:
    print("Welcome")

Please input your username: GoBrowns2020
Please input your password: ILUVWORK
---------------------------------------------------------------------------
PermissionError                           Traceback (most recent call last)
<ipython-input-18-fd8de8965591> in <module>
      6 
      7 if (usernameInput != username) & (passwordInput != password):
----> 8     raise PermissionError("Incorrect username and/or password!")
      9 else:
     10     print("Welcome")

PermissionError: Incorrect username and/or password!

In this example, I created a simple login authenticator where a employee of a company enters their username and password to access their work laptop. However, if they don’t use the preset username/password combo, then a PermissionError is thrown and the message “Incorrect username and/or password!” is displayed. However, if they use the preset username/password combo, the message “Welcome” is displayed and the user is logged on to the laptop.

  • If you ever needed a simple login authenticator for any program you’re creating, this code will certainly come in handy-customize it however you like!
  • As I mentioned earlier, Python has plenty of built-in exceptions that you can use-here is a link to the documentation that lists all the Python exceptions available https://docs.python.org/3/library/exceptions.html#os-exceptions (this link is for Python 3.9.2, which is the latest version as of March 2021).

Thanks for reading,

Michael

Java Program Demo 3: More Fun With Method Making, Exceptions, Recursion, and Encapsulation

Advertisements

Hello readers,

It’s Michael, and today’s post will be another Java program demo utilizing the concepts covered in the previous four posts (encapsulation, method making, exceptions, and recursion). I thought this would be a good post to show more examples using these four concepts (as well as build upon the other concepts I discussed in the previous 9 Java posts, because after all, the harder concepts in Java build upon the easier concepts).

First let’s do an encapsulation demo. Here’s our method class (the one that has our getter and setter methods):

package demo3;

public class Demo3
{
private double surfaceArea;
private double volume;

public double setSurfaceArea (double radius, double height)
{
surfaceArea = (2*3.14*Math.pow(radius,2)) + (2*3.14*radius*height);
return surfaceArea;
}

public double setVolume (double radius, double height)
{
volume = (3.14*Math.pow(radius, 2)*height);
return volume;
}

}

And here’s our main class (the class where we will run the program):

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 cylinder = new Demo3();

Scanner sc = new Scanner(System.in);

System.out.println(“Please give me a radius: “);
double r = sc.nextDouble();

System.out.println(“Please give me a height: “);
double h = sc.nextDouble();

System.out.println(“The cylinder’s surface area is ” + cylinder.setSurfaceArea(r, h));
System.out.println(“The cylinder’s volume is ” + cylinder.setVolume(r, h));
}
}

And here’s some sample output:

run:
Please give me a radius:
9.5
Please give me a height:
11.2
The cylinder’s surface area is 1234.962
The cylinder’s volume is 3173.912
BUILD SUCCESSFUL (total time: 30 seconds)

In the Demo3 class, I have two private double variables-surfaceArea and volume. My two setter methods-setSurfaceArea and setVolume-will set the values of the surfaceArea and volume variables. Oh, and in case you’re wondering where I got the formulas from, they are the formulas for the surface area and volume of a cylinder, respectively.

You will notice that I don’t have any getter methods here. Why? Since I am using formulas to set the values of surfaceArea and volume, using only the setter methods is fine; due to the nature of this program, there is no need to use getter and setter methods (and the code might have been more confusing if I had used both getters and setters).

In my main class, I have a Scanner object and two doubles-r and h-that will serve as the parameters for each setter method (r will be radius and h will be height). R and h will be set based on the user’s input.

  • One thing I wanted to mention that I didn’t mention earlier is that you don’t have to use the words get and set in your getter and setter methods, but it’s a good idea to do so.

Next, here’s a program demonstrating method making and exception handling. First, here’s the method class (the class that contains the method(s) needed for the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here is the main class (the class from where we will run the program):

package demo3;

public class Demo3
{
private double windchill;

public void findWindchill (double airTemp, double windSpeed)
{
try
{
windchill = 35.74 + (0.6215*airTemp) – (35.75*Math.pow(windSpeed, 2)) + (0.4275*airTemp*Math.pow(windSpeed, 16));
System.out.println(“The windchill is: ” + windchill);
}

catch (Exception e)
{
System.out.println(“Sorry please enter a number”);
}
}
}

And here are two sample outputs (one where the exception runs and one where the program runs normally):

run:
Please enter the temperature:
12
Please enter wind speed:
55
The windchill is : 3.596834017946246E28
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please enter the temperature:
12
Please enter wind speed:
H
Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

In this program, the method findWindchill will calculate the temperature with windchill using airTemp and windSpeed as parameters-both of which are double.

In the method findWindchill , I have included a try-catch statement. In the try portion, the block of code I will test will calculate and display the windchill. In the catch portion, the message Sorry please enter a number will be displayed should the method catch an error (which would involve either airTemp or windSpeed not being double).

Or so you would think that the Sorry please enter a number message will be displayed (I thought this would happen too). Here’s what you really see:

Exception in thread “main” java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextDouble(Scanner.java:2413)
at demo3.DemoClass3.main(DemoClass3.java:15)
/Users/michaelorozco-fletcher/Library/Caches/NetBeans/8.2/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 5 seconds)

So why don’t you see the Sorry please enter a number message? It’s because that, when dealing with double input, Java will automatically throw an InputMismatchException if the input is non-numeric.

In other words, writing a try-catch statement in my findWindchill method wasn’t necessary. I’ll admit that I didn’t realize this at first, and only found out this would happen after browsing through a few StackOverflow forums. Hey, even I learn new things in programming every now and then.

  • StackOverflow is a great resource for any coding questions you might have, but keep in mind that you might have to look through a few forums until you get the answer that you need.

Lastly, here’s a recursion demo, starting with the method class. Notice anything familiar about this program?:

public class Demo3
{
private int month;
private int day;
private String year;

public String findMonth (int month)
{
String m = null;

switch(month)
{
case 1: m = “January”; break;
case 2: m = “February”; break;
case 3: m = “March”; break;
case 4: m = “April”; break;
case 5: m = “May”; break;
case 6: m = “June”; break;
case 7: m = “July”; break;
case 8: m = “August”; break;
case 9: m = “September”; break;
case 10: m = “October”; break;
case 11: m = “November”; break;
case 12: m = “December”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);

}

}

return m;
}

public String findDay1 (int day)
{
String d = null;

{
switch(day)
{
case 1: d = “1st”; break;
case 2: d = “2nd”; break;
case 3: d = “3rd”; break;
case 4: d = “4th”; break;
case 5: d = “5th”; break;
case 6: d = “6th”; break;
case 7: d = “7th”; break;
case 8: d = “8th”; break;
case 9: d = “9th”; break;
case 10: d = “10th”; break;
case 11: d = “11th”; break;
case 12: d = “12th”; break;
case 13: d = “13th”; break;
case 14: d = “14th”; break;
case 15: d = “15th”; break;
case 16: d = “16th”; break;
case 17: d = “17th”; break;
case 18: d = “18th”; break;
case 19: d = “19th”; break;
case 20: d = “20th”; break;
case 21: d = “21st”; break;
case 22: d = “22nd”; break;
case 23: d = “23rd”; break;
case 24: d = “24th”; break;
case 25: d = “25th”; break;
case 26: d = “26th”; break;
case 27: d = “27th”; break;
case 28: d = “28th”; break;
case 29: d = “29th”; break;
case 30: d = “30th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return d;
}
}

public String findDay2 (int day)
{
String d2 = null;

switch(day)
{
case 1: d2 = “1st”; break;
case 2: d2 = “2nd”; break;
case 3: d2 = “3rd”; break;
case 4: d2 = “4th”; break;
case 5: d2 = “5th”; break;
case 6: d2 = “6th”; break;
case 7: d2 = “7th”; break;
case 8: d2 = “8th”; break;
case 9: d2 = “9th”; break;
case 10: d2 = “10th”; break;
case 11: d2 = “11th”; break;
case 12: d2 = “12th”; break;
case 13: d2 = “13th”; break;
case 14: d2 = “14th”; break;
case 15: d2 = “15th”; break;
case 16: d2 = “16th”; break;
case 17: d2 = “17th”; break;
case 18: d2 = “18th”; break;
case 19: d2 = “19th”; break;
case 20: d2 = “20th”; break;
case 21: d2 = “21st”; break;
case 22: d2 = “22nd”; break;
case 23: d2 = “23rd”; break;
case 24: d2 = “24th”; break;
case 25: d2 = “25th”; break;
case 26: d2 = “26th”; break;
case 27: d2 = “27th”; break;
case 28: d2 = “28th”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}
return d2;
}

public String findDay3 (int daÿ)
{
{
String d3 = null;

switch(day)
{
case 1: d3 = “1st”; break;
case 2: d3 = “2nd”; break;
case 3: d3 = “3rd”; break;
case 4: d3 = “4th”; break;
case 5: d3 = “5th”; break;
case 6: d3 = “6th”; break;
case 7: d3 = “7th”; break;
case 8: d3 = “8th”; break;
case 9: d3 = “9th”; break;
case 10: d3 = “10th”; break;
case 11: d3 = “11th”; break;
case 12: d3 = “12th”; break;
case 13: d3 = “13th”; break;
case 14: d3 = “14th”; break;
case 15: d3 = “15th”; break;
case 16: d3 = “16th”; break;
case 17: d3 = “17th”; break;
case 18: d3 = “18th”; break;
case 19: d3 = “19th”; break;
case 20: d3 = “20th”; break;
case 21: d3 = “21st”; break;
case 22: d3 = “22nd”; break;
case 23: d3 = “23rd”; break;
case 24: d3 = “24th”; break;
case 25: d3 = “25th”; break;
case 26: d3 = “26th”; break;
case 27: d3 = “27th”; break;
case 28: d3 = “28th”; break;
case 29: d3 = “29th”; break;
case 30: d3 = “30th”; break;
case 31: d3 = “31st”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}

}
return d3;
}
}

public String findYear (String year)
{
String y = null;

switch(year)
{
case “00”: y = “2000”; break;
case “01”: y = “2001”; break;
case “02”: y = “2002”; break;
case “03”: y = “2003”; break;
case “04”: y = “2004”; break;
case “05”: y = “2005”; break;
case “06”: y = “2006”; break;
case “07”: y = “2007”; break;
case “08”: y = “2008”; break;
case “09”: y = “2009”; break;
case “10”: y = “2010”; break;
case “11”: y = “2011”; break;
case “12”: y = “2012”; break;
case “13”: y = “2013”; break;
case “14”: y = “2014”; break;
case “15”: y = “2015”; break;
case “16”: y = “2016”; break;
case “17”: y = “2017”; break;
case “18”: y = “2018”; break;
case “19”: y = “2019”; break;

default:
{
System.out.println(“ERROR”);
System.exit(0);
}
}

return y;
}
}

And here’s the main class:

package demo3;
import java.util.Scanner;

public class DemoClass3
{
public static void main (String [] args)
{
Demo3 date = new Demo3 ();
Scanner sc = new Scanner (System.in);

System.out.println(“Please enter a number: “);
int month = sc.nextInt();

System.out.println(“Please enter a number: “);
int day = sc.nextInt();

System.out.println(“Please enter a two digit String: “);
String year = sc.next();

if (month == 4 || month == 6 || month == 9 || month == 11)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay1(day) + ” , ” + date.findYear(year));
}

else if (month == 2)
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay2(day) + ” , ” + date.findYear(year));
}

else
{
System.out.println(“The date is: ” + date.findMonth(month) + ” ” + date.findDay3(day) + ” , ” + date.findYear(year));
}
}
}

And here are two sample outputs, one where the program runs as normal, and another where the default case is executed:

run:
Please enter a number:
11
Please enter a number:
27
Please enter a two digit String:
19
The date is: November 27th , 2019
BUILD SUCCESSFUL (total time: 13 seconds)

run:
Please enter a number:
11
Please enter a number:
31
Please enter a two digit String:
19
ERROR
BUILD SUCCESSFUL (total time: 6 seconds)

Alright, so the familiar thing about this program is that it is a more complicated version of the recursion example from Java Lesson 13: Recursion (the one where you enter a number and return a month). However, unlike that program, you are trying to put together a whole date using three variables-month, day, and  year.

But that’s not all. See, the month and day variables are int but the year is actually a String. Ok, so year is really a two-digit String that can range from 00 to 19 (representing 2000 to 2019). From that two-digit string, the full year is returned.

The method class has 5 methods: findMonth, findDay1, findDay2, findDay3 and findYear.  If you’ll notice from the code,  the findDay methods do the same basic thing; the only difference is that findDay1 has 30 cases, findDay2 has 28 cases, and findDay3 has 31.

As for why I made three different findDay methods, here’s a poem that explains my reasoning:

Thirty days hath September
April, June and November
All the rest have 31
Except for February which has 28

See, depending on the value for the month that the user enters, I needed three different findDay methods to handle every appropriate scenario, since not all months have the same amount of days.

And yes, I know February has a 29th every four years, but I didn’t feel like overcomplicating this program. If you tried to input a date such as February 29, 2016, you would get an error:

run:
Please enter a number:
2
Please enter a number:
29
Please enter a two digit String:
16
ERROR
BUILD SUCCESSFUL (total time: 21 seconds)

As for the two pieces of sample output shown earlier, the first piece shows the output when month=11, day=27, year="19" (that output is November 27, 2019 , the day this post was published). The second piece shows the output when month=11, day=31, year "19" (this returns an error message, since there is no such date as November 31, 2019).

Thanks for reading and Happy Thanksgiving,

Michael

Python Lesson 5: Conditional Statements & User Input

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on conditional statements in Python. I covered Java conditional statements in Java Lesson 4: IF-ELSE statements & Logical/Comparison Operators, and in case you’re wondering, “conditional statements” is a more technical way of saying “if-else statements” (or “if statements” and “else statements”, for that matter). I will also cover user input in Python.

Just like Java, Python has if, else, and else if statements, except in Python, else if is referred to as elif. The logic behind conditional statements in Python is the same as in Java. By that I mean in any group of conditional statements, if will always come first, followed by any elif statements and an else statement at the end of the group. Here’s an example program with conditional statements (since I wrote this for explanatory purposes, I won’t have any sample output):

if (score >= 300) and (score <= 579); print (“POOR”)

elif (score >= 580) and (score <= 679); print (“FAIR”)

elif (score >= 680) and (score <= 739); print (“GOOD”)

elif (score >= 740) and (score <= 799); print (“VERY GOOD”)

else; print (“EXCEPTIONAL”)

In this program, there is a variable called score (a reference to FICO Credit Score) and based on the value of that variable, one of five things will be displayed-POOR, FAIR, GOOD, VERY GOOD, and EXCEPTIONAL. If the if statement is not true, each of the elif statements will be analyzed from the top down to see which one is true; once a true statement is found, any code on that statement will be executed and the compiler will stop analyzing the group of conditional statements. If neither the if statement nor any of the elif statements are true, then the else statement will execute.

Now. everything I just said will hold true in most cases, provided score falls between 300 and 849 inclusive. But what if the value of score was outside that range? You would simply write another elif statement that goes something like elif (score >= 800) and (score <= 850); print ("EXCEPTIONAL"). You would also have to revise the else statement so that it reads something like else; print ("NOT POSSIBLE"). By writing the new elif statement, the compiler will know to print out ERROR if score isn’t between 300 and 850 inclusive.

Now, let’s demonstrate conditional statements. Here’s a simple example:

rt = 78
if (rt >= 60) and (rt <= 100):
print(“fresh movie”)
else:
print(“rotten movie”)

And here’s the output:

fresh movie

Using Rotten Tomatoes’ movie scoring system as an example (the rt refers to Rotten Tomatoes score), the compiler will print out “fresh movie” if rt is between 60 and 100 and “rotten movie” if rt is below 60. Since rt is 78 (that’s the current score for the movie Good Boys), “fresh movie” will be displayed.

Now, here’s a more complex conditional statements example, with several elif statements:

IGN = 6.6
if (IGN == 10):
print(“MASTERPIECE”)
elif (IGN >= 9) and (IGN <= 9.9):
print(“AMAZING”)
elif (IGN >= 8) and (IGN <= 8.9):
print(“GREAT”)
elif (IGN >= 7) and (IGN <= 7.9):
print(“GOOD”)
elif (IGN >= 6) and (IGN <= 6.9):
print(“OKAY”)
elif (IGN >= 5) and (IGN <= 5.9):
print(“MEDIOCRE”)
elif (IGN >= 4) and (IGN <= 4.9):
print(“BAD”)
elif (IGN >= 3) and (IGN <= 3.9):
print(“AWFUL”)
elif (IGN >= 2) and (IGN <= 2.9):
print(“PAINFUL”)
elif (IGN >= 1) and (IGN <= 1.9):
print(“UNBEARABLE”)
else:
print(“DISASTER”)

And here’s the output:

OKAY

Using IGN’s gaming review scoring system in this example, the compiler will look at the value of IGN (referring to a game’s IGN score) and based on that value, will first analyze the if statement, then all of the elif statements from the top down, and finally the else statement (which will only be analyzed if neither the if statement nor the elif statements are true). Remember that the compilers will stop analyzing once it finds a true statement, which in this case would be elif (IGN >= 6) and (IGN <= 6.9) (which would print out OKAY).

  • Also remember that a colon would come after each conditional statement (in other words, right before the block of code that’s supposed to be executed with a particular statement). Unlike Java, there’s no need to place the code that goes with conditional statements in brackets (and you’ll likely get an error if you do so).

Now, one thing I would like to mention is that you can sometimes write conditional statements in a handy little shorthand.

Let’s use the if-else Rotten Tomatoes score example. Here’s the shorthand way of writing that program:

print(“fresh movie”) if (rt >= 60) and (rt <= 100) else print(“rotten movie”)

Even though you will need to assign a value to rt on a separate line, you can still write the if–else statement on the same line. However, if you’ve got multiple elif statements (like the IGN example), then this approach will not work.

Now, what if the value of a certain variable wasn’t already set. What if you needed to set the value of a certain variable?

This brings me to the next topic I will cover in this post-user input in Python. Just like Java, Python also allows for user input. Using the IGN scoring program from a previous example, here’s how to handle user input in Python:

IGN = float(input(“Give me an IGN score: “))
if (IGN == 10):
print(“MASTERPIECE”)
elif (IGN >= 9) and (IGN <= 9.9):
print(“AMAZING”)
elif (IGN >= 8) and (IGN <= 8.9):
print(“GREAT”)
elif (IGN >= 7) and (IGN <= 7.9):
print(“GOOD”)
elif (IGN >= 6) and (IGN <= 6.9):
print(“OKAY”)
elif (IGN >= 5) and (IGN <= 5.9):
print(“MEDIOCRE”)
elif (IGN >= 4) and (IGN <= 4.9):
print(“BAD”)
elif (IGN >= 3) and (IGN <= 3.9):
print(“AWFUL”)
elif (IGN >= 2) and (IGN <= 2.9):
print(“PAINFUL”)
elif (IGN >= 1) and (IGN <= 1.9):
print(“UNBEARABLE”)
else:
print(“DISASTER”)

And here’s the output if I use 5.1 as the value of IGN:

Give me an IGN score: 5.1
MEDIOCRE

In Python, user input is much simpler than it is in Java. In Java, you have to import a Scanner class for user input AND create a separate Scanner variable (along with familiarizing yourself with all the methods in the Scanner class). With regards to user input, Python is much simpler to use, as it has a built-in user input function-input()-so there is no need to import anything. As a result, it only take one line of code to handle user input in Python, as opposed to the three or four lines of code it can take in Java.

I have three important tips regarding user input in Python, which include:

  • You don’t technically need put in any parameters for the input() method, but it’s suggested that you do so, as I did with input(Give me an IGN score: ).
  • You can set the value of certain variable to the user’s input, as I did with the value of IGN.
  • The default type of user input in Python is String, so if you want to set the user input to another type, write something like this other type(input(text for input)). In my IGN example, I wanted input of type float, so I wrote IGN = float(input(Give me an IGN score: )). By writing this, my input for IGN would be read as float and not String.

Thanks for reading,

Michael

 

Python Lesson 4: Math & Logic

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on Python math and logic, with an emphasis on mathematical and logical operators in Python.

First, we’ll start off with mathematical operators. Python has seven mathematical operators, which include +, -, *, /, %, ** and //. If you know Java (or basic arithmetic for that matter), then the first four operators would look very familiar to you, since they are the addition, subtraction, multiplication, and division operators, respectively.

However, let’s discuss the other three operators-%, **, and //. % is the modulo operator, which is what we would use for modular division. For those unfamiliar with the concept, modular division is similar to regular division, except you are trying to find the remainder of two numbers instead of the quotient. For instance, 11%4 (read as 11 mod 4) is 3, since 11 divided by 4 is 2 with a remainder of 3.

** is the exponentiation operator. This one is pretty simple to explain, since this would be the operator you would use if you want to raise a number to a certain power. That’s all. For example, 8 cubed in Python would be 8**3. This is much simpler than using Java’s Math.power() function (which requires importing a class-not the case with Python).

// would probably look the most unfamiliar to you (I had to look it up the first time I saw it). This is the floor division operator, and I’ll admit that, even though I do lots of coding, I’ve never heard of the concept of floor division. Apparently, floor division is a very simple concept, as it is regular division with any decimal points removed from the quotient. However, keep in mind that floor division rounds DOWN to the nearest integer, so in a division problem like 20/7 with a simple division quotient of 2.86 (rounded to two decimal places), the floor division quotient would be 2, not 3.

Another thing to keep in mind with floor division is that, if either the dividend or divisor is negative, the quotient will also be rounded down, but it will be rounded away from 0 NOT towards 0. For example, -20/7 has a simple division quotient of -2.86 but a floor division quotient of -3, not -2. So when I say a negative floor division quotient would be rounded away from 0, I mean that the quotient will be rounded to the LOWER negative number, not the higher negative number.

Now, let’s see the %, **, and // operators in action:

a = 30 % 8
b = 6**3
c = 177 // 33
print(a)
print(b)
print(c)

And here’s the output:

6
216
5

The answer for a-6-is displayed first. 30 mod 8 is 6, meaning that 30 divided by 8 will give you a remainder of 6. The answer for b-216-is displayed next. 6 cubed is 216. The answer for c-5-is displayed last. The simple division quotient (rounded to two decimal places) is 5.36, so the floor division quotient is rounded down to 5.

Now let’s demonstrate some PEMDAS (remember this?) in Python:

a = 4 – (2 + 5) * 11 / 2
print(a)

And here’s the output:

-34.5

OK, so this is a simple enough problem. Parentheses come first, so (2+5) would be solved first; you would get a result of 7. 7 would then be multiplied by 11 to get 77, which would then be divided by 2 to get 38.5, which would be subtracted from 4 to get the final result of -34.5.

Now let’s try something a little more complex:

a = 100 // (16 + 2) – 31 + 3**4 / (6 * 12) * 15 % 6
print(a)

And here’s the output:

-21.125

Here’s a breakdown showing how to get to the final answer:

  • 100 // (16 + 2) - 31 + 3**4 / (6 * 12) * 15 % 6
  • 100 // 18 - 31 + 3**4 / 72 * 15 % 6
  • 100 // 18 - 31 + 81 / 72 * 15 % 6
  • 5 - 31 + 1.125 * 15 % 6
  • 5 - 31 + 16.875 % 6
  • 5 - 31 + 4.875
  • -26 + 4.875
  • -21.125

Keep in mind that with order of operations in Python, the % and // operators are treated with the same precedence as the simple division operator (/).

Next, I’ll cover comparison operators, which are used to compare two values. There are 6 comparison operators in total-==, !=, >, <, >=, <=, which respectively represent:

  • Equal to
  • Not equal to
  • Greater than
  • Less than
  • Greater than or equal to
  • Less than or equal to

Statements with these logical operators will either return true or false. Let’s demonstrate the comparison operators:

a = (13 + 11) == 24
b = (41 + 16) != 66
c = (15 > 29)
d = (41 < 23)
e = (13 >= 9)
f = (55 <= 22)
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)

And here’s the output:

True
True
False
False
True
False

So, in order, here’s the result for each statement:

  • a-TRUE
  • b-TRUE
  • c-FALSE
  • d-FALSE
  • e-TRUE
  • f-FALSE

The next thing I wanted to discuss are the three logical operators-and,or, and not. The logical operators work just as they do in Java, except in Python, you would words instead of the symbols &&, ||, and !-which are and, or, and not, respectively. However, the logic behind these operators is the same as in Java. By this I mean:

  • For two statements combined with and, both of the individual statements must be true for the statement pair to be true. If one of the statements is false, then both are false.
  • For two statements combined with or, only one of the statements must be true for the statement pair to be true. However, if both statements are false, then the whole statement pair is false.
  • Statement pairs with not often contain an and or or as well (e.g. not(statement pair a or statement pair b)). The statement pair in parentheses would first be evaluated, and the result would be whatever the opposite of the result from the statement pair. For instance, if the statement pair was true, then (assuming there is a not), the result would be false, and vice versa.

Let’s start with a simple demonstration of logical operators:

m = (14 > 19) and (15 + 12 != 33)
o = (51 >= 16) or (9 – 2 > 6)
f = not(14**2 < 28 and 13 % 9 <= 1)
print(m)
print(o)
print(f)

And here’s the output:

False
True
True

The results to each statement are:

  • m-FALSE
  • o-TRUE
  • f-TRUE

Now, let’s try something slightly more complex with logical operators:

m = (14 < 19) and (23 >= 11) or (100 % 16 > 7)
print(m)

And here’s the output:

True

How did we get this result? First of all, keep in mind that the statement pairs will be evaluated from left to right (just as they would in order of operations problems). The result of the first statement pair-(14 < 19) and (23 >= 11)-is true, so that result would be evaluated with the second statement-(100 % 16 > 7)-which is also true. Since we are dealing with two trues and an or, the entire statement group is true.

Next, we’ll discuss the two identity operators-is and is not-which also function as comparison operators. However, these operators don’t evaluate whether or not two objects are equal or not; rather, these operators test whether or not two values are the same object with the same memory location. I know that sounds like a lot of coding jargon, so here’s a program to demonstrate identity operators:

a = (“ant”,”bear”,”cat”,”dog”,”eel”)
b = (“ant”,”bear”,”cougar”, “dog”, “eel”)
print(a is b)
print(a is not b)

And here’s the output:

False
True

A simple way to explain this program is that I’m trying to test whether a and b have the exact same values. The first statement-a in b-is false because a and b do not have the exact same values. However, the second statement-a not in b-is true because a and b do not have the exact same values.

An easy way to remember identity operators is that, when comparing two lists, is means the two lists are exactly alike while is not means that the two lists aren’t exactly alike.

Finally, let’s cover the concept of membership operators. Like identity operators, there are two membership operators-in and not in-and both identity and membership operators are used with lists. Here’s a program demonstrating identity operators:

a = (“carrot”, “celery”, “squash”, “cucumber”, “eggplant”)
print(“squash” in a)
print(“squash” not in a)

And here’s the output:

True
False

In this program, I am testing whether or not squash is in my list (a). Just as with the previous program, I used both possible operators-in and not in-to see which one would give me true and which would give me false. The first statement-squash in a-is true, meaning that squash is in list a. Thus, the second statement-squash not in a-is false.

Thanks for reading,

Michael

Java Lesson 4: IF-ELSE statements & Logical/Comparison Operators

Advertisements

Hello everybody,

It’s Michael, and today’s post will be on if-else statements and logical/comparison operators in Java. If-else statements allow your program to choose between two or more alternative actions.

Why are if-else statements so important? Well, with Java programs, as in everyday life, things can go several different ways. Let’s say you just took a final exam for a college class. Depending on how you did on that exam, your grade can come out one of five ways (A, B, C, D, or F). The same sort of thinking applies to programming, as there can be several different actions a program can perform depending on certain scenarios (like if an int is greater than/less than/equal to a certain amount).

Let’s demonstrate using a program example (I had to copy and paste the code since you can’t see all of it from a screenshot):

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println (“Please enter a number: “);
double temperature = sc.nextDouble ();
System.out.println (“C or F: “);
String unit = sc.next();
double temp;

if (“C”.equals(unit))
{
temp = (1.8*temperature)+32;
System.out.println (“The temperature is ” +temp+ ” degrees Farenheit”);
}

else if (“F”.equals(unit))
{
temp = (temperature-32)*0.56;
System.out.println (“The temperature is ” +temp+ ” degrees Celsius”);
}

else
System.out.println(“Not a valid answer”);
}

}

This program is a temperature unit converter; the user enters a number and a “C” or “F” (for Celsius or Fahrenheit) and, depending on what letter was entered, converts the temperature from Celsius to Fahrenheit or vice versa.

I want to clarify that there is a difference between else if and else. Else if acts as another if statement; you would use else if if your program was trying to test two or more conditions, such as whether a “C” or “F” was typed. The else statement would come at the very end of your code since that would be the statement that executes should neither of the if/else if conditions be true; the output I used for the else statement would only display if neither a “C” nor an “F” was typed.

  • Always use .equals for String variables such as these. Don’t use =.
  • You need to use brackets if you if or else if statements use more than one line of code. If you only need one line of code, you don’t need the brackets.

Let’s try inputting a number:

run:
Please enter a number:
19
C or F:
C
The temperature is 66.2 degrees Farenheit
BUILD SUCCESSFUL (total time: 17 seconds)

I entered 19 and C, meaning I wanted to find out what 19 degrees Celsius was in Fahrenheit. I got 66.2, which means that 19 degrees Celsius is equal to 66.2 degrees Fahrenheit.

Now let’s see what happens when I don’t type a “C” or an “F”:

run:
Please enter a number:
45
C or F:
W
Not a valid answer
BUILD SUCCESSFUL (total time: 8 seconds)

I typed 45 and W and as a result, “Not a valid answer” displayed (which is the output I had set to display if neither “C” nor “F” was typed).

For those who’d like a video demo of the program, here it is-Temperature converter.

Now let me introduce some new concepts that perfectly relate to if and else if statements-comparison and logical operators.

Comparison operators are pretty self-explanatory, as they are used to compare two things (usually testing a variable and a value). If you know basic algebra, you’d be familiar with most of these:

  • == is “equal to” (remember to use .equals for Strings)
  • != is “not equal to”
  • > is “greater than”
  • >= is “greater than or equal to”
  • < is “less than”
  • <= is “less than or equal to”

Logical operators are similar to comparison operators since both compare statements. However, comparison operators are only used for single boolean statements, such as (temperature > 70) while logical operators are used for groups of boolean statements, such as (temperature >= 60) && (temperature <= 80).

Here are the three main logical operators:

  • &&-AND
  • ||-OR
  • !-NOT

OK, so even though I said logical operators are used for groups of boolean statements, the NOT operator is more for single boolean statements, such as !(temperature > 70)-meaning that you’re looking for temperatures that aren’t greater than 70 degrees. You can, however, also use the NOT operator for groups of boolean statements, such as (!(temperature >= 50) && (temperature <= 0))-meaning that you’re looking for temperatures that aren’t between 0 and 50 degrees.

Here’s the one takeaway with the NOT operator-it negates boolean statements (whether an individual statement or groups of statements). In other words, it essentially contradicts whatever is in the statement(s).

Now, one more thing I want to cover regarding logical operators-the truth table. The truth table doesn’t involve any coding, rather it’s a helpful guide with regards to boolean statements in your program. The truth table compares two boolean statements, looks at the values of each statement (whether they are true or false), and based on the values of each individual statement, returns true or false for that pair of statements. Here’s the table below:

When dealing with AND, both statements in a pair have to be to true in order for the statement pair to be true. If one or both statements are false, then the statement pair returns false. With OR however, only one statement has to be true for the pair to be true, but if both statements are false, then the pair is false. And as I mentioned earlier, NOT contradicts boolean statement(s), so if you not right by a boolean statement pair that is true, then that pair is false (and vice versa).

Let’s test this logic with an example program:

27jan capture1

In this program I have two boolean statements (5 > 7) and (12 < 16). I then use System.out.println to test whether the statement pair greaterThan && lessThan is true or false. Since I used AND and one of the statements is false-greaterThan-both of the statements are false. Remember with AND, if one of the statements are false, then both are false.

Now let’s apply our knowledge of truth tables to more than two boolean statements:

When dealing with more than two boolean statements, logical evaluation is done from left to right. The Java compiler would first read the first pair of statements-greaterThan && lessThan-to evaluate whether that statement pair is true or false (it’s false). The compiler then takes the false result and compares it with the subtraction statement, which is true (thus statements 1-3 are collectively true). Finally, the compiler takes the collective true result from statements 1-3 and compares it with the multiplication statement, which is false. But, since OR is being used to compare the statements, you only need 1 true statement to result in true, which is the case here. After analyzing all 4 statements, the compiler states that the 4 statements together are collectively true.

Now, let’s analyze a program with several if options. In this program, you would type in a year, and the program will tell you what generation you belong to; keep in mind that the dates provided are just approximations, as different sources use different dates to mark the beginning and end of a generation. Here is the code:

package javalessons;
import java.util.Scanner;

public class JavaLessons
{

public static void main(String[] args)
{
Scanner sc = new Scanner (System.in);
System.out.println (“Enter your birth year: “);
int year = sc.nextInt();

if (year >= 1900 && year <= 1928)
{
System.out.println(“You are part of the Greatest Generation”);
}

else if (year >= 1929 && year <= 1945)
{
System.out.println(“You are part of the Silent Generation”);
}

else if (year >= 1946 && year <= 1965)
{
System.out.println(“You are a Baby Boomer”);
}

else if (year >= 1966 && year <= 1981)
{
System.out.println(“You are a Gen-Xer”);
}

else if (year >= 1982 && year <= 2000)
{
System.out.println(“You are a Millenial”);
}

else if (year >= 2001 && year <= 2019)
{
System.out.println(“You are a Gen-Zer”);
}

else
{
System.out.println(“Invalid input”);
}
}

}

Please note that you will get a certain output (i.e. “You are a Millennial”) if both conditions are true; “You are a Millennial” will only print out if the year you typed is between 1982 and 2000.

Now let’s use the year 1946 (President Trump’s birth year):

run:
Enter your birth year:
1946
You are a Baby Boomer
BUILD SUCCESSFUL (total time: 3 seconds)

As you can see, 1946 corresponds to Baby Boomer, meaning President Trump is a Baby Boomer.

Now let’s try 1996 (my birth year):

run:
Enter your birth year:
1996
You are a Millenial
BUILD SUCCESSFUL (total time: 3 seconds)

According to the program, I am a millennial.

For those who want a video demo of the program, check this out-Generation program.

Now, a concept you should know that ties in with the material in this post is precedence. Precedence is similar to order of operations in the sense that both concepts involve doing things in a certain order. However, while order of operations just deals with arithmetic and exponents, precedence deals with arithmetic, comparison, and logical operators. With precedence, there is a certain order which the compiler evaluates statements with multiple arithmetic/comparison/logical operators. Here’s a handy guide:

  • First-the operators +,-,++,–, and !
    • The ++ and — operators represent incrementing and decrementing, respectively. These operators basically increase or decrease (or increment and decrement) a number by 1; you’ll see them more when I cover loops.
  • Second-the operators *, / and %
  • Third-the operators + and –
    • The plus and minus signs that take highest precedence actually refer to positive and negative numbers, while the one that are 3rd in precedence order actually refer to addition and subtraction
  • Fourth-the operators <, >, <= and >=
  • Fifth-the operators == and !=
  • Sixth-the operator &
  • Seventh-the operator |
  • Eighth- the operator &&
  • Ninth-the operator ||
    • The difference between the single & and || and the double && and || is that the former two are known as bitwise operators, which analyze data of types int, long, short, char, and byte bit by bit.
    • Check out this forum to learn more about bitwise operators-Bitwise Operators.

Keep in mind that parentheses ALWAYS take highest precedence (yes even higher than the operators listed as highest precedence). Any statements inside the parentheses are evaluated in order of operator precedence; if you’re dealing with parentheses-within-parentheses, the expression in the innermost set of parentheses is evaluated first, after which the compiler will work its way outward.

Here’s a series of statements; can you guess the result (true or false) based on precedence:

temperature = 44;

temperature – 2 < 32 || (temperature + 5 != 55) && temperature / 2 < 30

If you said true, you are right. Let me break it down:

  • The statement temperature + 5 != 55 is evaluated first, as it is in parentheses. It is true.
  • The next statement to be evaluated is temperature / 2 < 30, as it right by the && sign, which takes higher precedence than ||. That statement is also true, so that results, along with the true statement in parentheses, makes for a true statement pair.
  • The last statement to be evaluated is temperature - 2 < 32, since it’s right by the || sign. Even though this statement is false, the true statement pair to its right makes the whole group of statements collectively true (remember with OR, only one true makes for a collective true).

Thanks for reading,

Michael