Python Syntax + Strings and Console Output

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

from datetime import datetime now = datetime.now() print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second) ... 8/7/2017 20:31:16

Grand Finale We've managed to print the date and time separately in a very pretty fashion. Let's combine the two! from datetime import datetime now = datetime.now() print '%s/%s/%s' % (now.month, now.day, now.year) print '%s:%s:%s' % (now.hour, now.minute, now.second) The example above will print out the date, then on a separate line it will print the time. Let's print them all on the same line in a single print statement! Instructions 1. Print the date and time together in the form: mm/dd/yyyy hh:mm:ss. To start, change the format string to the left of the % operator. Ensure that it has 6 %s placeholders. Put slashes and colons and a space between the placeholders so that they fit the format above.Then, change the variables in the parentheses to the right of the % operator. Place the variables so that now.month, now.day, now.year are before now.hour, now.minute, now.second. Make sure that there is a ( before the six and a ) after them.

from datetime import datetime now = datetime.now() print '%s/%s/%s' % (now.month, now.day, now.year) ... 8/7/2017

Hot Date What if we want to print today's date in the following format? mm/dd/yyyy. Let's use string substitution again! from datetime import datetime now = datetime.now() print '%s-%s-%s' % (now.year, now.month, now.day) # will print: 2014-02-19 Remember that the % operator will fill the %s placeholders in the string on the left with the strings in the parentheses on the right. In the above example, we print 2014-02-19 (if today is February 19th, 2014), but you are going to print out 02/19/2014. Instructions 1. Print the current date in the form of mm/dd/yyyy. Change the string so that it uses a / character in between the %s placeholders instead of a - character. Re-arrange the parameters to the right of the % operator so that you print now.month, then now.day, then now.year.

# Set count_to equal to the sum of two big numbers count_to = 80 + 100 # Write code above! print count_to ... 180

Math Great! Now let's do some math. You can add, subtract, multiply, divide numbers like this addition = 72 + 23 subtraction = 108 - 204 multiplication = 108 * 0.5 division = 108 / 9 Instructions 1. Set the variable count_to equal to the sum of two big numbers.

#Set spam equal to 1 using modulo on line 3! spam = 3 % 2 print spam ... 1

Modulo Our final operator is modulo. Modulo returns the remainder from a division. So, if you type 3 % 2, it will return 1, because 2 goes into 3 evenly once, with 1 left over. Instructions 1.Use modulo to set spam equal to 1. You can use any two numbers that will leave a remainder of 1 to do this.

"""Hey my name is Anthony and I like the New York Giants, Knicks, Rangers, Villanova Basketball"""

Multi-Line Comments The # sign will only comment out a single line. While you could write a multi-line comment, starting each line with #, that can be a pain. Instead, for multi-line comments, you can include the whole block in a set of triple quotation marks: """Sipping from your cup 'til it runneth over, Holy Grail. """ Instructions 1. Write a multi-line comment in the editor. It can be any text you'd like!

# Assign your variables below, each on its own line! caesar = "Graham" praline = "John" viking = "Teresa" # Put your variables above this line print caesar print praline print viking ... Graham John Teresa

Practice Excellent! Let's get a little practice in with strings. Instructions 1. Set the following variables to their respective phrases: Set caesar to "Graham" Set praline to "John" Set viking to "Teresa"

from datetime import datetime now = datetime.now() print '%s:%s:%s' % (now.hour, now.minute, now.second) ... 20:2:2

Pretty Time Nice work! Let's do the same for the hour, minute, and second. from datetime import datetime now = datetime.now() print now.hour print now.minute print now.second In the above example, we just printed the current hour, then the current minute, then the current second. We can again use the variable now to print the time. Instructions 1. Similar to the last exercise, print the current time in the pretty form of hh:mm:ss. Change the string that you are printing so that you have a : character in between the %s placeholders. Change the three things that you are printing from month, day, and year to now.hour, now.minute, and now.second.

"""Tell Python to print "Monty Python" to the console on line 4!""" print "Monty Python" ... Monty Python

Printing Strings The area where we've been writing our code is called the editor. The console (the window to the right of the editor) is where the results of your code is shown. print simply displays your code in the console. Instructions 1. Print "Monty Python" to the console.

"""Assign the string "Ping!" to the variable the_machine_goes on line 5, then print it out on line 6!""" the_machine_goes = "Ping!" print the_machine_goes ... Ping!

Printing Variables Great! Now that we've printed strings, let's print variables Instructions 1. Declare a variable called the_machine_goes and assign it the string value "Ping!" on line 5. Go ahead and print the_machine_goes in line 6.

"""This program creates a mad libs story where the user inputs words to fill in the blanks.""" print "Mad Libs has started" name = raw_input("What is the name of your main character?") adjective1 = raw_input("What is an adjective that describes this character?") adjective2 = raw_input("What is another adjective that describes the character?") adjective3 = raw_input("What is a third adjective that describes the character?") verb1 = raw_input("Please provide a verb for an action that this character will perform.") verb2 = raw_input("Please provide a second verb for an action that this character will perform.") verb3 = raw_input("Please provide a third verb for an action that this character will perform.") noun1 = raw_input("Please provide a noun for the story.") noun2 = raw_input("Please provide a second noun for the story.") noun3 = raw_input("Please provide a third noun for the story.") noun4 = raw_input("Please provide a fourth noun for the story.") animal = raw_input("Please provide an animal for the story.") food = raw_input("Please provide a food for the story.") fruit = raw_input("Please provide a fruit for the story.") number = raw_input("Please provide a number for the story.") superhero_name = raw_input("Please provide a superhero name for the story.") country = raw_input("Please provide a country for the story.") dessert = raw_input("Please provide a dessert for the story.") year = raw_input("Please provide a year for the story.") #The template for the story STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to %s to the rhythm of the %s, which made all of the %ss very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %ss ruled the world." print STORY % (adjective1, name, verb1, adjective2, noun1, noun2, animal, food, verb2, noun3, fruit, adjective3, name, verb3, number, name, superhero_name, superhero_name, name, country, name, dessert, name, year, noun4)

Python Mad Libs Python can be used for a variety of different tasks. In this project, we'll use Python to write a Mad Libs story! Mad Libs are stories with blank spaces that a reader can fill in with their own words. The result is usually a funny (or strange) story. Mad Libs require: Words from the reader (for the blank spaces) A story to plug the words into For this project, we'll provide you with the story (feel free to modify it), but it will be up to you to build a program that does the following: Prompt the user for input Print the entire Mad Libs story with the user's input in the right places Let's begin! Mark the tasks as complete by checking them off Python Mad Libs 1. It's helpful to let other developers know what your program does. Begin by including a multi-line comment that starts on line 1 that describes what your program does. You can use the instructions above to help you. Stuck? Get a hint 2. Let's first inform the user that the program is running. Print a message to let the user know that Mad Libs has started. Stuck? Get a hint 3. The story that we have provided you with is going to need a main character. Ask the user to input a name, then store the user's input in a variable. Note: It's common practice to use short, but descriptive variable names. Stuck? Get a hint 4. For our story, you will need to ask the user for three adjectives. Similar to Step 3, ask the user for input three separate times. Store each adjective that the user inputs into descriptive variables. Stuck? Get a hint 5. You'll also need to ask the user for three verbs. Just like in Step 4, ask the user for input three separate times. Store each verb in descriptive variables. Stuck? Get a hint 6. We're also going to need some nouns in our story. This time, ask the user to input four nouns. Store each noun into its own descriptive variable. Stuck? Get a hint 7. This is where the story can get really fun (and weird)! Ask the user to input one of each of the following: An animal A food A fruit A number A superhero name A country A dessert A year Make sure to save the input into variables. Stuck? Get a hint 8. At this point, we have all the words needed for the Mad Libs story. The next step is to insert all of the user's inputs into the blank spaces of the story. Take a look at the variable named STORY. It is set equal to a string that contains our story template. 9. Use string formatting to insert the user's inputs into the story. We already formatted some of the STORY string for you with %s, but it's up to you to finish the rest of the string formatting anywhere you see _. Stuck? Get a hint 10. Now it's time to tell your tale! The final line of code should print the story and insert the inputs into the right blanks. The user's inputs should be inserted in the following order (get ready!): First adjective Name First verb Second adjective First noun Second noun Animal Food Second verb Third noun Fruit Third adjective Name Third verb Number Name Superhero name Superhero name Name Country Name Dessert Name Year Fourth noun Stuck? Get a hint 11. Let's read our Mad Libs story! First, click Save. Then, in the terminal, type the following command and press "Enter" on your keyboard: python Madlibs.py Feel free to add to the story or modify it in anyway you want. Have fun!

print "Welcome to Python!" ... Welcome to Python!

Ready to learn Python? Click Run to continue

# Reassign meal on line 7! meal = 44.50 tax = 6.75 / 100 tip = 15.0 / 100 meal = meal + meal*tax

Reassign in a Single Line Okay! We've got the three variables we need to perform our calculation, and we know some arithmetic operators that can help us out. We saw in Lesson 1 that we can reassign variables. For example, we could say spam = 7, then later change our minds and say spam = 3. Instructions 1. On line 7, reassign meal to the value of itself + itself * tax. And yes, you're allowed to reassign a variable in terms of itself! We're only calculating the cost of meal and tax here. We'll get to the tip soon.

parrot = "norwegian blue".upper() print parrot ... NORWEGIAN BLUE

STRINGS & CONSOLE OUTPUT upper() Now your string is 100% lower case! A similar method exists to make a string completely upper case. Instructions 1. Call upper() on parrot (after print on line 3) in order to capitalize all the characters in the string!

# TEST COMMENT mysterious_variable = 42

Single Line Comments You probably saw us use the # sign a few times in earlier exercises. The # sign is for comments. A comment is a line of text that Python won't try to run as code. It's just for humans to read. Comments make your program easier to understand. When you look back at your code or others want to collaborate with you, they can read your comments and easily figure out what your code does. Instructions 1. Write a comment on line 1. Make sure it starts with #. It can say anything you like.

# Print the concatenation of "Spam and eggs" on line 3! print "Spam " + "and " + "eggs" ... Spam and eggs

String Concatenation You know about strings, and you know about arithmetic operators. Now let's combine the two! print "Life " + "of " + "Brian" This will print out the phrase Life of Brian. The + operator between strings will 'add' them together, one after the other. Notice that there are spaces inside the quotation marks after Life and of so that we can make the combined string look like 3 words. Combining strings together like this is called concatenation. Let's try concatenating a few strings together now! Instructions 1. Let's give it a try. Print the concatenated strings "Spam ", "and ", "eggs" on line 3, just like the example above. Make sure you include the spaces at the end of "Spam " and "and ".

string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) ... Let's not go to Camelot. 'Tis a silly place.

String Formatting with %, Part 1 When you want to print a variable with a string, there is a better method than concatenating strings together. name = "Mike" print "Hello %s" % (name) The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it. Instructions 1. Take a look at the code in the editor. What do you think it'll do? Click Run when you think you know.

name = raw_input("What is your name? ") quest = raw_input("What is your quest? ") color = raw_input("What is your favorite color? ") print "Ah, so your name is %s, your quest is %s, " \ "and your favorite color is %s." % (name, quest, color) ... What is your name? Anthony What is your quest? To seek the Holy Grail What is your favorite color? Blue Ah, so your name is Anthony, your quest is To seek the Holy Grail, and your favorite color is Blue.

String Formatting with %, Part 2 Remember, we used the % operator to replace the %s placeholders with the variables in parentheses. name = "Mike" print "Hello %s" % (name) You need the same number of %s terms in a string as the number of variables in parentheses: print "The %s who %s %s!" % ("Knights", "say", "Ni") # This will print "The Knights who say Ni!" Instructions 1. Now it's your turn! We have ___ in the code to show you what you need to change! Inside the string, replace the three ___ with %s. After the string but before the three variables, replace the final ___ with a %. Hit Run. Answer the questions in the console as they pop up! Type in your answer and hit Enter.

parrot = "Norwegian Blue" print len(parrot) ... 14

String methods Great work! Now that we know how to store strings, let's see how we can change them using string methods. String methods let you perform specific tasks for strings. We'll focus on four string methods: len() lower() upper() str() Let's start with len(), which gets the length (the number of characters) of a string! Instructions 1. On line 1, create a variable named parrot and set it to the string "Norwegian Blue". On line 2, type len(parrot) after the word print, like so: print len(parrot). The output will be the number of letters in "Norwegian Blue"!

# Set the variable brian on line 3! brian = "Hello life!"

Strings Another useful data type is the string. A string can contain letters, numbers, and symbols. name = "Ryan" age = "19" food = "cheese" In the above example, we create a variable name and set it to the string value "Ryan". We also set age to "19" and food to "cheese". Strings need to be within quotes. Instructions 1. Create a new variable brian and assign it the string "Hello life!".

# Assign the variable meal the value 44.50 on line 3! meal = 44.50

The Meal Now let's apply the concepts from the previous section to a real world example. You've finished eating at a restaurant, and received this bill: Cost of meal: $44.50 Restaurant tax: 6.75% Tip: 15% You'll apply the tip to the overall cost of the meal (including tax). Instructions 1. First, let's declare the variable meal and assign it the value 44.50.

meal = 44.50 tax = 6.75/100

The Tax Good! Now let's create a variable for the tax percentage. The tax on your receipt is 6.75%. You'll have to divide 6.75 by 100 in order to get the decimal form of the percentage. (See the Hint if you would like further explanation.) Instructions 1. Create the variable tax and set it equal to the decimal value of 6.75%.

# You're almost there! Assign the tip variable on line 5. meal = 44.50 tax = 6.75 / 100 tip = 15.0 / 100

The Tip Nice work! You received good service, so you'd like to leave a 15% tip on top of the cost of the meal, including tax. Before we compute the tip for your bill, let's set a variable for the tip. Again, we need to get the decimal form of the tip, so we divide 15.0 by 100. Note we have to use 15.0 instead of 15 to ensure our program keeps the decimal points when dividing. Instructions 1. Set the variable tip to decimal value of 15% on line 5.

""" The string "PYTHON" has six characters, numbered 0 to 5, as shown below: +---+---+---+---+---+---+ | P | Y | T | H | O | N | +---+---+---+---+---+---+ 0 1 2 3 4 5 So if you wanted "Y", you could just type "PYTHON"[1] (always start counting from 0!) """ fifth_letter = "MONTY"[4] print fifth_letter ... Y

Access by Index Great work! Each character in a string is assigned a number. This number is called the index. Check out the diagram in the editor. c = "cats"[0] n = "Ryan"[3] In the above example, we create a new variable called c and set it to "c", the character at index zero of the string "cats". Next, we create a new variable called n and set it to "n", the character at index three of the string "Ryan". In Python, we start counting the index from zero instead of one. Instructions 1. On line 13, assign the variable fifth_letter equal to the fifth letter of the string "MONTY". Remember that the fifth letter is not at index 5. Start counting your indices from zero.

# Write your code below, starting on line 3! my_string = "Hi, my name is Anthony." print len(my_string) print my_string.upper() ... 23 HI, MY NAME IS ANTHONY.

And Now, For Something Completely Familiar Great job! You've learned a lot in this unit, including: Three ways to create strings 'Alpha' "Bravo" str(3) String methods len("Charlie") "Delta".upper() "Echo".lower() Printing a string print "Foxtrot" Advanced printing techniques g = "Golf" h = "Hotel" print "%s, %s" % (g, h) Instructions 1. Let's wrap it all up! On line 3, create the variable my_string and set it to any string you'd like. On line 4, print the length of my_string. On line 5, print the .upper() case version of my_string.

# Set the variables to the values listed in the instructions! my_int = 7 my_float = 1.23 my_bool = True

Booleans Great! You just stored a number in a variable. Numbers are one data type we use in programming. A second data type is called a boolean. A boolean is like a light switch. It can only have two values. Just like a light switch can only be on or off, a boolean can only be True or False. You can use variables to store booleans like this: a = True b = False Set the following variables to the corresponding values: my_int to the value 7 my_float to the value 1.23 my_bool to the value True

# Hi everyone! monty = True python = 1.234 monty_python = python ** 2

Bringing It All Together Nice work! So far, you've learned about: Variables, which store values for later use Data types, such as numbers and booleans Whitespace, which separates statements Comments, which make your code easier to read Arithmetic operations, including +, -, *, /, **, and % Instructions 1. Let's put our knowledge to work. Write a single-line comment on line 1. It can be anything! (Make sure it starts with #) Set the variable monty equal to True. Set another variable python equal to 1.234. Set a third variable monty_python equal to python squared.

ministry = "The Ministry of Silly Walks" print len(ministry) print ministry.upper() ... 27 THE MINISTRY OF SILLY WALKS

Dot Notation Let's take a closer look at why you use len(string) and str(object), but dot notation (such as "String".upper()) for the rest. lion = "roar" len(lion) lion.upper() Methods that use dot notation only work with strings. On the other hand, len() and str() can work on other data types. Instructions 1. On line 3, call the len() function with the argument ministry. On line 4, invoke the ministry's .upper() function.

# The string below is broken. Fix it using the escape backslash! 'This isn\'t flying, this is falling with style!'

Escaping characters There are some characters that cause problems. For example: 'There's a snake in my boot!' This code breaks because Python thinks the apostrophe in 'There's' ends the string. We can use the backslash to fix the problem, like this: 'There\'s a snake in my boot!' Instructions 1. Fix the string in the editor!

# Turn 3.14 into a string on line 3! print "The value of pi is around " + str(3.14) ... The value of pi is around 3.14

Explicit String Conversion Sometimes you need to combine a string with something that isn't a string. In order to do that, you have to convert the non-string into a string. print "I have " + str(2) + " coconuts!" This will print I have 2 coconuts!. The str() method converts non-strings into strings. In the above example, you convert the number 2 into a string and then you concatenate the strings together just like in the previous exercise. Now try it yourself! Instructions 1. Run the code as-is. You get an error! Use str() to turn 3.14 into a string. Then run the code again.

#Set eggs equal to 100 using exponentiation on line 3! eggs = 10 ** 2 print eggs ... 100

Exponentiation All that math can be done on a calculator, so why use Python? Because you can combine math with other data types (e.g. booleans) and commands to create useful programs. Calculators just stick to numbers. Now let's work with exponents. eight = 2 ** 3 In the above example, we create a new variable called eight and set it to 8, or the result of 2 to the power to 3 (2^3). Notice that we use ** instead of * or the multiplication operator. Instructions 1. Create a new variable called eggs and use exponents to set eggs equal 100. Try raising 10 to the power of 2.

# Assign the variable total on line 8! meal = 44.50 tax = 6.75 / 100 tip = 15.0 / 100 meal = meal + meal * tax total = meal + meal * tip print("%.2f" % total) ... 54.63

The Total Now that meal has the cost of the food plus tax, let's introduce on line 8 a new variable, total, equal to the new meal + meal * tip. The code on line 10 formats and prints to the console the value of total with exactly two numbers after the decimal. (We'll learn about string formatting, the console, and print in Unit 2!) Instructions 1. Assign the variable total to the sum of meal + meal * tip on line 8. Now you have the total cost of your meal!

from datetime import datetime now = datetime.now() print now.year print now.month print now.day ... 2017 8 7

Extracting Information Notice how the output looks like 2013-11-25 23:45:14.317454. What if you don't want the entire date and time? from datetime import datetime now = datetime.now() current_year = now.year current_month = now.month current_day = now.day You already have the first two lines. In the third line, we take the year (and only the year) from the variable now and store it in current_year. In the fourth and fifth lines, we store the month and day from now. Instructions 1. On a new line, print now.year. Make sure you do it after setting the now variable! Then, print out now.month. Finally, print out now.day.

from datetime import datetime

The datetime Library A lot of times you want to keep track of when something happened. We can do so in Python using datetime. Here we'll use datetime to print the date and time in a nice format. Instructions 1. Click Run to continue.

from datetime import datetime now = datetime.now() print now ... 2017-08-07 19:28:39.770311

Getting the Current Date and Time We can use a function called datetime.now() to retrieve the current date and time. from datetime import datetime print datetime.now() The first line imports the datetime library so that we can use it. The second line will print out the current date and time. Instructions 1. Create a variable called now and store the result of datetime.now() in it. Then, print the value of now.

# Write your code below! my_variable = 10 # Write your code above! print my_variable ... 10

Variables Creating web apps, games, and search engines all involve storing and working with different types of data. They do so using variables. A variable stores a piece of data, and gives it a specific name. For example: spam = 5 The variable spam now stores the number 5. Set the variable my_variable equal to the value 10. Click the Run button to run your code

def spam(): eggs = 12 return eggs print spam() ... File "python", line 2 eggs = 12 ^ IndentationError: expected an indented block

Whitespace In Python, whitespace is used to structure code. Whitespace is important, so you have to be careful with how you use it. Instructions 1. The code on the right is badly formatted. Hit Run to see what happens. You should see an error message. We'll fix it in the next exercise!

def spam(): eggs = 12 return eggs print spam() ... 12

Whitespace Means Right Space Now let's examine the error from the last lesson: IndentationError: expected an indented block You'll get this error whenever your whitespace is off. On Codecademy, we will use two-space indentation (two blank spaces for each indentation) to make sure you can easily read code with multiple indentations in your browser. Beyond Codecademy, you will also see Python code that uses four-space indentation. Both are correct, as long as you make sure to be consistent throughout your code. Instructions 1. Properly indent the code with two spaces before eggs on line 2 and another two before return on line 3.You should indent your code with two spaces.

# my_int is set to 7 below. What do you think # will happen if we reset it to 3 and print the result? my_int = 7 # Change the value of my_int to 3 on line 8! my_int = 3 # Here's some code that will print my_int to the console: # The print keyword will be covered in detail soon! print my_int ... 3

You've Been Reassigned Now you know how to use variables to store values. Say my_int = 7. You can change the value of a variable by "reassigning" it, like this: my_int = 3 Instructions 1. Try it and see! Change the value of my_int from 7 to 3 in the editor

parrot = "Norwegian Blue".lower() print parrot ... norwegian blue

lower() Well done! You can use the lower() method to get rid of all the capitalization in your strings. You call lower() like so: "Ryan".lower() which will return "ryan". Instructions 1. Call lower() on parrot (after print) on line 3 in the editor.

"""Declare and assign your variable on line 4, then call your method on line 5!""" pi = 3.14 print str(pi) ... 3.14

str() Now let's look at str(), which is a little less straightforward. The str() method turns non-strings into strings! For example: str(2) would turn 2 into "2". Instructions 1. Create a variable pi and set it to 3.14 on line 4. Call str(pi) on line 5, after print.


Ensembles d'études connexes

Chapter 27: Disorders of Cardiac Function, and Heart Failure and Circulatory Shock

View Set

Basics of marketing/ uncontrollable factors

View Set

Exam 3 Study Guide (Chapters 9-12)

View Set

Somatic vs. Autonomic Nervous System

View Set

Anatomy - Extensor digiti minimi muscle

View Set

Chapter 19: Documenting and Reporting (2)

View Set