The int and float data typesWe 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 Show If you store an integer value in a variable, Python will automatically use the 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 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 numbersPython also features a greeting = 'Hello, World!' You can also obtain some text by using the name = input('Enter your name: ') The text that appears in the The 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 statementThe 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 <test>: # Statements to execute if <test> is true else: # Statements to execute if <test> 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 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.
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.') Compound TestsA 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 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.') Variant FormsPython 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 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 changeThe 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.
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? |