Text
stringlengths
1
9.41k
The source amount and the exchange rate are of type float. Giving these objects significant names (rather than x, y, z, …) makes the code easy to read and understand. Now, on to the calculation.
Since we have the rate expressed as a ratio of the value of a unit of the source currency to a unit of the target currency, all we need to do is multiply. ``` target_amount = source_amount * exchange_rate ``` See how choosing good names makes things so clear?
You should aim for similar clarity when naming objects and putting them to use. The only thing left is to print the result.
Again, we’ll use f-strings, but this time we’ll include format specifiers to display the results to two decimal places of precision. ``` print(f'{source_amount:,.2f} {source_label} is worth ' f'{target_amount:,.2f} {target_label}') ``` Putting it all together we get: ``` """ Currency Converter Egbert Por...
We will convert {source_label} ' f'to {target_label}.') source_prompt = f'Enter the amount in {source_label} ' \ f'you wish to convert: ' ex_rate_prompt = f'Enter the exchange rate ' \ f'({source_label}/{target_label}): ' source_amount = float(input(source_prompt)) exchange_rate = ...
By choosing good names we’ve made comments unnecessary! We’ll revisit this program, making improvements as we acquire more tools. Feel free to copy, save, and run this code.
There are lots of websites which provide exchange rates and perform such conversions.
One such [website is the Xe Currency Converter (https://www.xe.com/currencyc](https://www.xe.com/currencyconverter/) [onverter/).](https://www.xe.com/currencyconverter/) ###### 7.11 Format specifiers: a quick reference Format specifiers actually constitute a “mini-language” of their own.
For a complete reference, see the section entitled “Format Specification Mini[Language” in the Python documentation for strings (https://docs.pyt](https://docs.python.org/3/library/string.html) [hon.org/3/library/string.html).](https://docs.python.org/3/library/string.html) Remember that format specifiers are optionall...
The format specifier is separated from the replacement expression by a colon.
Examples: ``` >>> x = 0.16251` >>> f'{x:.1%}' '16.3%' >>> f'{x:.2f}' '0.16' >>> f'{x:>12}' ' 0.16251' ``` ----- ``` >>> f'{x:.3E}' '1.625E-01' ``` Here’s a quick reference for some commonly used format specifiers: option meaning example `<` align left, can be combined with width `<12` `>` align ...
These functions take strings, so the issue isn’t the type of the argument.
Rather, it’s an issue with the value of the argument—some strings cannot be used to construct an object of numeric types. For example, ``` >>> int('5') 5 >>> int('5.0') Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '5.0' >>> int...
The other two calls fail with a ValueError. ``` int('5.0') fails because Python doesn’t know what to do about the ``` decimal point when trying to construct an int.
Even though 5.0 has a corresponding integer value, 5, Python rejects this input and raises a ``` ValueError. ``` The last example, int('kumquat'), fails for the obvious reason that the string 'kumquat' cannot be used to construct an integer. What about the float constructor, float()?
Most numeric strings are valid arguments to the float constructor.
Examples: ----- ``` >>> float('3.1415926') 3.1415926 >>> float('7') 7.0 >>> float('6.02E23') 6.02e+23 ``` The first example should be obvious.
The second example is OK because '7' can be used to construct a float. Notice the result of float('7') is 7.0.
The third example shows that the float constructor works when using scientific notation as well. Python has special values for positive and negative infinity (these do come in handy from time to time), and the float constructor can handle the following strings: ``` >>> float('+inf') inf >>> float('-inf') -inf ...
It turns out that this can never fail, since all objects in Python have a default string representation. There’s no object type that can’t be turned into a string!
Even things like functions have a default string representation (though this representation isn’t particularly human-friendly). Example: ----- ``` >>> def f(): ...
return 0 ... >>> str(f) '<function f at 0x10101ea70>' ###### 7.13 Exercises ``` **Exercise 01** The following code has a bug.
Instead of printing what the user types, it prints <built-in function input>.
What’s wrong and how would you fix it? ``` input('Please enter your name: ') print(input) ``` **Exercise 02** Which of the following are valid arguments to the int() constructor? (Try these out in a Python shell.) a.
'1' b. '1.0' c. '-3' d. 5 e. 'pumpkin' f. '1,000' g. '+1 802 555 1212' h. '192.168.1.1' i. '2023-01-15' j. '2023/01/15' k. 2023-01-15 l.
2023/01/15 **Exercise 03** Which of the following are valid arguments to the float() constructor? (Try these out in a Python shell.) a. 3.141592 b. 'A' c. '5.0 + 1.0' d. '17' e.
'inf' (Be sure to try this one out! What do you think it means?) f. 2023/01/15 g.
2023/1/15 ----- **Exercise 04** Write a program which prompts the user for two floating-point numbers and displays the product of the two numbers entered.
Example: ``` Enter a floating-point number: 3.14159 Enter another floating-point number: 17 53.40703 ``` Notice here that the second input is an integer string.
It’s easy to treat an input like this as an integer, just as easily as we could write “17.0” instead of “17”. ``` >>> float(17) 17.0 ``` **Exercise 05** Write a program which prompts the user for their name and then prints ‘Hello’ followed by the user’s name.
Example: ``` What is your name?
Egbert Hello Egbert ``` ----- #### Chapter 8 ### Branching and Boolean expressions In this chapter, we’ll further our understanding of Booleans and Boolean expressions, learn about branching and flow control, and learn some convenient string methods. **Learning objectives** - You will learn more about Boolea...
These take their name from the 19th century mathematician and logician George Boole.
His motivation was to systematize and formalize the logic that philosophers and others used, which had come down to us from ancient Greece, primarily due to Aristotle. The fundamental idea is really quite simple: we have truth values— _true or false—and rules for simplifying compound expressions._ It’s easiest to expla...
We’ll start with informal presentation, and then formalize things a little later. Say we have this sentence “It is raining.” Now, either it is, or it is not raining.
If it is raining, we say that this sentence is true. If it is not raining, we say that this sentence is false. We call a sentence like this a proposition. Notice that there is no middle ground here.
From our perspective, a proposition like this is either true or false. It can’t be 67% true and 33% false, for example.
We call this the law of the excluded middle. Another way of stating this law is that either a proposition is true, or its negation is true.
That is to say, either “It is raining” is true or its _negation, “It is not raining” (or “It is not the case that it is raining”) is_ true.
One or the other.[1] What does this mean for us as computer programmers?
Sometimes we want our code to do one thing if a certain condition is true, and do something different if that condition is false (not true).
Without this ability, our programs would be very inflexible. But before we get to coding, let’s learn a little more about Boolean _expressions._ ###### Boolean expressions What is a Boolean expression?
Well, true and false are both Boolean expressions. We can build more complex expressions using the Boolean connectives not, and, and or. We often use truth tables to demonstrate.
Here’s the simplest possible truth table.
We usually abbreviate true and false as T and F, respectively, but here we’ll stick with the Python Boolean literals True and False. Expression Truth value ``` True True False False ``` 1There are some logicians who reject the law of the excluded middle.
Consider this proposition called the liar paradox or Epimenides paradox: “This statement is false.” Is this true or false? If it’s true it’s false, if it’s false it’s true!
Some take this as an example of where the law of the excluded middle fails.
Thankfully, we don’t need to worry about this in this textbook, but if you’re curious, see: Law of the excluded middle (Wikipedia).
There’s even an episode in the original Star _Trek television series, in which Captain Kirk and Harry Mudd defeat a humanoid_ [robot by confronting it with the liar’s paradox.
You can view it on YouTube: https:](https://www.youtube.com/watch?v=QqCiw0wD44U) [//www.youtube.com/watch?v=QqCiw0wD44U.](https://www.youtube.com/watch?v=QqCiw0wD44U) ----- True is true, and false is false (big surprise, I know). Now let’s go crazy and mix it up.
We’ll begin with the Boolean connective not.
not simply negates the value or expression which follows. Expression Truth value ``` True True False False not True False not False True ``` Now let’s see what happens with the other connectives, and and or. Some languages have special symbols for these (for example, Ja...
In Python, we simply use and and ``` or.
When we use these connectives, we refer to the expressions being ``` connected as clauses. Expression Truth value ``` True and True True True and False False False and True False False and False False ``` So when using the conjunctive and, the expression is true if and onl...
In all other cases (above) the expression is false. Here’s or. Expression Truth value ``` True or True True True or False True False or True True False or False False ``` You see, in the case of or, as long as one clause is true, the entire expression is true.
It is only when both clauses are false that the entire expression is false. We refer to clauses joined by and as a conjunction. We refer to clauses joined by or as a disjunction.
Let’s try this out in the Python shell: ``` >>> True True >>> False False >>> not True False >>> not False True >>> True and True ``` ----- ``` True >>> True and False False >>> False and True False >>> False and False False >>> True or True True >>> True or False True >>> F...
Usually, we want to test some condition to see if it evaluates to True or False. Then our program does one thing if the condition is true and a different thing if the condition is false.
We’ll see how this works in another section. ###### De Morgan’s Laws When working with Boolean expressions De Morgan’s Laws provide us with handy rules for transforming Boolean expressions from one form to another.
Here we’ll use a and b to stand in for arbitrary Boolean expressions. `not (a or b)` is the same as `(not a) and (not b)` `not (a and b)` is the same as `(not a) or (not b)` You can think of this as a kind of distributive law for negation.
We distribute the not over the disjunction (a or b), but when we do, we change the or to and.
By the same token, we distribute not over the conjunction (a and b), but when we do, we change the and to or. You’ll see these may come in handy when we get to input validation (among other applications). ###### Supplemental information If you’d like to explore this further, here are some good resources: [• Stanford...
Let’s try it and find out! ``` >>> a = 'duck' >>> b = 'swan' >>> a == b False >>> a > b False ``` ----- ``` >>> a < b True >>> a >= b False >>> a <= b True >>> a != b True >>> not (a == b) True ``` What’s going on here?
When we compare strings, we compare them _lexicographically. A string is less than another string if its lexicographic_ order is lower than the other.
A string is greater than another string if its lexicographic order is greater than the other. ###### What is lexicographic order? Lexicographic order is like alphabetic order, but is somewhat more general.
Consider our example ‘duck’ and ‘swan’. This is an easy case, since both are four characters long, so alphabetizing them is straightforward. But what about ‘a’ and ‘aa’? Which comes first?
Both start with ‘a’ so their first character is the same. If you look in a dictionary you’ll find that ‘a’ appears before ‘aa’.[2] Why?
Because when comparing strings of different lengths, the comparison is made as if the shorter string were padded with an invisible character which comes before all other characters in the ordering.
Hence, ‘a’ comes before ‘aa’ in a lexicographic ordering. ``` >>> 'a' < 'aa' True >> 'a' > 'aa' False ``` The situation is a little more complex than this, because strings can have any character in them (not just letters, and hence the term “alphabetic order” loses its meaning).
So what Python actually compares are the code points of Unicode characters.
Unicode is the system that Python uses to encode character information, and Unicode includes many other alphabets (Arabic, Armenian, Cyrillic, Greek, Hangul, Hebrew, Hindi, Telugu, Thai, etc.), symbols from non-alphabetic languages such as Chinese or Japanese Kanji, and many special symbols (®, €, ±, ∞, etc.). Each cha...
In comparing strings, Python compares these values.[3] 2Yes, “aa” is a word, sometimes spelled “a’a”.
It comes from the Hawai’ian, meaning rough and jagged cooled lava (as opposed to pahoehoe, which is very smooth). 3If you want to get really nosy about this, you can use the Python built-in function ord() to get the numeric value associated with each character.
E.g., ``` >>> ord('A') 65 ``` ----- Thus, 'duck' < 'swan' evaluates to True, 'wing' < 'wings' evaluates to True, and 'bingo' < 'bin' evaluates to False. ``` >>> 'duck' < 'swan' True >>> 'wing' < 'wings' True >>> 'bingo' < 'bin' False ``` Now, you may wonder what happens in alphabetic systems, like Engli...
This is fine for some programs, but it’s rather inflexible.
Sometimes we want our program to respond differently to different conditions. Imagine we wanted to write a program that calculates someone’s income tax.
The US Internal Revenue Service recognizes five different filing statuses: ``` >>> ord('a') 97 >>> ord('b') 98 >>> ord('£') 163 ``` See also: Joel Spolsky’s The Absolute Minimum Every Software Developer Ab_solutely, Positively Must Know About Unicode and Character Sets (No Excuses!)_ last seen in the wild at https://w...
Obviously, this cannot be done in a strictly linear fashion. Instead, we’d want our program to be able to make decisions, and follow different branches, depending on the results of those decisions. This example of an income tax program is by no means unusual.
In fact, most real-world programs involve some kind of branching. When our program includes branches, we execute different portions of our program depending on certain conditions.
Which conditions might those be?
It depends entirely on the program we wish to write. Thus, most programming languages (Python included) allow for con_trol flow—which includes branching and conditional execution of code._ How do we do this?
In Python, we accomplish this with if, elif and ``` else statements (or combinations thereof). ###### 8.4 if, elif, and else if, elif, and else work with Boolean expressions to determine which ``` branch (or branches) our program will execute. Since tax preparation is complicated, let’s consider more modest examples....
") if user_guess == secret_word: print("You WIN!") else: print("You LOSE!") ``` Here’s another example, but this time we’re using a nested if statement and an elif (which is a portmanteau of “else” and “if”): ``` """ CS 1210 What's for dinner? """ bank_balance = float(input('What is your bank bal...
')) if bank_balance < 20.0: meal_points = input('Do you have any meal points?
y/n: ') if meal_points == 'y': print('Eat at the dining hall.') else: print('Eat that leftover burrito.') elif bank_balance < 50.0: print('Order pizza from Leonardo\'s') else: print('Go out to Tiny Thai in Winooski with a friend!') ``` First we prompt the user for their bank balance.
If this amount is less than $20.00 then we prompt the user again to find out if they have any meal points left.
If they do, that is, if meal_points == 'y', we print “Eat at the dining hall.” If not, we print “Eat that leftover burrito.” Now, what happens if that very first condition is false?
If that’s false, we know we have more than $20.00, so our next comparison is: ``` elif bank_balance < 50.0: ``` ----- Why not ``` elif bank_balance >= 20 and bank_balance < 50.0: ``` you might ask?
Because we only reach the elif if the first condition is false.
There’s no need to check again. So if the bank balance is greater than or equal to $20.00 and less than $50.00 we print “Order pizza from Leonardo’s”. Now, what if the bank balance is greater than or equal to $50.00?
We print “Go out to Tiny Thai in Winooski with a friend!”. We can have a single if statement, without elif or else.
We can also, as we’ve just seen, write compound statements which combine if and ``` else, if and elif, or all three, if, elif, and else.
We refer to each block ``` of code in such compound statements as clauses (distinct from clauses in a compound Boolean expression). ###### Some important things to keep in mind 1.
If we have a compound if/else statement in our program either the body of the if clause is executed or the body of the else clause is executed—never both. 2.
If we have a compound if/elif/else statement in our program, the body of only one of the branches is executed. ###### Supplemental resources [For more on control of flow, see: https://docs.python.org/3/tutorial/c](https://docs.python.org/3/tutorial/controlflow.html) [ontrolflow.html](https://docs.python.org/3/tutoria...
Most everything in Python has a truth value.
As noted earlier, we refer to the truth values of anything other than Booleans with the whimsical terms “truthy” and “falsey” (we also use the terms “truthiness” and “falsiness”). When used in Boolean expressions and conditions for loops or branching (if/elif), truthy values are treated (more-or-less) as True, and fals...
That is, we did not validate the input. Validation of input is a crucial part of any program that accepts user input. Users sometimes provide invalid input.
Some reasons for this include: ----- - The prompt was insufficiently clear. - The user did not read the prompt carefully. - The user did not understand what kind of input is needed. - The user was being mischievous—trying to break the program. - The user made a typo or formatting error when entering da...
The first that we’ll learn right now is simple _bounds checking._ Bounds checking is an approach to input validation which ensures that a value is in some desired range.