The int and float data types
We have already seen a few examples of how Python can do numerical computations. Python actually uses two different data types to store numerical values. The int data type is used to store integers, while the float data type is used to store non-integral floating point numbers.
If you store an integer value in a variable, Python will automatically use the int data type for that quantity. If you do arithmetic with variables with integer values the results of those computations will be integers, except in the case of division. Since the result of many divisions involving two integer operands can not be represented as an integer, Python defaults to converting the result of every division with two integer operands to the float data type.
If one or more of the operands in any arithmetic operation are floats, the result will always be a float.
Python also includes a couple of special operators for use with int data, the integer division operator // and the integer remainder operator %. The integer division operator returns the quotient that results when we divide one int into another.a = 17 b = 5 q = a//b # q now has the value 3
The integer remainder operator yields the remainder that is left over after we divide one int by another int.r = a % b # r now has the value 2
Converting numbers to text and text to numbers
Python also features a string data type, which is used to store text. You can create text in one of two ways in a Python program. You can assign a text literal to a variable, which looks like this:greeting = 'Hello, World!'
You can also obtain some text by using the input() command, which prompts the user to enter some text.name = input('Enter your name: ')
The text that appears in the input() is a prompt, which tells the user what information they are expected to enter. When your program reaches an input command it will display the prompt and wait for the user to type some input. As soon as the user hits enter, their text will be stored in the variable that you assigned the input result to.
The input() command always returns text as its result, even in cases where you prompt the user to enter a number. If you want to interpret the text the user entered as a numeric type, you need to use a type conversion command. For example, if you want to interpret the user's input as an integer quantity you would use this form:age = int(input('Enter your age: '))
If you want to interpret the input as a floating point real number you use this form instead:height = float(input('Enter your height in meters: '))
An important operation that the string data type supports is concatenation, which glues strings together to form larger strings.greeting = 'Hello, ' + name
Concatenation only works with two string operands. If you want to use concatenation with other data types you will have to convert that data to a string by using the str() command.compliment = 'You look good for someone who is ' + str(age) + '.'
The if-else statement
The basic construct in Python for making decisions and acting on different cases is the if-else statement. The basic form of the if-else statement is this:if : # Statements to execute if is true else: # Statements to execute if is false
The if-else statement begins by performing a test whose outcome can be either true or false. If the outcome of the test is true, the set of statements in the first indented block gets executed. Otherwise, the statements in the block after else will get executed. Once the statements in the selected branch have run, execution continues with the next statement after the if-else.
The most common way to form tests for an if-else statement is by using comparison operators. Here is a table of the available comparison operators.operatormeaning==is equal to!=is not equal to<is less than>is greater than<=is less than or equal to>=is greater than or equal to
Note especially the == comparison test. A very common mistake that beginning programmers will make is to us = in place of == in a test. = means 'set the thing on the left to the value on the right' and not 'compare the thing on the left with the thing on the right.'
Here are two examples of the if-else statement in use.# First example x = float(input('Enter a value for x: ')) if x < 0: absX = -x else: absX = x print('The absolute value of x is '+str(absX)) # Second example p = float(input('Enter a value for p: ')) q = float(input('Enter a value for q: ')) if q == 0.0: print('Error: division by 0.') else: print('p/q = ' + str(p/q))
Note that it is perfectly legitimate to place one if-else statement inside another one. This is known as a nested if-else.age = int(input('Enter your age in years: ')) height = int(input('Enter your height in inches: ')) if age > 12: if height > 60: print('Welcome aboard.') else: print('You must be at least 5 ft tall to ride.') else: print('You are too young to ride the roller coaster.')
A useful alternative to putting one if-else statement inside another is being able to form a compound test. A compound test is a test made up of two or more ordinary tests joined together by the logical connectors and or or.
We can rewrite the previous example by saying that you must be both older than 12 and taller than five feet to ride the roller coster:age = int(input('Enter your age in years: ')) height = int(input('Enter your height in inches: ')) if age > 12 and height > 60: print('Welcome aboard.') else: print('You do not meet the requirements to ride.')
Python also allows the if-else statement to be constructed in a variety of variant forms. The first variant is that you can construct an if statement with only an if branch and no else branch.x = float(input('Enter x: ')) absX = x if x < 0: absX = -x
Another useful variant comes about when we need to do a series of comparisons in order to categorize something into more than two possible categories. One way to do this categorization is to use nested if-else statements.temp = int(input('Enter a Centigrade temperature: ')) if temp <= 0: state = 'solid' else: if temp < 100: state = 'liquid' else: state = 'gas' print('Water is a '+state+' at '+str(temp)+' degrees.')
This sort of categorization task comes up so often in practice that Python has a special variant of the if-else that makes use of an 'else-if' branch labeled with elif.temp = int(input('Enter a Centigrade temperature: ')) if temp <= 0: state = 'solid' elif temp < 100: state = 'liquid' else: state = 'gas' print('Water is a '+state+' at '+str(temp)+' degrees.')
Example program - making change
The following program demonstrates the use of integer arithmetic and if-else statements. The program prompts the user to enter an amount in pennies to make change for. The program then uses an algorithm to compute how many quarters, dimes, nickels and pennies need to be counted out to make change for that amount.# Get input cents = int(input('How many cents do you need to give out? ')) # Do computations quarters = cents // 25 cents = cents % 25 dimes = cents // 10 cents = cents % 10 nickels = cents // 5 pennies = cents % 5 # Print results print('Your change is') if quarters > 1: print(str(quarters)+' quarters') elif quarters == 1: print('1 quarter') if dimes > 1: print(str(dimes)+' dimes') elif dimes == 1: print('1 dime') if nickels == 1: print('1 nickel') if pennies > 1: print(str(pennies)+' pennies.') elif pennies == 1: print('1 penny.')
The program uses the following logic to compute the amount of each coin to use:quarters = cents // 25 cents = cents % 25 dimes = cents // 10 cents = cents % 10 nickels = cents // 5 pennies = cents % 5
Here is an example of how this works. Suppose we entered 87 cents.
- 87//25 is 3, so we hand out 3 quarters.
- After handing out the quarters, we have 87 - 3*25 = 12 or 87%25 = 12 cents left to hand out.
- 12//10 is 1, so we hand out 1 dime.
- After handing out the dime, we have 12 - 1*10 = 2 or 12%10 = 2 cents left to hand out.
- 2//5 is 0, so we hand out 0 nickels.
- 2%5 is 2, so we still have 2 cents to hand out.
- Finally, we hand out the 2 cents as 2 pennies.
To ensure that the output is nicely formatted with proper use of plural and singular forms, we use a set of if-else statements to help us to decide how to print the output. Can you see how the logic handles the case of 0 coins?