Introduction Answers¶
Help Discovery Exercises¶
Count occurrence of word¶
- Make a multi-line string that contains the text of the declaration of independence (hint: copy-paste it from the file
declaration-of-independence.txtthat you downloaded to yourpython_classdirectory) - Count the number of times the phrase “people” appears in the declaration (hint: dig through the string documentation)
Answers
>>> declaration = """Action of Second Continental Congress,
... July 4, 1776.
... The unanimous Declaration of the thirteen united States of America,
... WHEN in the Course of human Events, it becomes necessary for one People to dissolve the Political Bands which have connected them with another, and to assume among the Powers of the Earth, the separate and equal Station to which the Laws of Nature and of Nature’s God entitle them, a decent Respect to the Opinions of Mankind requires that they should declare the causes which impel them to the Separation.
...
... WE hold these Truths to be self-evident, that all Men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the Pursuit of Happiness—That to secure these Rights, Governments are instituted among Men, deriving their just Powers from the Consent of the Governed, that whenever any form of Government becomes destructive of these Ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its Foundation on such Principles, and organizing its Powers in such form, as to them shall seem most likely to effect their Safety and Happiness. Prudence, indeed, will dictate that Governments long established should not be changed for light and transient Causes; and accordingly all Experience hath shewn, that Mankind are more disposed to suffer, while Evils are sufferable, than to right themselves by abolishing the forms to which they are accustomed. But when a long Train of Abuses and Usurpations, pursuing invariably the same Object, evinces a Design to reduce them under absolute Despotism, it is their Right, it is their Duty, to throw off such Government, and to provide new Guards for their future Security. Such has been the patient Sufferance of these Colonies; and such is now the Necessity which constrains them to alter their former Systems of Government. The History of the present King of Great-Britain is a History of repeated Injuries and Usurpations, all having in direct Object the Establishment of an absolute Tyranny over these States. To prove this, let Facts be submitted to a candid World.
...
... He has refused his Assent to Laws, the most wholesome and necessary for the public Good.
...
... He has forbidden his Governors to pass Laws of immediate and pressing Importance, unless suspended in their Operation till his Assent should be obtained; and when so suspended, he has utterly neglected to attend to them.
...
... He has refused to pass other Laws for the Accommodation of large Districts of People, unless those People would relinquish the Right of Representation in the Legislature, a Right inestimable to them, and formidable to Tyrants only.
...
... He has called together Legislative Bodies at Places unusual, uncomfortable, and distant from the Depository of their public Records, for the sole Purpose of fatiguing them into Compliance with his Measures.
...
... He has dissolved Representative Houses repeatedly, for opposing with manly Firmness his Invasions on the Rights of the People.
...
... He has refused for a long Time, after such Dissolutions, to cause others to be elected; whereby the Legislative Powers, incapable of Annihilation, have returned to the People at large for their exercise; the State remaining in the mean time exposed to all the Dangers of Invasion from without, and Convulsions within.
...
... He has endeavoured to prevent the Population of these States; for that Purpose obstructing the Laws for Naturalization of foreigners; refusing to pass others to encourage their Migrations hither, and raising the Conditions of new Appropriations of Lands.
...
... He has obstructed the Administration of Justice, by refusing his assent to Laws for establishing Judiciary Powers.
...
... He has made Judges dependent on his Will alone, for the Tenure of their Offices, and the Amount and Payment of their Salaries.
...
... He has erected a Multitude of new Offices, and sent hither Swarms of Officers to harrass our People, and eat out their Substance.
...
... He has kept among us, in Times of Peace, Standing Armies, without the consent of our Legislatures.
...
... He has affected to render the Military independent of and superior to the Civil Power.
...
... He has combined with others to subject us to a Jurisdiction foreign to our Constitution, and unacknowledged by our Laws; giving his Assent to their Acts of pretended Legislation:
...
... For quartering large Bodies of Armed Troops among us:
...
... For protecting them, by a mock Trial, from Punishment for any Murders which they should commit on the Inhabitants of these States:
...
... For cutting off our Trade with all Parts of the World:
...
... For imposing Taxes on us without our Consent:
...
... For depriving us, in many Cases, of the Benefits of Trial by Jury:
...
... For transporting us beyond Seas to be tried for pre-tended Offences:
...
... For abolishing the free System of English Laws in a neighbouring Province, establishing therein an arbitrary Government and enlarging its Boundaries, so as to render it at once an Example and fit Instrument for introducing the same absolute Rule into these Colonies:
...
... For taking away our Charters, abolishing our most valuable Laws, and altering fundamentally the forms of our Governments:
...
... For suspending our own Legislatures, and declaring themselves invested with Power to legislate for us in all Cases whatsoever.
...
... He has abdicated Government here, by declaring us out of his Protection and waging War against us.
...
... He has plundered our Seas, ravaged our Coasts, burnt our Towns, and destroyed the Lives of our People.
...
... He is, at this Time, transporting large Armies of foreign Mercenaries to compleat the Works of Death, Desolation, and Tyranny already begun with circumstances of Cruelty and Perfidy, scarcely paralleled in the most barbarous Ages, and totally unworthy of the Head of a civilized Nation.
...
... He has constrained our fellow Citizens taken Captive on the high Seas to bear Arms against their Country, to become the Executioners of their friends and Brethren, or to fall themselves by their Hands.
...
... He has excited domestic Insurrections amongst us, and has endeavoured to bring on the Inhabitants of our Frontiers, the merciless Indian Savages, whose known Rule of Warfare, is an undistinguished Destruction, of all Ages, Sexes and Conditions.
...
... In every stage of these Oppressions we have Petitioned for Redress in the most humble Terms: Our repeated Petitions have been answered only by repeated Injury. A Prince, whose Character is thus marked by every act which may define a Tyrant, is unfit to be the Ruler of a free People.
...
... Nor have we been wanting in Attentions to our British Brethren. We have warned them from Time to Time of Attempts by their Legislature to extend an unwarrantable jurisdiction over us. We have reminded them of the Circumstances of our Emigration and Settlement here. We have appealed to their native justice and Magnanimity, and we have conjured them by the Ties of our common Kindred to disavow these Usurpations, which, would inevitably interrupt our Connections and Correspondence. They too have been deaf to the Voice of Justice and of Consanguinity. We must, therefore, acquiesce in the Necessity, which denounces our Separation, and hold them, as we hold the rest of Mankind, Enemies in War, in Peace, Friends.
...
... We, therefore, the Representatives of the UNITED STATES OF AMERICA, in General Congress, Assembled, appealing to the Supreme Judge of the World for the Rectitude of our Intentions, do, in the Name, and by Authority of the good People of these Colonies, solemnly Publish and Declare, That these United Colonies are, and of Right ought to be, FREE AND INDEPENDENT STATES, that they are absolved from all Allegiance to the British Crown, and that all political Connection between them and the State of Great-Britain, is and ought to be totally dissolved; and that as FREE AND INDEPENDENT STATES, they have full Power to levy War, conclude Peace, contract Alliances, establish Commerce, and to do all other Acts and Things which INDEPENDENT STATES may of right do. And for the support of this Declaration, with a firm Reliance on the Protection of divine Providence, we mutually pledge to each other our Lives, our fortunes, and our sacred Honor.
... """
>>> declaration.lower().count("people")
10
Format decimal places¶
- Make a variable
costand set it to5.5 - Format a string that contains a dollar sign and the value of the
costvariable, formatted to two contain decimal places (“$5.50”)
Answers
>>> cost = 5.5
>>> "${:.2f}".format(cost)
'$5.50'
Use silly case¶
Alter the declaration of independence to make every word consist of a lower case character followed by all uppercase characters
Answers
>>> declaration.title().swapcase()
Count¶
Count the number of words in the declaration of independence.
Answers
>>> len(declaration.split())
1341
Count the number of lines in the declaration of independence.
Answers
>>> len(declaration.splitlines())
68
Conditional Exercises¶
Temperature Conditionals¶
Write some code that:
- sets a temperature variable
- prints out “Nice and cozy” if the temperature is between 65 and 75
- prints out “Too extreme” if the temperature is outside that range
Answers
>>> temperature = 80
>>> if 65 < temperature < 75:
... print("Nice and cozy")
... else:
... print("Too extreme")
...
Too extreme
Not a Robot¶
Write some code that:
- Sets a variable
sentenceto a sentence - Prints “Hi! I’m not a robot.” if the sentence includes the word “hello”
- Prints “Sure, why not” if the sentence includes the phrase “can I”
- Prints “I’m sorry, could you repeat that?” otherwise
Answers
Line Ordering¶
Write some code that:
- Sets a
my_namevariable equal to your first name - Sets a
their_namevariable to the name of one of the people sitting next to you - Prints “Before me in line” if their name comes before yours alphabetically
- Prints “After me in line” if their name comes after yours alphabetically
- Prints “We have the same name!” if your name is the same
Answers
Less, Greater, Equal¶
Write some code that:
- Creates two variables:
- sister_age: pick your favorite number from 0 to 100
- brother_age: pick your second favorite number in that range
- Write an if statement that prints out one of these three statements as appropriate:
- “Sister is older”: printed when sister_age is greater than brother_age
- “Brother is older”: printed when brother_age is greater than sister_age
- “Sister and brother are twins”: printed when sister_age is equal to brother_age
Answers
>>> sister_age = 83
>>> brother_age = 71
>>> if brother_age < sister_age:
... print("Sister is older")
... elif sister_age < brother_age:
... print("Brother is older")
... else:
... print("Sister and brother are twins")
...
Sister is older
De Morgan¶
Rewrite this if statement to use or instead of and:
>>> user = "taylor"
>>> level = 2
>>> if user != "root" and level < 3:
... print("Permission denied")
...
Permission denied
Answers
>>> user = "taylor"
>>> level = 2
>>> if not (user == "root" or level >= 3):
... print("Permission denied")
...
Permission denied