Install pymysql first

To connect to database

In Python, you need to create cursor first 

import pymysql

# To connect database
con = pymysql.connect(host = 'localhost',
                      user = 'root',
                      passwd = '1234',
                      port = 3306,
                      db = 'mysql',
                      charset = 'utf8')
# To create cursor
cursor = con.cursor()

# To execute SQL
cursor.execute('select * from user')

row = cursor.fetchone()         
print(type(row))                # 'tuple'
print(row)

rows = cursor.fetchall()        
print(type(rows))               # 'tuple'
print(rows)

for r in rows:
    print(r)

Create a table on MySQL workbench.

create table contact(
num int primary key auto_increment,
name varchar(100) not null,
phone varchar(20));

To insert data

import pymysql

try:
    con = pymysql.connect(host='localhost',
                          user='jspid',
                          passwd='jsppass',
                          port=3306,
                          db='jsptest',
                          charset='utf8')


    cursor = con.cursor()

    sql ="insert into contact(name, phone) values('Meadow','010-1111-2222')"

    cursor.execute(sql)
    con.commit()

    print('Successfully inserted')

except Exception as err:
    print(err)
finally:
    con.close()

If you search the inserted data on MySQL workbench, you will see them successfully inserted. 

To search data

import pymysql

try:
    con = pymysql.connect(host='localhost',
                          user='jspid',
                          passwd='jsppass',
                          port=3306,
                          db='jsptest',
                          charset='utf8')

    cursor = con.cursor()

    cursor.execute('select * from contact')

    row = cursor.fetchone()       
    print(type(row))                # 'tuple'
    print(row)                     

    for r in row:
        print(r)

except Exception as err:
    print(err)
finally:
    con.close()

To search all data

fetchall() prints tuples in python whereas, in sqlite and oracle, they print lists. 

import pymysql

try:
    con = pymysql.connect(host='localhost',
                          user='jspid',
                          passwd='jsppass',
                          port=3306,
                          db='jsptest',
                          charset='utf8')

    cursor = con.cursor()
    cursor.execute('select * from contact')
    rows = cursor.fetchall()    
    print(type(rows))               # 'tuple'
    print(rows)                     # cf. sqlite, oracle -> list (return)

    for r in rows:
        print(r)

except Exception as err:
    print(err)
finally:
    con.close()

To update

import pymysql

try:
    con = pymysql.connect(host='localhost',
                          user='jspid',
                          passwd='jsppass',
                          port=3306,
                          db='jsptest',
                          charset='utf8')
    cursor = con.cursor()
    sql = "update contact set phone='1234' where num=1"
    cursor.execute(sql)
    con.commit()
    
    print('Successfully updated')

except Exception as err:
    print(err)
finally:
    con.close()

To delete

import pymysql

try:
    con = pymysql.connect(host='localhost',
                          user='jspid',
                          passwd='jsppass',
                          port=3306,
                          db='jsptest',
                          charset='utf8')
    cursor = con.cursor()

    num = input('Insert the number to delete.')

    sql = 'delete from contact where num = %s'
    cursor.execute(sql, num)
    print('Delete')

# To search all data
    cursor.execute('select * from contact')
    rows = cursor.fetchall()         

    for r in rows:
        print(r)

#To count total data
    cursor.execute('select count(*) from contact')
    count = cursor.fetchone()          
    for c in count:
        print('Total data:', c)

    con.commit()

except Exception as err:
    print(err)
finally:
    con.close()

'Python' 카테고리의 다른 글

Python) Files input and output  (0) 2022.11.22
Python) Regular Expression  (0) 2022.11.21
Python) Database connection with SQLite  (0) 2022.11.19
Python) Class and Method  (0) 2022.11.18
Python) Database connection with Oracle  (0) 2022.11.18

To create an SQLite database

import sqlite3

def create_table():
   con = sqlite3.connect('naverDB')     

   cursor = con.cursor()                

# To create user table
   cursor.execute('''create table user(
                       id char(20),
                       username char(20),
                       email char(20),
                       birth char(20) )
                  ''')

   con.commit()
   con.close()

if __name__=='__main__':
    create_table()

To insert data with insert SQL:

import sqlite3

try:
    # To connect to the database
    con = sqlite3.connect('naverDB')

    cursor = con.cursor()
    
    while True:
        data1 = input('User ID?')
        if data1 == '':
            break
        data2 = input('User Name?')
        data3 = input('User Email?')
        data4 = input('User Date of Birth?')

        # sql = "insert into user values('" + data1 + "','" + data2 + "','" + data3 + "','" + data4 + "')"
        sql = "insert into user values(?, ?, ?, ?)"
        cursor.execute(sql, (data1,data2,data3,data4))

    con.commit()

except Exception as err:
    print(err)
    print('Failed to connect to the database')
finally:
    con.close()

To search the inserted data


import sqlite3

try:
    # To connect to the database
    con = sqlite3.connect('naverDB')

    cursor = con.cursor()

    cursor.execute('select * from user')

    print( User ID\t User Name\t User Email\t User DOB')
    print('---------------------------------------')

    # row = cursor.fetchone()                 
    # print(type(row))                        # <class 'tuple'>
    # print(row)                             

    rows = cursor.fetchall()                  # To search all
    print(type(rows))                         # <class 'list'>
    print(rows)

    for r in rows:
        print(r[0], r[1], r[2], r[3])

except Exception as err:
    print(err)
    print('Failed to connect database')
finally:

To update 


import sqlite3

try:
    con = sqlite3.connect('naverDB')

    cursor = con.cursor()

    id = input('Insert User ID.')
    email = input('Insert a new user email.')

    sql = "update user set email=? where id=?"
    cursor.execute(sql, (email, id))

    con.commit()

    cursor.execute('select * from user')
    rows = cursor.fetchall()
    for r in rows:
        print(r[0],r[1],r[2],r[3])

except Exception as err:
    print(err)
    print('Failed to connect to database')
finally:
    con.close()

To delete

import sqlite3

try:
    con = sqlite3.connect('naverDB')

    cursor = con.cursor()

    id = input('Insert User ID to delete.')

    sql = 'delete from user where id = ?'

    cursor.execute(sql, (id,) )
    con.commit()
    print('Successfully deleted.')

    cursor.execute('select * from user')
    rows = cursor.fetchall()
    for r in rows:
        print(r[0],r[1],r[2],r[3])

except Exception as err:
    print(err)
    print('Failed to connect')
finally:
    con.close()

'Python' 카테고리의 다른 글

Python) Regular Expression  (0) 2022.11.21
Python) Database connection with MySQL  (0) 2022.11.20
Python) Class and Method  (0) 2022.11.18
Python) Database connection with Oracle  (0) 2022.11.18
Python) try: except:  (0) 2022.11.14

Regarding class and inheritance, in Python for data analysis, we don't use them a lot, however, if you want to handle Django, it is necessary to know about classes and inheritance.

 

Class Example1

class Animal:
    name = 'dog'              
    age = 5

a1 = Animal()
# print(name)               
print(a1.name)                
print(a1.age)                 

a1.name = 'cat'
a1.age = 10
print(a1.name)               
print(a1.age)                

a2 = Animal()
print(a2.name)                
print(a2.age)

Class Example2

self. is similar to this. in Java.

class Car:

    def __init__(self):             # Constructor
       self.color = 'red'           
       self.wheel_size = 16        
       self.displacement = 2000     

    def forward(self):              # Method
        print('D')
    def backward(self):
        print('R')
    def turn_left(self):
        print('L')
    def turn_right(self):
        print('RR')

car1 = Car()                       

print(car1.color)                   # red
print(car1.wheel_size)              # 16
print(car1.displacement)            # 2000

car1.forward()                     
car1.backward()                     
car1.turn_left()                    
car1.turn_right()

Instance 

if __name__ == "__main__" allows You to Execute Code When the File Runs as a Script but Not When It’s Imported as a Module. You cannot import this in the other files if the file contains if __name__ == "__main__".

# if __name__=='__main__':

class InstanceVar:
    def __init__(self):             # Constructor
        self.text_list = []         

    def add(self, *text):          
        self.text_list.append(text)

    def print_list(self):           
        print(self.text_list)

if __name__=='__main__':
    a = InstanceVar()               
    a.add('Python', 'Oracle', 'Spring')
    a.print_list()                  
    print(a.text_list)              

    b = InstanceVar()              
    b.add('Java','JSP','tensorflow','keras')
    b.print_list()                 
    print(b.text_list)

Without if __name__ == "__main__"

def add(a, b):
    return a+b

def sub(a, b):
    return a-b

print(add(20, 10))              # 30
print(sub(20, 10))              # 10

With if __name__ == "__main__"

With this if statement, you cannot import in the other files. 

def add(a, b):
    return a+b

def sub(a, b):
    return a-b

if __name__=='__main__':
    print(add(20, 10))              # 30
    print(sub(20, 10))              # 10

if __name__ == "__main__" Example1

class ContactInfo:
    def __init__(self, name, email):           	# Constructor with parameters
        self.name = name                        
        self.email = email                      

    def print_info(self):
        print('{0} : {1}'.format(self.name, self.email))

if __name__=='__main__':
    ahn = ContactInfo('Zac','hong@naver.com')  
    ahn.print_info()
    print('name:', ahn.name)
    print('email:', ahn.email)

    ca = ContactInfo('choongang','master@gmail.com')
    ca.print_info()
    print('name:', ca.name)
    print('email:', ca.email)

Static Method

In java, @ is called an annotation whereas, in Python, we call it "Decorator".

When you use this decorator, it is a static method(@staticmethod). With this, you do not use self.

class Calculator:

    @staticmethod
    def plus(a,b):                 
        return a+b

    @staticmethod
    def minus(a,b):
        return a-b

    @staticmethod
    def multiply(a,b):
        return a*b

    @staticmethod
    def divide(a,b):
        return a/b

if __name__=='__main__':             
    print('{0}+{1}={2}'.format(7,4, Calculator.plus(7,4)))
    print('{0}-{1}={2}'.format(7,4, Calculator.minus(7,4)))
    print('{0}*{1}={2}'.format(7,4, Calculator.multiply(7,4)))
    print('{0}/{1}={2}'.format(7,4, Calculator.divide(7,4)))

 

'Python' 카테고리의 다른 글

Python) Database connection with MySQL  (0) 2022.11.20
Python) Database connection with SQLite  (0) 2022.11.19
Python) Database connection with Oracle  (0) 2022.11.18
Python) try: except:  (0) 2022.11.14
Python) list  (0) 2022.11.08

You must install cx-oracle library in pycharm to demonstrate this.

To test Python with Oracle

import cx_Oracle

try:
    # con = cx_Oracle.connect('ID/PASSWORD@IP:1521/INSTANCE NAME')
    con = cx_Oracle.connect('scott/tiger@localhost:1521/xe')
    
    cursor = con.cursor()
    
    cursor.execute('select * from dept')
    # cursor.execute('select * from board0')

    row = cursor.fetchone()             
    print(type(row))                    # <class 'tuple'>
    print(row)                          # (10, 'ACCOUNTING', 'NEW YORK')

    rows = cursor.fetchall()           
    print(type(rows))                   # <class 'list'>
    print(rows)

except Exception as err:
    print(err)
finally:
    con.close()

To insert data

import cx_Oracle

try:
    con = cx_Oracle.connect('scott/tiger@localhost:1521/xe')
    cursor = con.cursor()

    no = int(input('Insert DEPT NO.'))
    name = input('Insert DEPT NAME.')
    local = input('Insert LOCATION.')

    sql = "insert into dept values(:no, :name, :local)"
    cursor.execute(sql, no=no, name=name, local=local)
    con.commit()
    print('Your data has been successfully inserted.')

except Exception as err:
    print(err)
finally:
    con.close()

To search data

import cx_Oracle

try:
    con = cx_Oracle.connect('scott/tiger@localhost:1521/xe')
    cursor = con.cursor()

    no = input('Enter DEPT NO to search.')

    sql = "select * from dept where deptno = :no"

    cursor.execute(sql, no = no)
    rows = cursor.fetchall()          
    for r in rows:
        print(r[0], r[1], r[2])

except Exception as err:
    print(err)
finally:
    con.close()

To update data

import cx_Oracle

try:
    con = cx_Oracle.connect('scott/tiger@localhost:1521/xe')
    cursor = con.cursor()

    no = input('Insert DEPT NO to update')
    name = input('Insert DEPT NAME to update')
    local = input('Insert LOCATION to update')

    sql = "update dept set dname=:name, loc=:local where deptno=:no"
    cursor.execute(sql, name=name, local=local, no=no)
    con.commit()
    print('Successfully updated')

except Exception as err:
    print(err)
finally:
    con.close()

To delete

import cx_Oracle

try:
    con = cx_Oracle.connect('scott/tiger@localhost:1521/xe')

    cursor = con.cursor()

    no = input('Insert DEPT NO to delete.')

    sql = "delete from dept where deptno = :no"

    cursor.execute(sql, no=no)
    con.commit()

    print('Successfully deleted.')

except Exception as err:
    print(err)
finally:
    con.close()

'Python' 카테고리의 다른 글

Python) Database connection with SQLite  (0) 2022.11.19
Python) Class and Method  (0) 2022.11.18
Python) try: except:  (0) 2022.11.14
Python) list  (0) 2022.11.08
Python) Control statements  (0) 2022.11.06

try: except: to handle the exceptions that occur while the codes run.

The format is like this:

try:
  print(x)
except:
  print("An exception occurred")

You can specify the exceptions. Here are some examples. 

list = [1, 2, 3]

try:
    index = int(input('Insert an index number.'))   # 0, 1, 2
    print(list[index]/0)
except ZeroDivisionError:              
    print('Cannot be divided into 0.')
except IndexError:                     
    print('Wrong index.')
except ValueError:                      
    print('Not a number.')

try: except: can have else: if there is no exception. 

else is opposed to except. Here is an example.

list = [1, 2, 3]

try:
    index = int(input('Insert an index number'))   # 0, 1, 2
    print('list[{0} : {1}]'.format(index, list[index]))
except Exception as err:
    print('Exception:{0}'.format(err))
else:
    print('Success')

With finally: , you will execute the code without any conditions so even though there is an exception, you will see the finally statement will be executed.

try:
    print('Hello.')
    print(param)                    
except:
    print('Exception')
finally:
    print('Execute!')

You can also use else and finally in the same code. Try will test the excepted error to occur, except will handle the error, else will be executed if there is no exception, and finally gets executed either exception is generated or not. 

def divide(x, y):
    try:
        result = x // y
    except ZeroDivisionError:
        print("You cannot divide into 0. ")
    else:
        print("Answer: ", result)
    finally: 
        print('This is always executed')

raise is to define what kind of error to raise, and the text to print to the user.

def some_function():
    num = int(input('Insert an integer from 1 to 10'))
    if num<1 or num>10:    
        raise  Exception('Invalid number.{0}'.format(num))
    else:
        print('You inserted {0}.'.format(num))

try:
    some_function()                    
except Exception as err:
    print('Exception.{0}'.format(err))

'Python' 카테고리의 다른 글

Python) Class and Method  (0) 2022.11.18
Python) Database connection with Oracle  (0) 2022.11.18
Python) list  (0) 2022.11.08
Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04

append()

append() function is to add 

a = [1, 2, 3]
a.append(4)                 # add 4
print('a:', a)              # [1, 2, 3, 4]

a.append([5, 6])            # add [5, 6] 
print('a:', a)              # [1, 2, 3, 4, [5, 6]]

index()

It is like indexOf() in Java.

It is different from find()

 

 

pop()

To delete the last one

list = [10, 20, 30, 40, 50]
data1 = list.pop()             
print('data1:', data1)         
print('list:', list)           

data2 = list.pop(2)            
print('data2:', data2)          
print('list:', list)

insert()

a = [1, 2, 3]

# index no.0 -> put '4'
a.insert(0, 4)
print('a:', a)                  # [4, 1, 2, 3]

a.insert(3, 5)
print('a:', a)                  # [4, 1, 2, 5, 3]

sort()

namelist = ['Mary','Sams','Amy','Tom','Mike','Bob','Kelly']

namelist.sort()               # ascending order
print('namelist:', namelist)  

namelist.sort(reverse=True)    # descending order
print('namelist:', namelist)

sorted()

The difference between sort() and sorted() is that if you use sort(), the original list remains unchanged.

namelist = ['Mary','Sams','Amy','Tom','Mike','Bob','Kelly']

result1 = sorted(namelist)                  # ascending order
result2 = sorted(namelist, reverse= True)   # descending order
print(type(result1))                        # <class 'list'>
print(type(result2))

print('result1:', result1)  # ['Aimy', 'Bob', 'Kelly', 'Mary', 'Michale', 'Sams', 'Tom']
print('result2:', result2)  # ['Tom', 'Sams', 'Michale', 'Mary', 'Kelly', 'Bob', 'Aimy']

print('namelist:', namelist)

 

sort() and sorted() reverse() Example

# Change from [1, 3, 5, 4, 2] to [5, 4, 3, 2, 1]
list = [1, 3, 5, 4, 2]

#1. sort()
list.sort(reverse=True)                 
print('list:', list)

#2. sort(), reverse()
list.sort()                             
list.reverse()                          
print('list:', list)

#3. sorted()
list2 = sorted(list, reverse=True)     
print('list2:', list2)

#4. sorted(), reverse()
list3 = sorted(list)                   
list3.reverse()                         
print('list3:', list3)

list with dictionary

people = [
    {'name': 'noah', 'age': 19},
    {'name': 'liam', 'age': 23},
    {'name': 'jacob', 'age': 9},
    {'name': 'mason', 'age': 21}
]

# 1
people.sort(key=lambda x: x['age'])
print(people)

# 2
result = sorted(people, key=lambda x: x['age'])
print(result)

'Python' 카테고리의 다른 글

Python) Database connection with Oracle  (0) 2022.11.18
Python) try: except:  (0) 2022.11.14
Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04
Python) Tuple / Set  (0) 2022.11.03

if

Since there are no brackets like in Java, indentation is very important in the if statement. 

In the example below, you must convert the string type 'n' to an integer

n = input('Insert an integer.')
print(type(n))             
n = int(n)                 

if n>=0 :
    print(n, 'is a positive number.')

if n<0:
    print(n, 'is a negative number.')

if ~ else with try~ except

try:
    n = int(input('Insert an integer.'))
    
    if n >= 0:
        print(n, 'is a positive number.')
    else:
        print(n, 'is a negative number.')
    
except:
    print('Please insert numbers only.')

if ~ elif ~ else

In Java, there is else if, whereas in Python it is elif. 

s = int(input('Insert your score.'))

if s >= 90:
    print('A')
elif s >= 80:
    print('B')
elif s >= 70:
    print('C')
elif s >= 60:
    print('C')
else:
    print('F')

 

Loops: for / while 

There is no do ~ while statement in Python. Usually for loops are used a lot.

for loop

for loops are many times used with range() built-in function.

Please refer to my last post if you want to know more about the range() function.

링크

Example1

for i in range(10):             # 0 ~ 9
    print(i+1, 'Cofee and Tea')

for i in range(1, 11):          # 1 ~ 10
    print(i, 'Love in Life')
    
for i in range(1, 11, 1):       # 1 ~ 10   
    print(i, 'Happy days')

Example2 

for i in range(1, 10, 2):
    print(i, end=' ')                   # 1 3 5 7 9
print()

for i in range(1, 10):                  # 1 ~ 9
    print(i, end=' ')                   # 1 2 3 4 5 6 7 8 9
print()

for i in range(10):                     # 0 ~ 9
    print(i, end=' ')                   # 0 1 2 3 4 5 6 7 8 9
print()

for i in range(10, 1, -1):
    print(i, end=' ')                   # 10 9 8 7 6 5 4 3 2

Example3

sum = 0
for i in range(1, 11):              #  1 ~ 10
    sum = sum + i                   # sum += i
    print('1~',i,'=',sum)

print('sum=', sum)

Example4

# Sum of odd numbers
odd = 0
for i in range(1, 101, 2):
    odd += i
print(odd)

# sum of even numbers
even = 0
for i in range(0, 101, 2):
    even += i
print(even);

Example5

It is the same result as Example4, but it is a simpler way with just one for loop. 

odd = even = 0
for i in range(1, 101):                 # 1 ~ 100
    if i%2 == 0:                        # Even 
        even += i
    else:                               # Odd
        odd += i
print('1~100 sum of odd numbers:', odd)
print('1~100 sum of even numbers:', even)

Example6

#Multiplication table with a format() function.

dan = int(input('Insert a number between 1 and 9.'))

print('[',dan,'Table ]')
for i in range(1, 10):              # 1 ~ 9
    # print(dan, '*', i, '=', dan * i)
    print('{0} * {1} = {2}'.format(dan, i, dan*i))

Example7 

for loop with list

# List
list = ['China', 'Canada', 'Egypt', 'South Korea', 'France']
print(type(list))              # <class 'list'>
print(list)                    # ['China', 'Canada', 'Egypt', 'South Korea', 'France']
print(list[0])                 # China

for i in list:
    print(i, end=' ')           # China Canada Egypt South Korea France
print()

for loop with tuple

#Tuple
t = ('red','orange','yellow','green','blue','navy','purple')
print(type(t))                  # <class 'tuple'>
print(t)                        # ('red', 'orange', 'yellow', 'green', 'blue', 'navy', 'purple')
print(t[0])                     # red

for i in t:
    print(i, end=' ')           # red orange yellow green blue navy purple
print()

for loop with dictionary

# Dictionary : { 'key' : 'value' }
dic = {'Apple' : 'http://www.apple.com',
       'Google' : 'http://www.google.com',
       'Naver' : 'http://www.naver.com'}

print(type(dic))                # <class 'dict'>
print(dic)                      # {'Apple': 'http://www.apple.com', 'Google': 'http://www.google.com', '네이버': 'http://www.naver.com'}
print(dic['Apple'])             # http://www.apple.com

for k, v in dic.items():
    print(k,':', v)

while loop

while loop is very similar to Java.

Example1 

i = 1                          
while i <= 10 :                
    print(i,'I love Python')           
    i += 1

Example2

i=1; odd=even=0                
while i <= 100:                # Condition
    if i%2 == 0:                # Even numbers
        even += i
    else:                       # Odd numbers
        odd += i
    i += 1                      

print('1~100 sum of odd numbers:',  odd)
print('1~100 sum of even numbers:',  even)

Example3

Multiplication table with format function.

dan = int(input('Insert a number between 1 to 9'))

i = 1                                  
while  i <= 9:                          
    # print(dan, '*', i, '=', dan*i)
    print('{0} * {1} = {2}'.format(dan, i, dan*i))
    i += 1

Example4

Multiplication table

dan=2                                     
while dan <= 9:                             
    print('[',dan,'Table ]')
    i = 1
    while i <= 9:                           
        print(dan, '*', i, '=', dan*i)
        i += 1                              
    dan += 1                              
    print()

break and continue

Infinite loop 

i=1
while True:

    print(i, 'Infinite loop')
    i += 1

Infinite loop with break

i=1
while True:

    print(i, 'Infinite loop')
    if i == 100: break
    i += 1

for, if, and break

for i in range(1, 1001):            # 1 ~ 1000
    print(i,'Print')

    if i==100:
        print('Loop Escaped')
        break

continue

continue is for going back to the loop. 

Example1 

for i in range(1, 11):              # 1 ~ 10

    if i==5:
        continue
    print(i, 'Print')

Example2 

If it is not divided into 5, it skips printing.

for i in range(1, 101):             # 1 ~ 100

    if i%5 != 0:                    
        continue
    print(i)

'Python' 카테고리의 다른 글

Python) try: except:  (0) 2022.11.14
Python) list  (0) 2022.11.08
Python) Dictionary  (0) 2022.11.04
Python) Tuple / Set  (0) 2022.11.03
Python) Datatypes - Str  (0) 2022.11.03

Str, List and Dictionary are the most used data structure. 

To save data in a dictionary, you must save the key and value(data) together, and you will use the key to get the value. Like set, dictionary is not an ordered data structure as well. If there are multiple overlapped key and we search the same key, it will print out the value of the last key.

Example

{ 'key ' : 'value' } = { 'Name' : code }
names = {'Mary':10999, 'Sams':2111, 'Amy':9778, 'Tom':20245 , 'Mike':27115,
         'Bob':5887, 'Kelly':7855, 'Mary':100}
print(type(names))           # <class 'dict'>
print(names)                 # {'Mary': 100, 'Sams': 2111, 'Amy': 9778, 'Tom': 20245, 'Mike': 27115, 'Bob': 5887, 'Kelly': 7855}

print(names['Amy'])        # 9778
print(names['Tom'])         # 20245
print(names['Mary'])        # 100

keys()

names = {'Mary':10999, 'Sams':2111, 'Amy':9778, 'Tom':20245 , 'Mike':27115,
         'Bob':5887, 'Kelly':7855}

for k in names.keys():
    # print('Key:%s\t Value:%d'%(k, names[k]))
    # print('Key:', k, ' Value:', names[k])
    print('Key:{0} Value:{1}'.format(k, names[k]))

values()

result = names.values()
print(type(result))               # <class 'dict_values'>
print(result)                     # dict_values([10999, 2111, 9778, 20245, 27115, 5887, 7855])

list = list(result)              # list()
print(type(list))                # <class 'list'>
print(list)                      # [10999, 2111, 9778, 20245, 27115, 5887, 7855]

count()

count = sum(list)
print('Sum:%d'%count)

items()

for item in names.items():
    print(item)                 # ('Mary', 10999)
                                # ('Sams', 2111)
                                # ...

for k, v in names.items():
    print(k,':',v)              # Mary : 10999
                                # Sams : 2111
                                # ...

To edit dictionary values

names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245 , 'Michale':27115,
         'Bob':5887, 'Kelly':7855}

print(names)
print(names['Aimy'])            # 9778
print(names.get('Aimy'))        # 9778

names['Aimy'] = 10000

print(names['Aimy'])            # 10000

To delete dictionary values

names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245 , 'Michale':27115,
         'Bob':5887, 'Kelly':7855}

del names['Sams']
del names['Bob']

# To check
print(names)

# Delete all
names.clear()

# To check
print(names)            # {}

mydic = {}

Example

names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245 , 'Michale':27115,
         'Bob':5887, 'Kelly':7855}

k = input('Enter the name.')

if k in names: 
    print('%s: %d'%(k, names[k]))
else:
    print('There is no ''%s''.'%k)
    names[k] = 1000;

print(names)

Ascending and descending order of dictionary

names = {'Mary':10999, 'Sams':2111, 'Aimy':9778, 'Tom':20245 , 'Michale':27115,
         'Bob':5887, 'Kelly':7855}

def f1(x):
    return x[0]

def f2(x):
    return x[1]

# 1. key, ascending
result1 = sorted(names)
print('result1:', result1)              # ['Aimy', 'Bob', 'Kelly', 'Mary', 'Michale', 'Sams', 'Tom']

result2 = sorted(names.items(), key=f1)
print('result2:', result2)              # [('Aimy', 9778), ('Bob', 5887), ('Kelly', 7855), ('Mary', 10999), ('Michale', 27115), 'Tom']

# 2. key, descending
result3 = sorted(names, reverse=True)
print('result3:', result3)              # ['Tom', 'Sams', 'Michale', 'Mary', 'Kelly', 'Bob', 'Aimy']

result4 = sorted(names.items(), reverse=True , key=f1)
print('result4:', result4)              # [('Tom', 20245), ('Sams', 2111), ('Michale', 27115), ('Mary', 10999), ('Kelly', 7855)y']

# 3. value ascending
result5 = sorted(names.items(), key=f2)
print('result5:', result5)              # [('Sams', 2111), ('Bob', 5887), ('Kelly', 7855), ('Aimy', 9778), ('Mary', 10999),

# 4. value descending
result6 = sorted(names.items(), reverse=True , key=f2)
print('result6:', result6)                # [('Michale', 27115), ('Tom', 20245), ('Mary', 10999), ('Aimy', 9778), ('Kelly', 7855)

 

'Python' 카테고리의 다른 글

Python) list  (0) 2022.11.08
Python) Control statements  (0) 2022.11.06
Python) Tuple / Set  (0) 2022.11.03
Python) Datatypes - Str  (0) 2022.11.03
Python) Variables and Operators  (0) 2022.10.29

Tuple()

Tuple is what only Python has.

It is similar to lists, but there are a few differences.

Your use () instead of [], and once you put the data in the tuple, the data cannot be edited. As lists, you can mix different datatypes in the tuples.

Example1

t1 = ()                         # An empty tuple
t2 = (1,)
t3 = (1,2,3)
t4 = 1, 2, 3
t5 = (30, 3.14, True, False, 'python')
# t5[1] = 42.195               # error: tuple cannot be edited.
t6 = ('a', 'b', 'c', ('ab', 'cd'))

print(type(t1))                 # <class 'tuple'>
print(type(t2))                 # <class 'tuple'>
print(type(t4))                 # <class 'tuple'>
print('t1:', t1)
print('t2:', t2)
print('t3:', t3)
print('t4:', t4)
print('t5:', t5)
print('t6:', t6)

indexing

t1 = (1, 2, 'a', 'b')
print(t1[0])                        # 1
print(t1[1])                        # 2
print(t1[2])                        # a
print(t1[3])                        # b
print(t1[-1])                       # b

slicing

# [ start index : end index ]
t2 = (10, 20, 30, 40, 50)
print(t2[1:3])                      # 1 - 2 : (20, 30)
print(t2[ :4])                      # 0 - 3  : (10, 20, 30, 40)
print(t2[1:])                       # 1 - end : (20, 30, 40, 50)

add

print(t1 + t2)                      # (1, 2, 'a', 'b', 10, 20, 30, 40, 50)
print(t2 + t1)                      # (10, 20, 30, 40, 50, 1, 2, 'a', 'b')

multiply

print(t2 * 3)            # (10, 20, 30, 40, 50, 10, 20, 30, 40, 50, 10, 20, 30, 40, 50)

len() with tuple

t1 = (10, 20, 30, 40, 50)
print(len(t1))                      # len : 5
print(t1)                           # (10, 20, 30, 40, 50)

count() with tuple

t2 = (1,100,2,100,3,100,4,100,5,100)
print(t2.count(100))

index() with tuple

t3 = ('java','jsp','python','spring','R','tensorflow','keras')
print(t3.index('spring'))

tuple packing

To bind multiple data into the tuple

t1 = 10, 20, 30
print(type(t1))                     # <class 'tuple'>
print(t1)                           # (10, 20, 30)

tuple unpacking

10 -> one / 20 -> two / 30 -> three

one, two, three = t1
print('one:', one)                  # 10
print('two:', two)                  # 20
print('three:', three)              # 30

 

set()

You can't save overlapped data in set(). It is not an ordered data structure so you can't print the data out in order.

s1 = set([1,2,3,4])
print(type(s1))                     # <class 'set'>
print(s1)                           # {1, 2, 3, 4}

s2 = set('Hello')
print(type(s2))                     # <class 'set'>
print(s2)                           # {'e', 'H', 'o', 'l'}

set() -> list() 

list1 = list(s3)
print(type(list1))                  # <class 'list'>
print(list1)                        # [1, 2, 3]
print(list1[0])                     # 1
print(list1[1])                     # 2
print(list1[2])                     # 3

set() -> tuple()

t1 = tuple(s3)
print(type(t1))                     # <class 'tuple'>
print(t1)                           # (1, 2, 3)
print(t1[0])                        # 1
print(t1[1])                        # 2
print(t1[2])                        # 3

intersection(), union(), and difference()

s1 = set([1,2,3,4,5,6])
s2 = set([4,5,6,7,8,9])

# 1. intersection()
print(s1 & s2)                          # {4, 5, 6}
print(s1.intersection(s2))              # {4, 5, 6}

# 2. union()
print(s1 | s2)                          #  {1, 2, 3, 4, 5, 6, 7, 8, 9}
print(s1.union(s2))                     #  {1, 2, 3, 4, 5, 6, 7, 8, 9}

# 3. difference()
print(s1 - s2)                          # {1, 2, 3}
print(s1.difference(s2))                # {1, 2, 3}

print(s2 - s1)                          # {8, 9, 7}
print(s2.difference(s1))                # {8, 9, 7}

add(), update(), and remove()

# 1. add() 
s1 = set([1, 2, 3])
s1.add(3)                          # Overlapped data cannot be saved.
s1.add(4)
# s1.add([4, 5])                   # Only one data can be saved.
print(s1)                          # {1, 2, 3, 4}

# 2. update() : to add multiple data
s2 = set([1, 2, 3])
s2.update([4, 5, 6])
print(s2)                           # {1, 2, 3, 4, 5, 6}

# 3. remove() 
s3 = set([1, 2, 3])
s3.remove(2)                       
s3.remove(3)                       
print(s3)                           # {1}

'Python' 카테고리의 다른 글

Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04
Python) Datatypes - Str  (0) 2022.11.03
Python) Variables and Operators  (0) 2022.10.29
Python) Configuration and Basics  (0) 2022.10.27
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
None Type: NoneType

String 

s1 = 'Hello World'
print(type(s1))                 # <class 'str'>
print(s1)

s2 = "Python is fun"
print(type(s2))                 # <class 'str'>
print(s2)

s3 = '''Life is too short, you need python.'''
print(type(s3))                 # <class 'str'>
print(s3)

s4 = """Life is too short, you need python."""
print(type(s4))                 # <class 'str'>
print(s4)

Unlike other languages, in Python, you can add and multiply the strings. 

head = 'Python'
tail = ' is fun'
str = head + tail
print(str)                     
print(head + tail)             

s = 'python'
print(s * 2)                  
print(s * 3)                   

print('='*50)                 
print('My Program')
print('='*50)                  

print('*'*1)
print('*'*2)
print('*'*3)
print('*'*4)
print('*'*5)

print('*'*5)
print('*'*4)
print('*'*3)
print('*'*2)
print('*'*1)

Indexing

Indexing is used when you need to extract parts of the data. 

The first letter is index'0', and the last letter is index'-1'. 

s = 'Life is too short, you need python'
print(s)

print(s[0])                 # L
print(s[3])                 # e
print(s[-1])                # n
print(s[-2])                # o

str = 'korea'
print(str[0])               # k
print(str[-2])              # e

Slicing

Example1

# format :  variable[ start : stop ]

s = 'Life is too short, you need python'

print(s[0:2])         # 0 - 1 : Li
print(s[0:5])         # 0 - 4 : Life
print(s[5:7])         # 5 - 6 : is
print(s[12:17])       # 12 - 16 : short

print(s[ : 7])        # 0 -6 : Life is

print(s[5 : ])        # 5 - last : is too short, you need python

print(s[ : ])         # first - last


str = '20201024Rainy'
date = str[:8]              # 20201024
weather = str[8:]           # Rainy
print(date,':', weather)


year = str[:4]              # 2020
month = str[4:6]            # 10
day = str[6:8]              # 24
print(year, 'Year', month, 'Month', day, 'Day')

 

Example2

str = 'korea'

print(str[0])           # [0] : k
print(str[-2])          # The second last : e

print(str[1:3])         # 1 - 2 : or
print(str[0:5:2])       # 0 - 4 (+2) : kra
print(str[:-1])         # first - -2 : kore
print(str[::-1])        # reverse : aerok

Example3 

To change strings with slicing, you need to slice first and combine the letters.

s = 'pithon'
print(s[1])                       # i

# i -> y 
# s[1] = 'y'                      # TypeError: 'str' object does not support item assignment

s = s[:1] + 'y' + s[2:]           # python
print(s)

 

Functions

upper() / lower()

txt = 'A lot of things happen everyday.'

result1 = txt.upper()
result2 = txt.lower()

print('result1:', result1)  #result1: A LOT OF THINGS HAPPEN EVERYDAY.
print('result2:', result2)  #result2: a lot of things happen everyday.

format()

%s String
%c Character
%d Integer
%f float
%%
txt1 = 'Java'; txt2 = 'Python'
num1 = 5; num2 = 10

print('I like %s and %s!' %(txt1, txt2))
print('%s is %d times easier than %s.' %(txt2,num1,txt1))
print('%d + %d = %d' %(num1, num2, num1+num2))
print('Inflation rate in 2022: %d%%' %num1)

len()

msg = input('Insert a sentence.')
print(type(msg))
len = len(msg)                

print('The length of the sentence is ', len,'.')
print('The length of the sentence is {}.'.format(len))
print('The length of the sentence is %d.'%len)

count()

txt = 'A lot of things occur each day, every day.'

count1 = txt.count('o')            
count2 = txt.count('day')         
count3 = txt.count(' ')           

print('count1:', count1)
print('count2:', count2)
print('count3:', count3)

escape()

\n enter
\t tab
\\ print"\"
\' print"'"
\" print"""
print('I love Python.\n Python is easier than other languages!')
print('Name:John Simth\tSex:Male\tAge:22')
print('\"Welcome to Meadow\'s devlog!\"')
print('\'python\"')                
print('\\Java\\')

find()

txt = 'Today is Tuesday! I love Tuesdays.'

offset1 = txt.find('e')         # first 'e'
offset2 = txt.find('day')       # first 'day'
offset3 = txt.find('day', 20)   # 'day' after index[20]
offset4 = txt.find('j')         # no 'j' => returns -1

print('offset1:', offset1)		#11
print('offset2:', offset2)		#2
print('offset3:', offset3)		#29
print('offset4:', offset4)		#-1

 

strip()

txt = '    I am hungry!    '

result1 = txt.lstrip()  
result2 = txt.rstrip()
result3 = txt.strip()

print('<'+txt+'>')   #<    I am hungry!    >
print('<'+result1+'>')  #<I am hungry!    >
print('<'+result2+'>')  #<    I am hungry!>
print('<'+result3+'>') #<I am hungry!>

isdigit()

txt1 = '010-1234-5678'
txt2 = 'R2D2'
txt3 = '1212'

result1 = txt1.isdigit()
result2 = txt2.isdigit()
result3 = txt3.isdigit()

print('result1:', result1)          # False 
print('result2:', result2)          # False
print('result3:', result3)          # True

 

'Python' 카테고리의 다른 글

Python) Control statements  (0) 2022.11.06
Python) Dictionary  (0) 2022.11.04
Python) Tuple / Set  (0) 2022.11.03
Python) Variables and Operators  (0) 2022.10.29
Python) Configuration and Basics  (0) 2022.10.27

+ Recent posts