LIKE A DIAMOND

[Python] 001.Hello World! #codeAcademy 본문

notUsed_STUDY

[Python] 001.Hello World! #codeAcademy

OPENLUNCH 2018. 8. 6. 16:16
728x90
반응형

#codeAcademyPython

1
PYTHON SYNTAX

Hello World!

If programming is the act of teaching a computer to have a conversation with a user, it would be most useful to first teach the computer how to speak. In Python, this is accomplished with the print statement.

print "Hello, world!" print "Water—there is not a drop of water there! Were Niagara but a cataract of sand, would you travel your thousand miles to see it?"

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.

 

---

2

Print Statements

There are two different Python versions. Both Python 2 and Python 3 are used throughout the globe. The most significant difference between the two is how you write a print statement. In Python 3, print has parentheses.

print("Hello World!") print("Deep into distant woodlands winds a mazy way, reaching to overlapping spurs of mountains bathed in their hill-side blue.")

In this course we will be using Python 2. If you go on to write Python 3 it will be useful to note this key difference.

 

---

3

PYTHON SYNTAX

Strings

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'

Above we printed two things that are strings and then attempted to print two things that are not strings. 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.

We can combine multiple strings using +, like so:

print "This is " + "a good string"

This code will print out "This is a good string".

 

---

4

PYTHON SYNTAX

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.

Another issue you might run into is attempting to create a string 

 

---

5

PYTHON SYNTAX

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_messageand 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.

 

---

6

PYTHON SYNTAX

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.

Python also offers a companion to division called the 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.

---

7

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.

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).

 

---

8

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

 

---

9

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

---

10

Two Types of Division

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

---

11

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..." """ ... a complicated piece of code here...

---

12

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 Truecorresponds to an integer value of 1, and will behave the same. A value of False corresponds to an integer value of 0.

 

---

13

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

---

14

PYTHON SYNTAX

Review

Great! So far we’ve looked at:

  • Print statements
  • How to create, modify, and use variables
  • Arithmetic operations like addition, subtraction, division, and multiplication
  • How to use comments to make your code easy to understand
  • Different data types, including strings, ints, floats, and booleans
  • Converting between data types
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.

 

 

 
5.

Add a comment above your declaration of points_per_exercisethat 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.

---

Finish Quiz Answer

 

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

 

728x90
반응형
Comments