Python - How to the base

From Linux - Help
Jump to: navigation, search
Python.jpeg

PAGE WORK IN PROGRESS

Goal: The objective is to have a memo to Python, this first page will cover the basics of this language.

Python Syntax

Installing Python

On Gentoo / Funtoo you need to emerge Python:

 sudo emerge -a python

If an old version of python is installed you need to eselect the version you want to use:

 eselect python list

Then:

 eselect python set number

After the installation and that you selected the version you want to use, you can type in a terminal:

 python
Python home oswin 016.png

Good work Python is installed ^^

Print Statements

Python has two version, Pyhton 2 and Python 3. As you will learn with a programming language to speak to your computer, a first good idea is to learn the computer to speak to you. In Python this can be achieved with:

Python2:

 print "Hello World"

Python3:

 print ("Hello World")

Strings

When printing things in Python, we are supplying a text block that we want to be printed. Text in Pyhton 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 the readed together by string. Strings can be defined in different ways:

 print ("This is a good string")
 print ('You can use signle quotes or double quotes for a string')
 print ("This is " + " a good string too")

Handling Errors

When developping with a language we run in to errors and exceptions. These are complaints that the program makes when it doesn't understand what you want it to do. So it is a good habit to read and understand them.

Here some common errors we might run in to when printing strings:

 print ("Mismatched quotes will cause 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 without quotes at all. Pyhton treats words not in quotes as command, like the print statement. If it fails to recoginze these words as defined (in Python or by your program elsewhere) Python will complain the code has a NameError. This mean that Python found what it thinks is a command, but doesn't know what it means because it's not defined anywhere.

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 at different times. Python uses variables to define things that are subject to change.

 greeting_message = "Welcome to my wiki!" 
 current_exercises = 5

In the above example, we defined a variable callet greeting_message and set it equal to the string "Welcomne to my wiki!". It also defined a variable called current_exercises and set it equal to the number 5.

Arithmetic

One thing computers are capable of doing exceptionallu 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:

 additon = 12381 + 91817
 subtraction = 981 - 312
 multiplication = 38 * 902
 division = 540 / 45
 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 is divided by 7 has no remainder, 133 % 7 evaluates to 0.

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 "Cathing fish"
 number_of_fish_caught = 10
 fish_in_clarks_pond = fish_in_clarks_pond - number_of_fish_caught

In the avove 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 eand 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 calculatye 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).

Comments

Most of the time, code should be written in such 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 to figure out what it was intended to do.

 # this variable counts how many rows of the spreadsheet we have: 
 row_coutn = 13

Numbers

Variable 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 
 int 2 = 10
 int 3 = -5

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

 float1 = 1.0
 float2 = 10.
 float3 = -5.5

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

 float4 = 1.5e2

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 work fine:

 quotient = 6/2
 # the calue of quotient is now 3.

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 suprising when you expect to receive a decimal and you receive a rounded-down integer:

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

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

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

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:

 multi_string = """ 136
 this is an example
 of multi-strings """

This string spans multiple lines, and is still contained in one variable, multi_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...

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

ValueError

Python automatically assigns a variable the apporpriate datatype based on the value it is given. A variable with the value 7 is an integer. 7. is a floatm "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' suing str():

 age = 13
 print "I am " + str(age) + "years old!"

This would print:

 "I am 13 years old!"

Strings and Console Output

Strings & Console Output

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.

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!'

Access by Index

Each character in a string is assigned a number. This number is called the index. Check out the diagram:

 c = "cats"[0]
 n = "Ryan"[3]

In the above example. we create a new variable 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"

Notice that in the first "cat" example we are calling the 0th letter of "cat" and getting "c" in return. This is because in Python indices begin counting at 0. Therefore, in the string "cat", the first letter, c, is at the 0th index and the last letter. s, is at the 3rd index.

 """
 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!)
 """

String methods