CHAPTER 2
While we discussed in the previous chapter how to create strings by placing text within quotation marks, it is important to note that numbers in Python require no such special treatment. If you’d like to use a number, simply include it in your source code. If you want to assign a number to a variable, use the pattern variable_name = number as shown in the following example.
Code Listing 74
height = 70 temperature = 98.6 |
It is important to note that Python supports both integers and floating point numbers. Integers are numbers without a decimal point, otherwise known as whole numbers. Floating point numbers however will always contain a decimal point. The data type for integers is int, while the data type for floating point numbers is float.
Keep in mind that the Python interpreter is capable of performing several operations using numbers. The following table lists the most commonly used numeric operations.
Table 1: Numeric Operators
Symbol | Operation |
|---|---|
+ | add |
- | subtract |
* | multiply |
/ | divide |
** | exponentiate |
% | modulo |
You are most likely familiar with the common symbols +, -, *, and /. The ** operator represents exponentiation, otherwise known as "raising to the power of." For example, 2 ** 4 means "2 raised to the power of 4." The written out equivalent to this is 2 * 2 * 2 * 2, which will result in an outcome of 16.
The modulo operation is performed by the percent sign. Put quite simply, it will return the remainder. For example, 3 % 2 is 1 because 3 divided by 2 is 1 with a remainder of 1. 4 % 2 returns 0 since 4 divided by 2 is 2 with a remainder of 0. In general, modulo arithmetic is done using non-negative integers. Modulo arithmetic with negative numbers can be very tricky. For example, -5 % 4 returns 3.
By making use of these symbols, Python allows you to perform mathematical calculations directly within the interpreter.
Code Listing 75
[jason@mac ~]$ python3 Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 00:54:21) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 2 + 3 5 >>> exit() [jason@mac ~]$ |
You can also assign the resulting value of a mathematical operation to a variable.
Code Listing 76
sum = 3 + 2 difference = 88 - 2 product = 4 * 2 quotient = 16 / 4 power = 3 ** 5 remainder = 7 % 3 print('Sum: {}'.format(sum)) print('Difference: {}'.format(difference)) print('Product: {}'.format(product)) print('Quotient: {}'.format(quotient)) print('Power: {}'.format(power)) print('Remainder: {}'.format(remainder)) |
Output:
Code Listing 77
Sum: 5 Difference: 86 Product: 8 Quotient: 4.0 Power: 243 Remainder: 1 |
Take note that even though the result of 16 / 4 is the integer 4, the floating point number 4.0 was displayed in the output created using the example in Code Listing 76. The division operator (/) performs floating point division, and will in every case return a floating point number and not an integer. Also, be aware that if you add an integer to a floating point number the result will always be a float.
The following example demonstrates the capability of Python to perform mathematical operations using variables.
Code Listing 78
sum = 3 + 4 difference = 200 - 2 new_number = sum + difference print(new_number) print(sum / sum) print(sum + 1) |
Output:
Code Listing 79
205 1.0 8 |
The following example establishes a variable named quantity and assigns it the numeric value 4. It also creates a variable named quantity_string and assigns it the string 4.
Code Listing 80
quantity = 4 quantity_string = '4' |
Keep in mind that if you try to perform a mathematical operation against a string, you will encounter an error. Try to be aware that if you surround a number with quotes it will become a string.
Code Listing 81
quantity_string = '4' total = quantity_string + 1 |
Output:
Code Listing 82
Traceback (most recent call last): File "string_test.py", line 2, in <module> total = quantity_string + 1 TypeError: Can't convert 'int' object to str implicitly |
If you are looking to convert a string into an integer, use the int() function and pass in the string to convert.
Code Listing 83
quantity_string = '4' total = int(quantity_string) + 1 print(total) |
Output:
Code Listing 84
5 |
In order to convert a string into a floating point number, use the float() function and pass in the string to convert.
Code Listing 85
quantity_string = '4' quantity_float = float(quantity_string) print(quantity_float) |
Output:
Code Listing 86
4.0 |
Comments can be a great benefit to us humans, but will be totally ignored by Python. The main benefit of comments is that they give you a way to document your code. For example, a comment can help summarize what is about to happen in a complex piece of code. This can be incredibly helpful if you or a fellow programmer need to look at the code at a later date. Using comments can quickly explain what the intention of the code was at the time it was written.
A single-line comment is prefixed with an octothorpe (#), which is also known as a pound sign, number sign, or hash.
Code Listing 87
# This is a comment. Python simply skips comments. |
If desired, you can also chain multiple single-line comments together.
Code Listing 88
# The following code: # Computes the hosting costs for one server. # Determines the duration of hosting that can be purchased given a budget. |
Another option is to create multi-line comments by using triple quotes. You can use either single quotes or double quotes. The comment will begin directly after the first set of triple quotes and will end directly before the following set of triple quotes.
Code Listing 89
""" The comment starts here. This is another line in the comment. Here is the last line of the comment. """ |
Here is another example.
Code Listing 90
""" This starts a comment down here! Python will not attempt to interpret these lines as they are comments. """ |
It is even possible to create a single line quote by using the triple quote syntax.
Code Listing 91
"""Yet another comment.""" |
If we go back to our "Pig Speak" exercise in the previous chapter, you can practice adding in some of your own comments to make your code clearer.
Code Listing 92
# Get the input from the user. text = input('What would you like the pig to say? ') # Determine the length of the input. text_length = len(text) # Make the border the same size as the input. print(' {}'.format('_' * text_length)) print(' < {} >'.format(text)) print(' {}'.format('-' * text_length)) print(' /') print(' ^..^ /') print('~( ( oo )') print(' ,, ,,') |
Unlike strings, numbers require no special decoration. When you enclose a number in quotes it will become a string.
Use the int() function to convert a string to an integer.
Use the float() function to convert a string to a float.
An octothorpe (#) will begin a single line comment.
Multiline comments must be enclosed with triple quotes (""").
In this exercise let's assume that you are planning to build a social networking service using your new Python skills. You make the decision to host your application on servers running in the cloud. Once you’ve selected a hosting provider, you want to know how much it will cost to operate per day and per month. You will launch your service using one server, and your provider will charge $1.02 per hour.
Try to write a Python program that will display the answers to the following questions:
How much will it cost to operate one server per day?
How much will it cost to operate one server per month?
The following is one way to use Python to find the answers to the preceding questions. Take note of the fact that comments are used throughout the code. Also, while this is one possible solution, keep in mind that there are multiple ways to go about solving the same problem.
Code Listing 93
# The cost of one server per hour. cost_per_hour = 1.02 # Compute the costs for one server. cost_per_day = 24 * cost_per_hour cost_per_month = 30 * cost_per_day # Display the results. print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day)) print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month)) |
Output:
Code Listing 94
Cost to operate one server per day is $24.48. Cost to operate one server per month is $734.40. |
Building upon the previous example, let's add some more information. Assuming that you have saved $1,836 to fund your new business venture, you are now wondering how many days you can keep one server running before your money runs out. Ideally though, you are hoping that your social network becomes incredibly popular and ultimately requires 20 servers to keep up with the demand. So, factoring in this information, how much will it cost to operate at that point?
Try writing a Python program that will display answers to the following questions:
How much will it cost to operate one server per day?
How much will it cost to operate one server per month?
How much will it cost to operate twenty servers per day?
How much will it cost to operate twenty servers per month?
How many days can I operate one server with $1,836?
Code Listing 95
# The cost of one server per hour. cost_per_hour = 1.02 # Compute the costs for one server. cost_per_day = 24 * cost_per_hour cost_per_month = 30 * cost_per_day # Compute the costs for twenty servers cost_per_day_twenty = 20 * cost_per_day cost_per_month_twenty = 20 * cost_per_month # Budgeting budget = 1836 operational_days = budget / cost_per_day # Display the results. print('Cost to operate one server per day is ${:.2f}.'.format(cost_per_day)) print('Cost to operate one server per month is ${:.2f}.'.format(cost_per_month)) print('Cost to operate twenty servers per day is ${:.2f}.'.format(cost_per_day_twenty)) print('Cost to operate twenty servers per month is ${:.2f}.'.format(cost_per_month_twenty)) print('A server can operate on a ${0:.2f} budget for {1:.0f} days.'.format(budget, operational_days)) |
Output:
Code Listing 96
Cost to operate one server per day is $24.48. Cost to operate one server per month is $734.40. Cost to operate twenty servers per day is $489.60. Cost to operate twenty servers per month is $14688.00. A server can operate on a $1836.00 budget for 75 days. |