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

 

Java Program Demo 1: Factorials and Fibonacci Sequences

Advertisements

Hello everybody,

It’s Michael, and today’s Java post will be a little different from the previous six because I am not giving you guys a lesson today. See, when I launched this blog in June 2018, I said I was going to posts lessons and analyses with various programs. However, in the case of Java, I feel it is better to give you guys program demos that cover the concepts I’ve discussed so far (loops, if-else statements, etc.). In this post, I will show you guys two programs that cover all the Java concepts I’ve discussed so far.

Here is this code for the first program (video in link)-Fibonacci sequence program:

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 choose a number: “);
int num = sc.nextInt();

int start = 0;
int t2 = 1;

if (num >= 0)
{
while (start <= num)
{
System.out.print(start + ” + “);

int sum = start + t2;
start = t2;
t2 = sum;
}
}

else
{
System.out.println(“Need a 0 or a positive number”);
}
}
}

This program prints every number in the Fibonacci sequence up to a certain point. If you’re wondering, the Fibonacci sequence is a pattern of numbers that starts with 0 and 1 and calculates each subsequent element by finding the sum of the two previous numbers.

  • Here are the first 10 numbers of the Fibonacci sequence-0,1,1,2,3,5,8,13,21,34,55. Notice how every element after the 3rd is the sum of the previous two numbers (e.g. 13 is found by calculating 5+8-the two numbers that directly precede 13 in the series)

To calculate the Fibonacci sequence, I first ask the user to type in a number. That number will serve as the endpoint for my while loop where I calculate each element in the Fibonacci sequence; in other words, my while loop will find every element in the sequence until it reaches the closest possible number to the user’s input. For instance, if I wanted to find every number in the Fibonacci sequence stopping at 600, the program would stop at the closest possible number to 600-which is 377.

  • I decided to add an endpoint because the Fibonacci sequence is infinite, and had I decided not to have an endpoint, I would’ve created an infinite loop.

Notice the if-else statement in my program. The loop will only run IF the user inputs a positive number. Otherwise, the user will just see a message that goes Need a 0 or a positive number. I decided to include the if-else statement since Fibonacci sequences don’t have any negative numbers.

Let’s see some sample output:

run:
Please choose a number:
112
0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 + 55 + 89 + BUILD SUCCESSFUL (total time: 6 seconds)

run:
Please choose a number:
-5
Need a 0 or a positive number
BUILD SUCCESSFUL (total time: 3 seconds)

As you can see, my first output-112-displays the Fibonacci sequence up to 112 while my second output-negative 5-displays a message that is shown when a negative number is chosen.

Here is the code for my next program (video in link)-Factorial program:

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 choose a number: “);
int num = sc.nextInt();

long factorial = 1;

if (num >= 1)
{
for(int i = 1; i <= num; ++i)
{
factorial *= i;
}
System.out.println(“The factorial of ” + num + ” is ” + factorial);
}

else
{
System.out.println (“Number is too low”);
}
}
}

This program calculates the factorial of a number greater than 0. For those wondering, a factorial is the product of a positive number and all positive numbers below it (stopping at 1). For instance 3 factorial is 6, since 3*2*1=6. Just so you guys know, factorials are denoted by the exclamation point (!), so 3 factorial is 3!.

I have three conditional statements in this program that account for the three possible scenarios of user input (>0,0, and <0). If the user enters a number greater than 0, then the for loop will execute and the factorial of the number will be calculated. If the user enters 0, then the message The factorial of 0 is 1 will be displayed, since 0!=1. If the user enters a negative number, then the message Number is too low will be displayed, since factorials only involve positive numbers.

  • If you are wondering why I used long for the factorial variable, I thought it would be more appropriate since factorials can get pretty long (13! is over 6 billion), and long has a wider range than int (9 quintillion as opposed to 2 billion).

Now, let’s see some sample output

run:
Please choose a number:
11
The factorial of 11 is 39916800
BUILD SUCCESSFUL (total time: 12 seconds)

run:
Please choose a number:
0
The factorial of 0 is 1
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
-14
Number is too low
BUILD SUCCESSFUL (total time: 3 seconds)

run:
Please choose a number:
344
The factorial of 344 is 0
BUILD SUCCESSFUL (total time: 3 seconds)

In the first output sample, I chose 11 and got 39,916,800 as the factorial (11!=39,916,800). In the second output sample, I chose 0 and got 1 as the factorial (remember than 0! is 1). In the third output sample, I chose -14 and got the Number is too low message since factorials only involve positive integers.

Now I know I mentioned that there were three possible scenarios for this program. There are actually 4. See, if you type in a number like 700 or 344 (as I did above), you will get 0 as the factorial, even though the actual factorial will be considerably larger. A 0 will be displayed if the actual factorial is greater than 9 quintillion since long doesn’t extend past 9 quintillion.

This concludes my current series of Java posts, but don’t worry, there will be more Java lessons soon! In the meantime, you can look forward to more R posts.

Thanks for reading,

Michael

Java Lesson 3: User Input, Importing Classes, and Java Math

Advertisements

Hello everybody,

It’s Michael, and today’s post will be on user input, importing classes, and doing math in Java. I know these may seem like three totally unrelated topics, but I think they relate well to one another, which is why I’m going to cover all of them in this post.

First off, let’s discuss how to manage user input in your Java program. If you weren’t already aware, Java output doesn’t always have to be predefined-you can write your code so that you can choose the output.

The first thing you would need to do is import the Scanner class from Java, which is the class that handles all text input (don’t think about using it for graphics-heavy programs). Importing the Scanner class (or any class for that matter) allows you to use all its methods.

Here’s an example of a Scanner program:

19jan capture1

The first thing I did was to import the Scanner class. I then created s, which is a variable of type Scanner. Remember to always create a Scanner variable every time you want to use the Scanner class in your program! And remember to ALWAYS set the parameters as (System.in).

I then used System.out.println to write the command asking the user for their input.  The user’s input then is stored in a variable, in this case int year. You must always store your input in a variable if you want it to display on the screen. What variable type you choose depends on what kind of input you are seeking. In this case, since I am seeking integers, I want to use type int. The value you assign to the variable would be (name of Scanner variable).next(type of variable your input is). Since my Scanner variable is named s and my input variable is of type int, the value I assigned my variable was s.nextInt(). The next______ method you use depends on the input variable’s type, so if I had a char variable I would use s.nextChar(). Please note that there is no nextString method so for String variables use next or nextLine.

For those who would like a video demonstration of the Scanner class, check out this program-Scanner demo.

Now, Scanner isn’t the only class you can import from Java. In fact there are plenty of other classes (and methods) you can use and import for a variety of purposes, such as the class Calendar for calendar programs. The best part is that you don’t need to memorize all of the classes available on Java, as there is a handy online dictionary where you can look up classes and methods that you need for your program. This dictionary does a very good job of explaining how you can use each available class.

Now at the beginning of this post, I said I was going to cover how to do math in Java. Well, there is a certain class that I will show you how to use to do just that-it’s the Math class. To access this class, use the line import java.lang.Math. Here are three programs utilizing the Math class and its methods.

This program asks the user for a negative number, then finds the absolute value of that number. Since I typed -33, the program calculated 33 as the absolute value.

This program asks the user for two numbers, then will calculate the value of the first number raised to the power of the second number. Since my first number was 9 and my second number was 3, the program printed out 729, or 9 cubed (which is a more colloquial way of saying “to the third power”)

This last program asks the user for a number, which in this context is an angle measurement for a right triangle. The program will then display the cosine (recall SOHCAHTOA) for that angle measurement; since I used a 49 degree angle in this example, the cosine is  0.3006 (rounded to four decimal places).

However, one thing to note is that the Math is more geared towards complex mathematical operations (like finding logs, trigonometric ratios, and square roots). You don’t need the Math class for basic arithmetic.

In case you’re wondering, here are two programs showing how to do basic arithmetic in Java:

This program demonstrates simple division; the user is asked for a number divisible by 3, then the program will print out the quotient of that number divided by 3. Since I used 612, the quotient displayed was 204.

This program utilizes the order of operations (think PEMDAS); the user is asked to type in a number and the program will print out the answer to the problem (pemdas/2)*3+8-4. Remember pemdas is the name of the variable where you will store the number you choose. I chose to store the user input as a double because I wanted a precise answer; had I stored the input as int , I would’ve gotten the nearest whole number (12) instead of the more precise answer I wanted-11.5.

  • Something I should have pointed out earlier-ALWAYS remember to put semicolons after each statement! To be clear, this only means the lines of code inside each method or class along with any import statements. This doesn’t mean semicolons are needed after class/method declarations themselves!
  • This isn’t totally necessary when coding, but the // symbol right before a line of code is a way to take notes within your program. The compiler won’t read any line of code that begins with //.

Now before I go, here’s a video demonstration on doing math in Java (both with the Math class and without)-Java Math.

Thanks for reading,

Michael