Python 2 Intro

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

Print Statement

A print statement is the easiest way to get your Python program to communicate with you. Being able to command this communication will be one of the most valuable tools in your programming toolbox.

Handling errors

As we get more familiar with the Python programming language, we run into errors and exceptions. These are complaints that Python makes when it doesn't understand what you want it to do. Everyone runs into these issues, so it is a good habit to read and understand them. 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.

Comments

Most of the time, code should be written in such a way that it is easy to understand on its own. However, 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. # this variable counts how many rows of the spreadsheet we have: row_count = 13

Arithmetic

One thing computers are capable of doing exceptionally well is performing arithmetic. Addition, subtraction, multiplication, division, and other numeric calculations are easy to do in most programming languages, and Python is no exception. Some examples: mirthful_addition = 12381 + 91817 amazing_subtraction = 981 - 312 trippy_multiplication = 38 * 902 happy_division = 540 / 45 sassy_combinations = 129 * 1345 + 120 / 6 - 12 Above are a number of arithmetic operations, each assigned to a variable. The variable will hold the final result of each operation. Combinations of arithmetical operators follow the usual order of operations.

ValueError

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!" Similarly, if we have a string like "7" and we want to perform arithmetic operations on it, we must convert it to a numeric datatype. We can do this using int(): number1 = "100" number2 = "10" string_addition = number1 + number2 #string_addition now has a value of "10010" int_addition = int(number1) + int(number2) #int_addition has a value of 110 If you use int() on a floating point number, it will round the number down. To preserve the decimal, you can use float(): string_num = "7.5" print int(string_num) print float(string_num) >>> 7 >>> 7.5

What happens when you do not use quotes?

Python treats words not in quotes as commands, like the print statement. If it fails to recognize these words as defined (in Python or by your program elsewhere) Python will complain the code has a NameError. This means that Python found what it thinks is a command, but doesn't know what it means because it's not defined anywhere.

Booleans

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.

Modulo operator

The modulo operator is indicated by % and returns the remainder after division is performed. is_this_number_odd = 15 % 2 is_this_number_divisible_by_seven = 133 % 7 In the above code block, we use the modulo operator to find the remainder of 15 divided by 2. Since 15 is an odd number the remainder is 1. We also check the remainder of 133 / 7. Since 133 divided by 7 has no remainder, 133 % 7 evaluates to 0.

Numbers

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 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 You can also define a float using scientific notation, with e indicating the power of 10: # this evaluates to 150: float4 = 1.5e2

Multi-line Strings

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. 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..." """ EX2: haiku = """The old pond, A frog jumps in: Plop!""" print haiku

Updating variables

Changing the contents of a variable is one of the essential operations. As the flow of a program progresses, data should be updated to reflect changes that have happened. 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.

Variables

In Python, and when programming in general, we need to build systems for dealing with data that changes over time. That data could be the location of a plane, or the time of day, or the television show you're currently watching. The only important thing is that it may be different at different times. Python uses variables to define things that are subject to change. greeting_message = "Welcome to Codecademy!" current_excercise = 5 In the above example, we defined a variable called greeting_message and set it equal to the string "Welcome to Codecademy!". It also defined a variable called current_exercise and set it equal to the number 5.

String

When printing things in Python, we are supplying a text block that we want to be printed. 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' We can combine multiple strings using +, like so: print "This is " + "a good string"


Set pelajaran terkait

weather and climate final study guide

View Set

Farm and Ranch Management Final Exam

View Set

Chapter 4: Managing Ethics and Social Responsibility

View Set

LEADERSHIP AND MENTAL HEALTH MIDTERM BONUS

View Set