Exercise On Numbers

 Question

1) Create a program to calculate the area and circumference of a circle. Ask the user for the radius.

Formulas needed

Area  =  ฯ€ x r2

circumference =  2 x ฯ€ x r

where r = radius, and pi = 3.14

Good luck when you're done come back here to see the solution.


Solution

code:










output:







So our program is working, good luck out there. We would later look at how to create a calculator.

Python Programming Tutorial 6

Data Type: Numbers

There are two data types to represent numbers:

1. float

2. integers

There aren't many differences between them aside from the fact that a float has decimals. However, the operations we can perform in them are the same.

Python converts integers to floats automatically when an operation results in a number with decimals. Alright, let's get started by creating some variables and finding the type of these variables.













As you can see the type of num1 is an integer (int)

Now let's create a new variable called results and perform some operations.

results = num1 divided by num2!

Hit enter key, type results and it executes in the python terminal.

Let's have a pictorial view of it๐Ÿ˜:









And now we have decimals, and hence our variable results are floats. 

Verify with the code:

 type(results)

<class 'float'>

So int and float can work together, as we can see, and most of the time you do not need to worry if your variable is an integer or a float because Python will take care of it.

Note: When dealing with thousands of numbers, you do not need to use thousand separators like a comma (,)) because you might have unexpected results. For example, 100,323.60

Also note that the dot (.)) is used to separate decimals.















There is also the modulus operator (%), which works by dividing the first number by the second number; it takes the result; and instead of continuing the division, it stops there and returns the remainder. This can be used in some situations, like figuring out if a number is odd or even. Let's look into it.


















The result is going to be 1 for an odd number. 

Another operator is the double asterisk, which makes the power operation, i.e., 5 raised to the power 4 can be coded as 5 ** 4.

You can use the parenthesis to represent the order of our operation. For example: (2+2)/3

and even ((2+2)/3)/4. For your exercise you try it out and see the hierarchy in which the operations are executed. Let me know in the comment section if you have any problems.

These are some of the basic operators you can do with numbers. There are also some built-in functions that can be applied to numbers, for example, the round() function we used to convert kilometers to miles. If we pass only one argument, which is the number we want to round, 4.87765, and nothing more, it's going to return an integer. Let's see below:





We can also pass a second argument in the function which is the numbe of decimal places we want to round our number to.






To avoid confusing this with a thousand separator ( , ), you can space out the number of decimal places you are rounding to.

What if we want to do more complex mathematical operations like logarithmic functions and Trigonometric functions ?

One of the best things in Python is that we can import modules and extend our possibilities, and because of that there's nothing we can't do with Python.

In order to use the functions i just mentioned we must use a module we call math that comes with the Python installation. We can call this module by writing import math. Inside this module, the are hundreds of maths functions we can use! One of them is the factorial function. For example: math.factorial(5) which is 120. It can be solved mathematically as 5 * 4 * 3 * 2 * 1 = 120

We also have more round opotions; we can round up or down using the ceil or floor function.











We also find the log this way; This gives us the natural  logarithm of 20 to the base e.






As well as the pi value: 




These are just some examples, to learn learn more about the maths module go to google  and type: python maths module.





 




This is for python 3.












Go to the documentation, here you can explore functions you have available in the maths module.















There are also thousands of external modules made by other people that we need to install first, and then we can also import them.

I will also teach you how you can build your own modules. That's all we are going to learn about the Python math module ATM. Good luck and happy coding!

Exercise On Strings

Question1

1. Create a program that asks the user for his first name, his middle name and his last name. Then print:

"Your initials are_ _ _ _ _"


SOLUTION

code: 












Output:















Question2

Let's say your company has a product with this lot number: "037-00901-00027". 

037 is the country code. 00901 is the product code. 00027 is the batch number. 

Create a program to print: 

Country code: _ _ _

Product code: _ _ _

Batch code: _ _ _



SOLUTION

code: 








output:




Using the individual index we learnt from indexing, We printed out the various components of our lot number. 

Good Luck. See you next time! 








Python Tutorial 5

 Data Types: Strings

A string is a sequence of characters. (A string can be a text, a sentence or multiple sentences, It could be a word or a single character)

Let's create a new string and learn something cool.

  • Let's create a new variable called myString 

We can see the data type of our variable using the type() function.

 





  • As you can see 'str' stands for string which means text!
  • How did Python know we passed a string?
  • ans: It's inside a quotation marks " " 

Note; Strings should always be inside quotation marks! And if you pass a number inside  quotation marks it would be stored as a string not an integer!

  • lets try 40 in quotation marks and checck the data type.







  • Actually this is the correct way of storing numbers that are not used for calculation. eg. kkamenyoh111@gmail.com, an invoice number or a zip code!
  • We can also use a single quotation mark ' ' , you just can't mix them. When you start with a single quotation mark,  you should end with a single quotation mark and not double as this will result in problems.
  • These can be useful when we want to use quotation marks inside our string.

Example:



You can see that " meet me at 5 " turned to color black instead of green.

Python thinks the string ends at " She said ", it does understand what your trying to do afterwards.

So if you want to do something like that you can use single quotation marks outside  the text, so you can use double inside.




I'm glag you're following. If you don't understand anything just leave it in the comment section and I will respond.

Okay let's continue.....

In a string every character has it's own index, starting from zero.

We can access an index by using braces [ ]. 

Steps

1. Use the name of the variable

2. Using braces we can tell the index we want to get

3. Let's get the first, second and last character









  • A string also has a length(the number of characters).
  • We can get the length of a string by using the len( ) function.




  • Meaning we have 25 characters in our string.

More example:






With these 3 characters we know that our first character is index 0, second is 1, and third is 2.

So no matter the length of our string the last character is going to be our [ length - 1 ]







And it is going to work no matter the size of our string.

This formula is going to be very important when we start treating loops in this course!

Slicing

  • We can also get part of a string using a technique called slicing.

Example:

Let's say we have a string that represents a bank account number, where the first two characters indicate the country.








As you can see first index [0 : 2] which is G is included but the second index [0 : 2] which is 2, is not not included. So we got from G to 2 but not including 2!

Example 2:

Lets put the country code in the end.





And that's how we do it.

You can try and have some more fun as much as you want.

We already talked about concatenation using the + sign.

ex. 





  • We concatenated with space as seen above.
  • But we have to be careful when we have different data type.

ex. ๐Ÿ‘‰๐Ÿ‘‰๐Ÿ‘‰๐Ÿ‘‰➡











  • You can use either the str() function to convert the number to a string before concatenating or simply use the string quotation marks.

Now we know the basics of strings. We will learn more about strings as we advance in the course. 

SUMMARY

Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:06:47) [MSC v.1914 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> myString = " Some text "
>>> #checking data type using the type function
>>> type(myString)

Output:
<class 'str'>

>>> myString = "40"
>>> type(myString)

Output:
<class 'str'>
>>> myString = ' She said " meet me at 5 " '
>>> myString

Output:
' She said " meet me at 5 " '
>>> myString[0]

Output:
' '
>>> myString[1]

'S'
>>> # let's get the last character, the last character of a string is -1
>>> myString[-1]

Output:
' '

See you in our next tutorial. Good luck!


Exercise On Variables and Input Functions

Question:

Create a program that asks the user for a number of kilometers, converts it to miles, and prints the results to the user.

To perform this exercise, you need the conversion rate:

1 mile = 1.609344 km

Good luck, and when you finish, come back here to see the solution.

 

  • We are starting a new file. In your Python interpreter, go to File from the menu.
  • Then select the new file where we are going to write our computer program.
  • Save your file as Ex01_km2miles for easy identification.


We will get the number of km, divide by the conversion rate, and print the output.

 

Follow the red comments in the program carefully.









Now run your program:









  • As you can see, our program has been beautifully executed. The user input has made our program interactive for the user.
  • But you notice our program has so many decimal places, so we are going to round it using the round() function.
  • So let's go back to our program and edit our program.








 When rounding the number of miles, we punctuate it with a comma (,)) and type the number of places we want to run it to.







And now we have only 4 decimal places. Fantastic, our program is working!

We will learn more functions like this when we learn about numbers.

 Summary

km = float( input("Type the number of kilometers: ") )
miles = km / 1.609344

print(km, "km = ", round(miles,4), "miles")

Output:

Type the number of kilometers: 34
34.0 km =  21.1266 miles

If you have any questions feel free to leave it in the comment section.

Good luck happy coding!


Beginner Python Tutorial 4

In this lesson, we will learn about input functions.

We are going to make our program more dynamic by getting user input! In order to do that, we are going to use the input function!

Let's create some variables:

number 1 and number 2instead of assigning a static value to our variable, we can make it dynamic with the input function. see below!








With the input function outside the value, we will pass the instructions for the user inside parenthesis with double quotation marks, making it a string (text), i.e., "Please enter the first number: ".

Note that this time we are working with the Python interpreter!

1. Press enter! and it will ask you to type the first number. I chose 4, but you can choose any number of your choice.

2. Type or print the variable number to see the results. We can see that the value 4 has been assigned or stored in the variable number.

Let's do the same for number 2, and then we can perform some basic operations!










You can see that as we added 4 + 8, it gave us 48, and here's why: As I told you earlier, our values are stored as strings (text), so we are dealing with a data type called string. In our next lesson, we will learn more about data types in detail. 

Here's how to check the data type of a variable: just use the type function, for instance: 




Now we can see that the type of this variable is'str', which means string. 

Operators like addition (+)  work differently depending on the data type. If we have numbers, the + sign makes a sum of those numbers, but if we have strings, the + sign makes a concatenation of those strings. That's why we just put 4 and 8 together!

Here's something cool we can do with concatenation.

Let's create a variable called first name and last name, assigning a string to each variable.




Now let's use concatenation to create an email address.

I did concatenate my first name and last name with a period (. ), and I concatenated my last name with another string ("@gmail.com").

Type enter to see results!




Remember, with our numbers, we couldn't perform the right operation, and here's how to do it.

We are going to convert our user input from a string to a number.

There are two types of numbers in Python.

1. floats: numbers with decimals. eg. 53.422223

2. integers: numbers without decimals, e.g., 34

For our program, let's allow the user to type decimal numbers in the format the format he wants:

Let's convert the input to a float using the float function. 




We converted the variable from text to numbers using the float function.

Now let's get into our program from the IDE. 









Copy and replace numbers 1 and 2 from the Python interpreter, and replace them with number one on the IDE. Remember to make the conversion by adding a float function to the value of the variable. Now let's save it and see what we get:













Now our program looks flexible and organised! We can run it now and see if our program is working.





Put in your desired numbers and see if this is the working gas shown above.

Now that our program is dynamic, if we run it again and type different values in the interpreter, here's what we get:










In our next tutorial, we are going to have an exercise. Follow for more! If you have any questions, feel free to leave them in the comment section. Good luck!


Exercise on Variables


EXERCISE

Write a program that calculates the area of a square and prints the area of the square.

Try your hands on this exercise before looking at the solution below.

SOLUTION

In this program, we will create two variables named length and width and store the value of our preference in the variables; in this case, I chose 4 and 6. We could have used actual variables like x and y for the length and width, but when the program becomes more complex, it may seem confusing.

Let's save our program using Command S or Control S and run our program to see if it is working. 







And it is working. We can also change the value of our variables and run it by pressing F5.
 

















You can also do similar operations using the division sign (/), addition sign (-), etc.
 
Our program is too static; anytime we want to change a variable, we have to change something in the code. In our next tutorial, we will learn how to make our program more dynamic. We will learn how to assign user input to a variable.

SUMMARY
print("This program calculates the area of a square")
length = 6
width = 10
print("The length and width of the square are", length, "and", width, "respectively")
print("The area of the square is:", length * width)

Output:
This program calculates the area of a square
The length and width of the square are 6 and 10 respectively
The area of the square is: 60
>>> 











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...