First python (data type, control statement, function definition)

Recently, I have had many opportunities to analyze data, and I decided to study python a little because I heard that it is good for statistical calculation. It is a memo writing at that time. It's broken here and there.

[Reference] http://docs.python.jp/2/tutorial/index.html

Data type

Numerical value

You can use basic operators. Imaginary numbers can also be used naturally.

python


>>> 2
2
>>> 2 + 4 #operator+, -, *, /Such
6
>>> 5/2 #When integers are used, the calculation result is also an integer(Devaluation)
2
>>> 5/2.0 #If you use a floating point number, the calculation result will be a floating point number.
2.5

>>> 1j * 1J #Imaginary number is j or J
(-1+0j)
>>> a=1.5+0.5j #Variable declaration
>>> a.real #Get the real part
1.5
>>> a.imag #Acquisition of imaginary part
0.5

String

Indicates a character string in single or double quotes. Escape special characters with a backslash.

python


>>> 'spam eggs' #Single quote
'spam eggs'
>>> "doesn't" #Double quote
"doesn't"
>>> '"Yes," he said.' #Double quotes within single quotes are displayed
'"Yes," he said.'
>>> "\"Yes,\" he said." #Double quotes inside double quotes are escaped with a backslash
'"Yes," he said.'
>>> '"Isn't," she said.' #Single quotes inside single quotes are in error
  File "<stdin>", line 1
    '"Isn't," she said.'
          ^
SyntaxError: invalid syntax
>>> '"Isn\'t," she said.' #Even if you insert a backslash, it is displayed together with the backslash
'"Isn\'t," she said.'

Intuitive operation of character strings

python


>>> word = 'Help' + 'A' #Addition of strings
>>> word
'HelpA'
>>> string = 'str' 'ing' #+ Can be omitted
>>> string
'string'
>>> 'str'.strip() 'ing' #But don't omit it in this case
  File "<stdin>", line 1
    'str'.strip() 'ing'
                      ^
SyntaxError: invalid syntax

It is also possible to operate character strings with subscripts. If omitted, it will be complemented appropriately.

>>> word
'HelpA'
>>> word[4] # index 4,Get the 5th character
'A'
>>> word[0:2] # index 0,Get 1
'He'
>>> word[:2] #index first~Get up to 1
'He'
>>> word[2:] # index 2~Get to the end
'lpA'
>>> word[-1] #Minus notation is also possible.Index from the end
'A'

Cannot be assigned to a string

python


>>> word[0] = 'x' #Error when trying to assign
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

list

Lists are separated by commas and enclosed in parentheses. The types of list elements do not have to be the same. You can also nest lists.

python


>>> a = ['spam', 'eggs', 100, 1234] #List declaration
>>> a
['spam', 'eggs', 100, 1234]
>>> a[3] #Can also be specified by index
1234
>>> a[0:2] = [] #Delete element
>>> a
[100, 1234]
>>> a[1:1] = ['bletch', 'xyzzy'] #Add element
>>> a
[100, 'bletch', 'xyzzy', 1234]

Substitution

Can be assigned collectively.

python


>>> a, b = 0, 1 # a =0 and b=Run 1
>>> a
0
>>> b
1

Control statement

if

You can add as many elifs as you like. You can also add else. if ... elif ... elif ... is a substitute for switch statements and case statements.

python


>>> x = int(raw_input("Please enter an integer: ")) #Input from command line
Please enter an integer: 42
>>> if x < 0: #The beginning of the if statement
...     x = 0
...     print 'Negative changed to zero'
... elif x == 0: #Add condition with elif
...     print 'Zero'
... elif x == 1:
...     print 'Single'
... else: #If the condition is not met, set to else
...     print 'More'
...
More

for

The for statement iterates over lists and strings

python


>>> a = ['cat', 'window', 'defenestrate']
>>> for x in a: #Iterative processing for each element of a
...     print x, len(x) # len()Get the length with
...
cat 3
window 6
defenestrate 12

You can use the range () function when iterating over a sequence.

python


>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5,10) #Use by specifying the range
[5, 6, 7, 8, 9]
>>> range(1, 10, 2) #Use by specifying the range and how to increase
[1, 3, 5, 7, 9]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)): #Operate using range and len
...     print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb

What is used in the control statement

break

The break statement is used to end the operation in the middle. Exit the innermost for and while.

python


>>> #Check if it is a prime number
>>> for n in range(2, 10):
...     for x in range(2,n):
...             if n % x == 0:
...                     print n, 'equals', x, '*', n/x
...                     break
...     else:
...             print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

pass

The pass statement does nothing. Used when you have to write a sentence but there is no processing.

python


>>> #Smallest class
>>> class MyEmptyClass:
...     pass
...

Function definition

def indicates the function declaration. You can change the name by assigning a function to a variable.

python


>>> #Output Fibonacci sequence up to n
>>> def fib(n):
...     a, b = 0, 1
...     while a < n:
...             print a, #Hitting a comma does not break the output
...             a, b = b, a+b
...
>>> fib(100)
0 1 1 2 3 5 8 13 21 34 55 89
>>> f = fib #Give the function a different name
>>> f(200)
0 1 1 2 3 5 8 13 21 34 55 89 144

Return to return a value. Default arguments and keyword arguments can be used.

python


>>> def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
...     print "-- This parrot wouldn't", action,
...     print " if you put", voltage, "volts through it."
...     print "-- Lovely plumage, the", type
...     print "-- It's", state, "!"
...
>>> parrot(100) #Use default values except voltage
-- This parrot wouldn't voom  if you put 100 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !
>>> parrot(action = 'VOOOOM', voltage = 100000) #Pass by specifying a keyword
-- This parrot wouldn't VOOOOM  if you put 100000 volts through it.
-- Lovely plumage, the Norwegian Blue
-- It's a stiff !

It can also accept variadic arguments. Use \ * name to receive a tuple with positional arguments beyond the list of formal arguments, and ** name to receive a dictionary containing all keyword arguments except those corresponding to the previous formal arguments. ..

python


>>> def cheeseshop(kind, *arguments, **keywords):
...     print "-- Do you have any", kind, "?"
...     print "-- I'm sorry, we're all out of", kind
...     for arg in arguments:
...             print arg
...     print "-" * 40
...     keys = sorted(keywords.keys())
...     for kw in keys:
...             print kw, ":", keywords[kw]
...
>>> cheeseshop("Limburger",
...            "It's very runny, sir.",              # arguments
...            "It's really very, VERY runny, sir.", # arguments
...            shopkeeper="Michael Palin",           # keywords
...            client="John Cleese",                 # keywords
...            sketch="Cheese Shop Sketch")          # keywords
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch

Recommended Posts

First python (data type, control statement, function definition)
Function argument type definition in python
Python data type summary memo
Image data type conversion [Python]
python function ①
Use PostgreSQL data type (jsonb) from Python
[Introduction to Udemy Python3 + Application] 48. Function definition
[Python] function
python generated csv-like definition single element type
[Python] First data analysis / machine learning (Kaggle)
python function ②
I compared "python dictionary type" and "excel function"
Python if statement
First time python
First Python 3 ~ First comparison ~
Python numeric type
python enumerate function
Data analysis python
Python> function> Closure
[Python] Generator function
First time python
Python exec statement
First Python ~ Coding 2 ~
Install Python Control
First python [O'REILLY]
[Python] if statement
Python> function> Inner function
Python assert statement
Python2 string type
Python # string type
Python function decorator
[python] Read data
Image data type conversion [Python]