ラベル python の投稿を表示しています。 すべての投稿を表示
ラベル python の投稿を表示しています。 すべての投稿を表示

2019年4月1日月曜日

python basic

x = 3
y = 4
z = 5

x, y, z = 3, 4, 5

my_height = 58

x = int(4.7)   # x is now an integer 4
y = float(4)   # y is now a float of 4.0
>>> print(type(x))
int
>>> print(type(y))
float

String

>>> first_word = 'Hello'
>>> second_word = 'There'
>>> print(first_word + second_word)

HelloThere

>>> print(first_word + ' ' + second_word)

Hello There

>>> print(first_word * 5)

HelloHelloHelloHelloHello

>>> print(len(first_word))

5

>>> first_word[0]

H

>>> first_word[1]

e

print("Mohammed has {} balloons".format(27))
# Mohammed has 27 balloons

new_str = "The cow jumped over the moon."
new_str.split()
# ['The', 'cow', 'jumped', 'over', 'the', 'moon.']

new_str.split(' ', 3)
# maxsplit is set to 3, ['The', 'cow', 'jumped', 'over the moon.']

List

list_of_random_things = [1, 3.4, 'a string', True]
>>> list_of_random_things[-1]
True
>>> list_of_random_things[-2]
a string

When using slicing, it is important to remember that the lower index is inclusive and the upper index is exclusive.

>>> 'isa' in 'this is a string'
False
>>> 5 not in [1, 2, 3, 4, 6]
True

name = "-".join(["García", "O'Kelly"])
print(name)
# García-O'Kelly

letters = ['a', 'b', 'c', 'd']
letters.append('z')
print(letters)
# ['a', 'b', 'c', 'd', 'z']

tuple

location = (13.4125, 103.866667)
print("Latitude:", location[0])
print("Longitude:", location[1])

dimensions = 52, 40, 100
length, width, height = dimensions
print("The dimensions are {} x {} x {}".format(length, width, height))

set

A set is a data type for mutable unordered collections of unique elements.
numbers = [1, 2, 6, 3, 1, 1, 6]
unique_nums = set(numbers)
print(unique_nums)
# {1, 2, 3, 6}

fruit = {"apple", "banana", "orange", "grapefruit"}  # define a set
print("watermelon" in fruit)  # check for element
fruit.add("watermelon")  # add an element
print(fruit.pop())  # remove a random element

dictionary

elements = {"hydrogen": 1, "helium": 2, "carbon": 6}
print(elements["helium"])  # print the value mapped to "helium"
elements["lithium"] = 3  # insert "lithium" with a value of 3 into the dictionary

We can check whether a value is in a dictionary the same way we check whether a value is in a list or set with the in keyword. Dicts have a related method that's also useful, get. get looks up values in a dictionary, but unlike square brackets, get returns None (or a default value of your choice) if the key isn't found.

print("carbon" in elements)
print(elements.get("dilithium"))

Zip

a = [1, 2, 3, 4, 5]
b = [10, 11, 12, 13, 14]
list(zip(a, b)) #[(1, 10), (2, 11), (3, 12), (4, 13), (5, 14)]



2017年11月30日木曜日

Django appを作成

1)Projectを作成、cloud9環境ではすでに作成されたので、不要
django-admin startproject mysite

2)appを作成
python manage.py startapp polls

Projects vs. apps
What’s the difference between a project and an app? An app is a Web application that does something – e.g., a Weblog system, a database of public records or a simple poll app. A project is a collection of configuration and apps for a particular website. A project can contain multiple apps. An app can be in multiple projects.

3)Viewを作成
polls/views.py を編集

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world. You're at the polls index.")

4)To call the view, we need to map it to a URL
 polls/urls.py を作成

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

5)To point the root URLconf at the polls.urls module

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^polls/', include('polls.urls')),
    url(r'^admin/', admin.site.urls),
]

6)DBの設定
MySQLのアクセスモジュールを追加
sudo pip3 install PyMySQL

Projectフォルダーにsettings.pyのDATABASESを変更
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'c9',  #dbname
        'USER': 'XXXXc9',       #username
        'PASSWORD': 'password',
        'HOST': '',
        'PORT': '',
    }
}

manage.pyに以下を追加
import pymysql
pymysql.install_as_MySQLdb()

7)migrate実施
python manage.py migrate
settings.pyのINSTALLED_APPSに必要なTableが作成されれば、DB設定OK


2017年10月26日木曜日

cloud9でpython3/djangoを設定

django projectの設定(歯車)から、python2->3にしてから以下を実施

sudo rm /usr/bin/python
sudo ln -s /usr/bin/python3.4 /usr/bin/python  ->ここ3.5を設定したら、djangoが認識してくれなかったとりあえず3.4にした
sudo pip3 install django

以下のコマンドでバージョン確認
python -V
python -m django --version