PYTHON SYNTAX

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

A number with a decimal point is called a float. You can define floats with numbers after the decimal point or by just including a decimal point at the end:

float1 = 1.0 float2 = 10. float3 = -5.5

fish_in_clarks_pond = 50 print "Catching fish" number_of_fish_caught = 10 fish_in_clarks_pond = fish_in_clarks_pond - number_of_fish_caught

In the above example, we start with 50 fish in a local pond. After catching 10 fish, we update the number of fish in the pond to be the original number of fish in the pond minus the number of fish caught. At the end of this code block, the variable fish_in_clarks_pond is equal to 40.

Here are some common errors that we might run into when printing strings: print "Mismatched quotes will cause a SyntaxError' print Without quotes will cause a NameError If the quotes are mismatched Python will notice this and inform you that your code has an error in its syntax because the line ended (called an EOL) before the double-quote that was supposed to close the string appeared. The program will abruptly stop running with the following message: SyntaxError: EOL while scanning a string literal

This means that a string wasn't closed, or wasn't closed with the same quote-character that started it.

Python automatically assigns a variable the appropriate datatype based on the value it is given. A variable with the value 7 is an integer, 7. is a float, "7" is a string. Sometimes we will want to convert variables to different datatypes. For example, if we wanted to print out an integer as part of a string, we would want to convert that integer to a string first. We can do that using str(): age = 13 print "I am " + str(age) + " years old!"

This would print: >>> "I am 13 years old!"

You have come home from the grocery store with 100 cucumbers to split amongst yourself and your 5 roommates (6 people total). Create a variable cucumbers that holds 100 and num_people that holds 6. 2. Create a variable called whole_cucumbers_per_person that is the integer result of dividing cucumbers by num_people. Print whole_cucumbers_per_person to the console. 3. You realize that the numbers don't divide evenly and you don't want to throw out the remaining cucumbers. Create a variable called float_cucumbers_per_person that holds the float result of dividing cucumbers by num_people. Print float_cucumbers_per_person to the console.

cucumbers = 100 #number of cucumbers num_people = 6 #number of people whole_cucumbers_per_person = cucumbers/num_people #cucumbers per person print whole_cucumbers_per_person #print number of cucumbers per person #16 float_cucumbers_per_person = float(cucumbers)/num_people # the number of cucumbers per person doesn't divide evenly, created a float print float_cucumbers_per_person #print the float of cucumbers per person #16.6666666667

Create a variable called haiku and store this haiku as a multi-line string: The old pond, A frog jumps in: Plop!

haiku = """The old pond, A frog jumps in: Plop!"""

Updating a variable by adding or subtracting a number to the original contents of the variable has its own shorthand to make it faster and easier to read.

money_in_wallet = 40 sandwich_price = 7.50 sales_tax = .08 * sandwich_price sandwich_price += sales_tax money_in_wallet -= sandwich_price In the above example, we use the price of a sandwich to calculate sales tax. After calculating the tax we add it to the total price of the sandwich. Finally, we complete the transaction by reducing our money_in_wallet by the cost of the sandwich (with tax).

Try adding your name to the print statement with the + operator so that this Python program prints "Hello [your_name]"

print "Hello " + "Jennifer"

Text in Python is considered a specific type of data called a string. A string, so named because they're a series of letters, numbers, or symbols connected in order — as if threaded together by string. Strings can be defined in different ways:

print "This is a good string" print 'You can use single quotes or double quotes for a string' While double-quotes (") and single-quotes (') are both acceptable ways to define a string, a string needs to be opened and closed by the same type of quote mark.

In Python 2, when we divide two integers, we get an integer as a result. When the quotient is a whole number, this works fine:

quotient = 6/2 # the value of quotient is now 3, which makes sense

However, if the numbers do not divide evenly, the result of the division is truncated into an integer. In other words, the quotient is rounded down to a whole number. This can be surprising when you expect to receive a decimal and you receive a rounded-down integer:

quotient = 7/2 # the value of quotient is 3, even though the result of the division here is 3.5

To yield a float as the result instead, programmers often change either the numerator or the denominator (or both) to be a float:

quotient1 = 7./2 # the value of quotient1 is 3.5 quotient2 = 7/2. # the value of quotient2 is 3.5 quotient3 = 7./2. # the value of quotient3 is 3.5

An alternative way is to use the float() method:

quotient1 = float(7)/2 # the value of quotient1 is 3.5

. What is the remainder when 1398 is divided by 11? Save the results in a variable called remainder. Hint Remember that remainders can be found using the modulus operator. Calculate a remainder with %.

remainder = 1398 % 11

When a string like this is not assigned to a variable, it works as a multi-line comment. This can be helpful as your code gets more complex:

"""The following piece of code does the following steps: takes in some input does An Important Calculation returns the modified input and a string that says "Success!" or "Failure..." """ ... a complicated piece of code here...

Someone has introduced themselves to you using comments in script.py. Read the comments and then create a variable called age_is_12 and set it to be True or False depending on if this person's age is 12. Stuck? Get a hint 2. Create a variable called name_is_maria and set it to be True or False depending on if this person's name is Maria.

# Hi! I'm Maria and I live in script.py. # I'm an expert Python coder. # I'm 21 years old and I plan to program cool stuff forever. age_is_12 = False name_is_maria = True

You can also define a float using scientific notation, with e indicating the power of 10:

# this evaluates to 150: float4 = 1.5e2

1. You are going shopping. Let's make a grocery list so that you can plan your budget. Store the number of cucumbers you want to buy in a variable called cucumbers. Make sure it's at least 1, and that it's the appropriate datatype! The store doesn't sell partial cucumbers. 2. Each cucumber costs 3.25 doubloons. Store the price per cucumber in a variable called price_per_cucumber. 3. Create a new variable called total_cost which is the product of how many cucumbers you are going to buy and the cost per cucumber. 4. Print out total_cost. What datatype is it?

#grocery list cucumbers = 5 #price per cucumber price_per_cucumber = 3.25 #total cost of cucumbers total_cost = cucumbers * price_per_cucumber #print out cost of total cucumbers print total_cost #this code printed 16.25 #this is a float

Sometimes we have a need for variables that are either true or false. This datatype, which can only ever take one of two values, is called a boolean. In Python, we define booleans using the keywords True and False: a = True b = False

A boolean is actually a special case of an integer. A value of True corresponds to an integer value of 1, and will behave the same. A value of False corresponds to an integer value of 0.

If you want to include a piece of information to explain a part of your code, you can use the # sign.

A line of text preceded by a # is called a comment. The machine does not run this code — it is only for humans to read. When you look back at your code later, comments may help you figure out what it was intended to do.

Variables can also hold numeric values. The simplest kind of number in Python is the integer, which is a whole number with no decimal point:

int1 = 1 int2 = 10 int3 = -5

We're trying to figure out how much it rained in the past year! Update the annual_rainfall variable to include the values from September to December.

january_to_june_rainfall = 1.93 + 0.71 + 3.53 + 3.41 + 3.69 + 4.50 (I added the below) september_to_december_rainfall = 5.16 + 7.20 +5.06 + 4.06 annual_rainfall = january_to_june_rainfall + september_to_december_rainfall july_rainfall = 1.05 annual_rainfall += july_rainfall august_rainfall = 4.91 annual_rainfall += august_rainfall september_rainfall = 5.16 october_rainfall = 7.20 november_rainfall = 5.06 december_rainfall = 4.06

1. Multiply two numbers together and assign the result to a variable called product.

product = 2 * 2

1. Let's apply all of the concepts you have learned one more time! Create a variable called skill_completed and set it equal to the string "Python Syntax". 2. Create a variable called exercises_completed and set it equal to 13. Create another variable called points_per_exercise and set it equal to 5. 3. Create a variable called point_total and set it equal to 100. 4. Update point_total to be what it was before plus the result of multiplying exercises_completed and points_per_exercise. Stuck? Get a hint 5. Add a comment above your declaration of points_per_exercise that says: The amount of points for each exercise may change, because points don't exist yet 6. Print a string to the console that says: I got X points! with the value of point_total where X is.

skill_completed = "Python Syntax" exercises_completed = 13 #The amount of points for each exercise may change, because points don't exist yet points_per_exercise = 5 point_total = 100 point_total += exercises_completed*points_per_exercise print("I got "+str(point_total)+" points!")

We have seen how to define a string with single quotes and with double quotes. If we want a string to span multiple lines, we can also use triple quotes: address_string = """136 Whowho Rd Apt 7 Whosville, WZ 44494"""

This address spans multiple lines, and is still contained in one variable, address_string.

1. Add a comment above the declaration of city_pop with a description of what you think the variable contains.

city_name = "St. Potatosburg" # this variable shows the city's population city_pop = 340000

Create a variable called product that contains the result of multiplying the float value of float_1 and float_2. 2. Create a string called big_string that says: The product was X with the value of product where the X is. Hint You can combine strings by casting the numerical value to a string and using the + operator: "I have " + str(18) + " dogs at home!"

float_1 = 0.25 float_2 = 40.0 product = float_1 * float_2 big_string = "The product was " + str(product)


Set pelajaran terkait

Criminal Justice Chapter 3 and 4.

View Set

5. Making a Radiographic Image: Projection Geometry & Characteristics of Diagnostic Radiograph Localization

View Set

Prep U Psychiatric-Mental Health Nursing Chapter 11: Anger, Hostility, and Aggression

View Set