Python Programming Tutorial 15

 Error Handling

Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we did in the previous lesson, but we also need to make sure that input is not going to make our program crash. In order to do that, we are going to use the try and except statements. So let's understand why the program crashed. 

Let's create a new variable called number, and let's assign a user input converted to a float and type a string to see what happens. 








This leads to an error, as Python is unable to convert this value into a string. So in order to solve this problem, we are going to use try and accept statements. 
 
Let's just copy and paste our program in a new file, and instead of converting to float immediately, we can ask for user input first. 

Instead of this: 
number = float ( input("Type a number: ") )

We are going to use this instead:
number =input("Type a number: ")

Then, we are going to use a try statement. This works the same way as the conditionals. The code after the try function is going to be inside the try statement. 
number = input("Type a number:")
try:
      number = float(numbers)
      print("The number is:", number)
What I tried to do here is that i tried to get the conversion. If we are able to get to the next line it means we were able to do this without any problems. If we see the print message, it means we made the conversion without any problem. 

If we have any errors inside the try block, instead of crashing we can just jump to the except function. And inside the except function we can print invalid number.
except:
    
    print("Invalid number")

Entire code:
number =input("Type a number: ")

try:
      number = float(number)
      print("The number is:", number)
except:
    
    print("Invalid number")
Okay, so let's run this code and see what happens. 
First, let's try a valid number and see if it will print the float conversion in the format 20.0.
Output:
>>> 
== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Error handling.py ==
Type a number: 20
The number is: 20.0
>>> 

And it worked. Now, let's try an invalid number: a string.

>>> 
== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Error handling.py ==
Type a number: test
Invalid number
>>> 

And now instead of crashing, it just printed a message. We could have done anything we wanted inside the except block. So this is how we do error handling in Python. 
See you inside our next tutorial. Goodluck.
 

 































dgbds

Python Programming Tutorial 14.

 Data Validation

In this lesson we are going to talk about data validation, and we are going to use the program we created for the grades of the student. 

..................................................................................................................................................................
I'm referring to this data:
grade1 = float ( input("Type the grade of the first test: ") )    
grade2 = float ( input("Type the grade of the second test: ") )
absences = int ( input("Type the number of absences: ") )
total_classes = int ( input("Type the the total number of classes: ") )

avg_grade = (grade1 + grade2) / 2
attendance = (total_classes - absences) / total_classes

print("Average grade: ", round(avg_grade,2) )
print("Attendance rate: ", str(round((attendance * 100),2))+'%' )

if (avg_grade >= 6 or attendance >= 0.8):
        print("The student has been approved.")
elif(avg_grade < 6 and attendance < 0.8):
    print("The student has failed due to an average grade less than 6.0 and an attendance rate less than 80%.")
elif(attendance >= 0.8):
     print("The student has failed due to an average grade less than 6.0.")
else:
    print("The student has failed due to an attendance rate less than 80%")

..................................................................................................................................................................

Let's talk about some problems that might occur in this program. 
In this data, there's no data validation, so even grades from 0 to 10, we can type a 100 by accident, and the program is going to accept it. 
Another program is that if I type a string, our program crashes, which is really tragic. Before we see how we can do basic data validation, let's visualize this: 










And we had an error after running this code and answering with the above information. In our next lesson, we will keep our program crashing by doing error handling.

Data validation

So before asking for user input, we are going to create a variable called "data_valid" and assign to it a value of False. { data_valid  =  False }.
So let's start a while loop with this information: 











Now, the highlighted text is going to return true because data_valid is equal to false, so we are going to go inside this while loop. Afterwards, we will request the grade and perform the validation using an if statement.
 
data_valid = False

while data_valid == False:
        grade1 = float ( input("Type the grade of the first test: ") )
        if grade1 < 0 or grade1 > 10:
                print("Grade should be between 0 and 10")
                continue
        else:
                data_valid = True

This is what it will look like. So we just went inside the while loop and asked for the grade, and we made the validation with an if condition. You do notice that we use the'or'operator, so if one of the tests results true, the whole test is going to result true. If this happens, it means we have an invalid input, and in this case we are going to print the range of the grade. Then we are going to continue in this loop; using the continue function, the continue will jump out of this loop and start over again. Then, we complete with an else statement because if this if grade1 < 0 or grade1 > 10 is not true, it means we have valid input, so in this case, we are going to make data_valid = true. This is going to end the loop, and when it tries to run again, this test data_valid == False is going to return in false, so it is not going to go inside the loop and it's going to continue with our program. Now we are going to do the exact same thing for grade 2.

Let's copy all the data, and set the value of data_valid to false again.

data_valid = False


while data_valid == False:

        grade1 = float ( input("Type the grade of the first test: ") )

        if grade1 < 0 or grade1 > 10:

                print("Grade should be between 0 and 10")

                continue

        else:

                data_valid = True


data_valid = False


while data_valid == False:

        grade2 = float ( input("Type the grade of the second test: ") )

        if grade2 < 0 or grade2 > 10:

                print("Grade should be between 0 and 10")

                continue

        else:

                data_valid = True

This is how our code will look like. Before we continue, let's test it to see what happens.






I first tried negative ten, and it didn't work, it said grade should be between zero and 10. I tried eleven, and it still didn't work. Now, our program only accepts numbers between zero and ten, so let's try eight for the first test and minus ten for the second test. 





It still didn't work. 

Alright, let's continue. For the absences in total classes, lets do something similar, but let's change the order and ask for the total classes first. Let's copy the data one more time. 

 data_valid = False


while data_valid == False:

        total_classes = int ( input("Type the the total number of classes: ") )

        if total_classes <= 0:

                print("The number of classes can't be zero or less")

                continue

        else:

                data_valid = True

We asked for the total number of classes, and we tested if total classes were less than 0. We can have a negative number of classes here, but we won't put any limitation on the number of classes. Actually, this is going to be a bit different since we can have zero classes, and hence the less than or equal to sign was used. So we printed or told the user that the number of classes can't be zero or less.
 
Now let's do the same for the absences. 
We won't accept absences less than zero. We can't accept zero and we can't accept the number of absences greater than the total number of classes. 

data_valid = False

while data_valid == False:
        absences = int ( input("Type the number of absences: ") )
        if absences <= 0 or absences > total_classes:
                print("The number of absences can't be less than or greater than the number of total classes")
                continue
        else:
                data_valid = True
Alright, let's run this and see. 











The validation is working fine. Well this is better but our program crashes when we type in a string, so in our next lesson, we are going to do some error handling. 

Lines of code used: 

data_valid = False

while data_valid == False:
        grade1 = float ( input("Type the grade of the first test: ") )
        if grade1 < 0 or grade1 > 10:
                print("Grade should be between 0 and 10")
                continue
        else:
                data_valid = True

data_valid = False

while data_valid == False:
        grade2 = float ( input("Type the grade of the second test: ") )
        if grade2 < 0 or grade2 > 10:
                print("Grade should be between 0 and 10")
                continue
        else:
                data_valid = True
                
data_valid = False

while data_valid == False:
        total_classes = int ( input("Type the the total number of classes: ") )
        if total_classes <= 0:
                print("The number of classes can't be zero or less")
                continue
        else:
                data_valid = True

data_valid = False

while data_valid == False:
        absences = int ( input("Type the number of absences: ") )
        if absences <= 0 or absences > total_classes:
                print("The number of absences can't be less than or greater than the number of total classes")
                continue
        else:
                data_valid = True


avg_grade = (grade1 + grade2) / 2
attendance = (total_classes - absences) / total_classes

print("Average grade: ", round(avg_grade,2) )
print("Attendance rate: ", str(round((attendance * 100),2))+'%' )

if (avg_grade >= 6 or attendance >= 0.8):
        print("The student has been approved.")
elif(avg_grade < 6 and attendance < 0.8):
    print("The student has failed due to an average grade less than 6.0 and an attendance rate less than 80%.")
elif(attendance >= 0.8):
     print("The student has failed due to an average grade less than 6.0.")
else:
    print("The student has failed due to an attendance rate less than 80%")
     
        
Goodluck see you next time.































     
        

Exercise 2: Loops

2. Create a guess game with the names of the colors. At each round pick a random color from a list and let a user guess it. When he does it, ask if he wants to play again. Keep playing until the user types "no."

I think this is going to be a very nice challenge. Good luck, and when you finish, come back here to see the solution. 

Solution to exercise.

Code:

import random

colors = ["white", "black", "yellow", "blue", "pink", "purple", "grey", "indigo"]

while True:
    color = colors[random.randint(0, len(colors) - 1)]
    guess = input("I'm thinking about a color, can you guess it: ")

    while True:
        if color == guess.lower():
            print("You guessed it! I was thinking about", color)
            break
        else:
            guess = input("Nope. Try again: ")

    play_again = input("Let's play again? Type 'no' to quit: ")

    if play_again.lower() == 'no':
        print("It was fun, thanks for playing!")
        break

Output:

>>> 
==== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Ex.loops2.py ====
I'm thinking about a color, can you guess it: red
Nope. Try again: white
Nope. Try again: blue
Nope. Try again: green
Nope. Try again: yellow
Nope. Try again: pink
Nope. Try again: grey
Nope. Try again: indigo
Nope. Try again: black
You guessed it! I was thinking about black
Let's play again? Type 'no' to quit: 

You can hit enter to see if it repeats, then you try again.

Let's try typing no to see what happens:

>>> 
==== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Ex.loops2.py ====
I'm thinking about a color, can you guess it: red
Nope. Try again: white
Nope. Try again: blue
Nope. Try again: green
Nope. Try again: yellow
Nope. Try again: pink
Nope. Try again: grey
Nope. Try again: indigo
Nope. Try again: black
You guessed it! I was thinking about black
Let's play again? Type 'no' to quit: no
It was fun, thanks for playing!
>>> 

Alright let me know in the comment section if you have further questions. See you in our next tutorial.










































dsssds

Exercise 1: Loops

 1. Create a program that asks the user for 8 names of people and store them in a list. When all the names have been given, pick a random one and print it.

I think this is going to be a very nice challenge. Good luck,  and when you finish, come back here to see the solution. 

Okay let's delve into the solution of this problem.

Code:

import random

people = []

for x in range(0,8):
    person = input("Type the name of the person: ")
    people.append(person)

index = random.randint(0,7)

random_person = people[index]

print("Picking a random person: ", random_person)

#Let's see if this is working

Output:

>>> 
 RESTART: C:/Users/ameny/OneDrive/Desktop/Python.course/Exercise 1 on loops.py 
Type the name of the person: John
Type the name of the person: Paul 
Type the name of the person: Kofi
Type the name of the person: William
Type the name of the person: Kwame
Type the name of the person: KING
Type the name of the person: Hank
Type the name of the person: Walt
Picking a random person:  KING
>>> 

And it worked perfectly. You have the solution for excercise number 1. Let me know if you have further questions.



Python Programming Tutorial 13

For Loops 

In this lesson, we will talk about for loops. For loops in Python, they work as sequence iterators. So let's create a list that we know is a sequence of elements. This list is going to be called blog_posts with some blog post titles:

blog_posts = ["The 10 coolest math functions in Python", "How to make HTTP requests in Python", "A tutorial about data types"]

Now, how could we print all the blog posts in that list using the same lines of code? It doesn't matter how many posts we have in a list. We can start a variable with a value of zero, then start a while loop, and use that variable as an index to print each blog post, but it is actually way easier to do this with a "for loop," and this is how it works:

we are going to write for, and then we are going to create a variable. Let's create one called post and then use the "in"" keyword and then the sequence we want to iterate over. So the first time we run this loop, "The 10 coolest math functions in Python,"  this value is going to be assigned to the post variable. The second time we are going to run this loop, this value "How to make HTTP requests in Python" is going to be assigned to the post variable. And the third time for the third one as well until the end of the list. And we don't have to control the number of iterations because the for loop is going to do that automatically for us. So in every iteration we are going to print the post, which is going to be each element of this list. Let's type the above information into a code and run it:

 





The list continues, however, my screen didn't display all so I gave the list earliar. Okay let us run it to see how it works:






We just printed the titles of our blog posts one by one. No matter how many blog posts we have, this is going to work. I hope you remember we learned about the break statement in the previous lesson. There is also the continue statement, which doesn't interrupt the loop but goes to the next iteration. So let's use it to avoid printing empty blog posts. Let's say for any reason we have some empty values at the beginning of the list and in the middle of the list. In this format: " ", " ",



Let me know if you have difficulty seeing any of the images. Alright let's run this and see what 

happens: 



 And now we have empty values printed as empty spaces. How can we avoid it?

We are going to check if our post is an empty string, and if it is, we are going to use the continue statement, which is going to jump out of the loop but is not going to interrupt the loop. It is just going to jump out of it and go to the next iteration. So when the post is empty it is not going to do anything. Afer that we will run and else statement to print the list. Let's visualise this and run to see if it is better.






Output: 





And it worked successfully. We didn't print the empty strings. Remember that you will get an error message if you use a single equal sign for the program. I explained the differences early in this course. Please refer to my previous tutorial if this feels new to you. 

Remember, a string is also a sequence, so we can also loop through all characters of a string. Let's create a string called myString and do a for loop to iterate over the string. So the variable name is going to be char, the sequence is going to be myString, and every iteration we are going to print a character.

 


 Okay so let's create a separator at the start of this code so this is organised:











let's run this and see:














We just iterated over a string. We can also define a specific number of iterations by using the range function:





















Which would be outputed as:























And by doing that we just printed 10 numbers. We can also use the for loop in dictionaries. So let's create a new dictionary called person.







We used the for loop and printed the key, the colon, and used the name of the dictionary and the key variable as the key. Let's print it to see how this is going to work:























This is the first part of the code and the continuation follows:























For this way we just listed all the elements of the dictionary. 

Just like conditionals loops can also be nested. We can use loops inside loops. We can also use loops inside conditionals, conditionals inside loops and so on.... So let's get the blog post variable we just posted. Remember to separate it....................




This is going to be a dictionary. We are going to change the brakets to curly brackets and add category-Python and assign to this key a list of blogposts. Then, let's add a new property to this dictionary, which is going to be let's say javascript, with a list of posts.


 continuation:



So this is how our dictionary is going to look like: 

print('-------------------------------------')

blog_posts = {"Python": ["The 10 coolest math functions in Python", "How to make HTTP requests in Python", "A tutorial about data types"], "Javascript": ["Namespaces in Javascript", "New functions available in ES6"]}

How can we print all the blog post by category?

we can do like: for category in blog_posts:

Everytime we use a for loop with a dictionary, every iterations the key: Python, is going to be assigned as the value of the variable category. So the first iteration of the loop Python is going to be assigned to the variable category. In this case we are going to print("Posts about", category). We are going to print post about the category which is python. Now we are going to start a new loop inside this loop.

for post in blog_posts[category] which is going to result in the first list- the 10 coolest..... by doing this we can just print(posts) and when it finishes it is going to start the first loop again. And then the next category is going to be Javascript . And then it is going to iterate over the list of Javascript. Let's see if this works:







This is how the code is going to look like. Let's run this code to see what happens:






























































And our code worked. Now we can see posts about Python. It lists all the posts. Posts about Javascript and the two posts about Javascript. Really cool, right? This might be a bit confusing at the beginning. So if you have any questions, just leave them in the comment section. This is all for this lesson, so I will see you in the next lesson.

 

Python programming tutorial 12.

 While Loops

Loops are very important in computer programming. Loops are structures of repetition. We use loops to repeat the same lines of code multiple times. We can also use loops to iterate over lists, tuples, dictionaries, and even strings, as I will show you later. Let's start with the "while loop." First, let's start with a variable called while x and assign a value of zero. Then let's create a list of people that is going to start as an empty list, and then we start a loop writing a condition. Let's visualize it below. 











As you can see there's an indentation just like the "if structure", so everything that is aligned under the indentation is going to be inside the while loop so if this test "while  x  <  5:"  returns true it is going to go inside this loop. Once inside let's create a new variable called a person and append this person to the list called people









We are done here, but if we leave it like this, this loop is going to run forever. Because when we finish here, it is going to keep running again and again until x <  5 doesn't run anymore. However, this is not going to happen because we are not changing the value of x. 

So what we need to do is in every iteration of this loop, we have to increment the value of x.

We can do it by typing x  =  x + 1. This is one way of incrementing the value of a variable. You can also increase the value of x by using the increment operator, x  +=  1. This mean x equals x plus one. So this is going to run in a loop until the test returns false. When this happens then we are going to continue with our program.  As we run the program, you can enter any name of your choice and the list will be updated. 









 















Our program runs the loop five times, and when that test returns fault, it continues with the rest of the code, which was this ['John', 'Mary', 'Peter', 'Paul', 'George'] print statement. We could have done this with fewer lines of code. 

Since we are adding people to a list in every iteration of the loop, we can use the length of the list to control the loop. Instead of using x, we can use the length of the list called people, as shown below.



So I erased x = 0 and applied the len(length) function to the list, which contains zero people [] in the first iteration of the loop. However, as we add more people to the list, the number of people in the list is going to be greater than 0. And when the number of people is 5 or greater than 5, we are going to jump outside of the loop, so in this case we don't need to increment the value of any variable; hence, x += 1 must be erased. 



  And... we just this that. Let's try running it again to see what happens.











And we have the same results. We can also jump out of loops using the break statement. Let's write a program to make a guess game. 

In this case, let's start with a variable called number, assigning a value of 5 to it. Secondly, let's create a variable called guess and ask for a user's input. Note that I will compare the user input into an integer so that we can compare with the number 5. We will give the user multiple chances so that he can guess; for that, we can use a loop. In this case, let's start a loop that we will run forever. 






Meaning every time that test returns true, the loop is going to be executed. So in this case, the loop is going to be executed forever unless we stop the execution with a break statement, which is what we are going to do!

 


 So this means inside the loop, if guess equals (we use double equal signs to differentiate it from assigning a value or variable in other parts of the code), a number, which is 5, means the user guesses the number correctly. In this case, we are going to use a break statement, which will stop the execution of the loop and jump outside of the loop. If that doesn't happen, then the user has to guess again under the else statement. Okay, let's run it to see if our game is working. 








let's try number 2 and see what happens. 






What just happened here is that the two that was assigned to the variable guess: 


 


as a result, we entered the loop. Since the guess is not equal to number,





we entered the else statement. And now we have infinite chances until we guess the number correctly. So let's try some random numbers.






This is going to run forever until the user guess the right answer. After the user guess the right answer we should have written something like you guessed the right answer to notify the user (print("You guessed it. I was thinking about", number)).

 So let's try again:









And it worked. We can even make our game even cooler by picking a random number. We can use the random module for that. So before starting the program we can import the random module. So now the number is going to be random.randint(0,10). It is going to pick a random integer in the range of 1 to 10.








But we still don't know what the number is, so we have to guess.












Really cool right? That was all for this lesson. In our next lesson we will learn about the "FOR LOOP"

See you next time.


Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...