Today we will continue talking about things we can do with numbers and strings in Python. We will go over a couple examples of doing math in programs, then a few more operations on both sorts of data.
Finally, we'll talk about another type of data, the boolean.
How could we write a program which asks the user for the cost of an item and then applies a 5% sales tax. The program should print the full cost of the item with tax.
cost = int(input("How much is the item?" ) total = cost * 1.05 print("The total cost is", total)
How could we write a program which will take in the radius of a circle, and print out the area and circumference?
The formulas for these are:
$A = \pi R^2$
$C = 2 \pi R$
# get input radius = int(input("What is the radius of the circle? " ) # do the area area = 3.1416 * (radius ** 2) print("The area is", area) # do the circumference circum = 2 * 3.1416 * radius print("The circumference is", circum)
A string is a sequence of one or more characters. A character is just a single symbol of text, such as a letter, numeral, punctuation or space. For instance, the string string "Hello World!" has 12 characters: 10 letters, a space, and an exclamation mark.
We can get the length of a string by using the
The following program will get a string from the user and then print how
long it is:
response = input("Enter a string: ") length = len(response) print("That string has", length, "characters.")
We can also get any individual characters out of a string if we want to. Each character in a string has an index. The index starts at 0 and goes up by 1 for each character. For instance, the string "Hello" has these indices:
The indices of a string
To get just one character from a string, we put the name of the string, then the index we want inside square brackets.
For example, we can write a program that prints out the first letter of our input like this:
response = input("Enter a string: ") first = response print(first)
How could we get the last character of a string to print out?
response = input("Enter a string: ") length = len(response) last = response[length - 1] print(last)
Sometimes our tax calculator program above will print prices that don't stay in the normal 2 decimal places of money values. For instance, if we pass 3.67, it will return 3.8535.
In order to fix this, we can round the result to 2 decimal places. This is
done with the
round command, which takes the number we want to round
and how many decimal places to round to:
>>> round(3.8535, 2) 3.85
round always rounds to the nearest place. For instance
round(4.7, 0) rounds up to 5, while
will round down to 4.
Copyright © 2018 Ian Finlayson | Licensed under a Creative Commons Attribution 4.0 International License.