60 Basic Python Exercises for Beginners (Part Three)

60 Basic Python Exercises for Beginners (Part Three)Click the image below to search for the secret code[Interview Guide], claim it nowInterview Questions + Resume Template.

60 Basic Python Exercises for Beginners (Part Three)

41 – String Formatting

"%s is %s years old" % ('bob', 23)  # Commonly used
"%s is %d years old" % ('bob', 23)  # Commonly used
"%s is %d years old" % ('bob', 23.5)  # %d is an integer, commonly used
"%s is %f years old" % ('bob', 23.5)
"%s is %5.2f years old" % ('bob', 23.5)  # %5.2f has a width of 5 and 2 decimal places
"97 is %c" % 97
"11 is %#o" % 11  # %#o indicates octal with prefix
"11 is %#x" % 11
"%10s%5s" % ('name', 'age')  # %10s indicates a total width of 10, right-aligned, commonly used
"%10s%5s" % ('bob', 25)
"%10s%5s" % ('alice', 23)
"%-10s%-5s" % ('name', 'age')  # %-10s indicates left alignment, commonly used
"%-10s%-5s" % ('bob', 25)
"%10d" % 123
"%010d" % 123

"{} is {} years old".format('bob', 25)
"{1} is {0} years old".format(25, 'bob')
"{:<10}{:<8}".format('name', 'age')

42 – Common Methods of shutil Module

import shutil


with open('/etc/passwd', 'rb') as sfobj:
    with open('/tmp/mima.txt', 'wb') as dfobj:
        shutil.copyfileobj(sfobj, dfobj) # Copy file object


shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')
shutil.copy('/etc/shadow', '/tmp/')  # cp /etc/shadow /tmp/
shutil.copy2('/etc/shadow', '/tmp/')  # cp -p /etc/shadow /tmp/
shutil.move('/tmp/mima.txt', '/var/tmp/')  # mv /tmp/mima.txt /var/tmp/
shutil.copytree('/etc/security', '/tmp/anquan') # cp -r /etc/security /tmp/anquan
shutil.rmtree('/tmp/anquan')  # rm -rf /tmp/anquan
# Set permissions of mima2.txt to be the same as /etc/shadow
shutil.copymode('/etc/shadow', '/tmp/mima2.txt')
# Set metadata of mima2.txt to be the same as /etc/shadow
# Use stat /etc/shadow to view metadata
shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')

43 – Exercise: Generate Text File

import os


def get_fname():
    while True:
        fname = input('filename: ')
        if not os.path.exists(fname):
            break
        print('%s already exists. Try again' % fname)


    return fname

def get_content():
    content = []
    print('Input data, type end to finish')
    while True:
        line = input('> ')
        if line == 'end':
            break
        content.append(line)


    return content

def wfile(fname, content):
    with open(fname, 'w') as fobj:
        fobj.writelines(content)

if __name__ == '__main__':
    fname = get_fname()
    content = get_content()
    content = ['%s\n' % line for line in content]
    wfile(fname, content)

44 – List Methods

alist = [1, 2, 3, 'bob', 'alice']
alist[0] = 10
alist[1:3] = [20, 30]
alist[2:2] = [22, 24, 26, 28]
alist.append(100)
alist.remove(24)  # Delete the first 24
alist.index('bob')  # Return index
blist = alist.copy()  # Equivalent to blist = alist[:]
alist.insert(1, 15)  # Insert number 15 at index 1
alist.pop()  # Default pops the last item
alist.pop(2) # Pops the item at index 2
alist.pop(alist.index('bob'))
alist.sort()
alist.reverse()
alist.count(20)  # Count occurrences of 20 in the list
alist.clear()  # Clear the list
alist.append('new')
alist.extend('new')
alist.extend(['hello', 'world', 'hehe'])

45 – Check Valid Identifier

import sys
import keyword
import string


first_chs = string.ascii_letters + '_'
all_chs = first_chs + string.digits

def check_id(idt):
    if keyword.iskeyword(idt):
        return "%s is keyword" % idt


    if idt[0] not in first_chs:
        return "1st invalid"


    for ind, ch in enumerate(idt[1:]):
        if ch not in all_chs:
            return "char in position #%s invalid" % (ind + 2)


    return "%s is valid" % idt

if __name__ == '__main__':
    print(check_id(sys.argv[1]))  # python3 checkid.py abc@123

46 – Create User and Set Random Password

Refer to the randpass module in "37 - Generate Password/Verification Code"

import subprocess
import sys
from randpass import gen_pass

def adduser(username, password, fname):
    data = """user information:
%s: %s
"""
    subprocess.call('useradd %s' % username, shell=True)
    subprocess.call(
        'echo %s | passwd --stdin %s' % (password, username),
        shell=True
    )
    with open(fname, 'a') as fobj:
        fobj.write(data % (username, password))

if __name__ == '__main__':
    username = sys.argv[1]
    password = gen_pass()
    adduser(username, password, '/tmp/user.txt')
# python3 adduser.py john

47 – List Exercise: Simulate Stack Operations

stack = []

def push_it():
    item = input('item to push: ')
    stack.append(item)

def pop_it():
    if stack:
        print("from stack popped %s" % stack.pop())

def view_it():
    print(stack)

def show_menu():
    cmds = {'0': push_it, '1': pop_it, '2': view_it}  # Store functions in a dictionary
    prompt = """(0) push it
(1) pop it
(2) view it
(3) exit
Please input your choice(0/1/2/3): """


    while True:
        # input() gets a string, use strip() to remove whitespace, then take the first character
        choice = input(prompt).strip()[0]
        if choice not in '0123':
            print('Invalid input. Try again.')
            continue


        if choice == '3':
            break


        cmds[choice]()
        
if __name__ == '__main__':
    show_menu()

48 – Implement Unix2Dos Functionality in Linux

import sys

def unix2dos(fname):
    dst_fname = fname + '.txt'


    with open(fname) as src_fobj:
        with open(dst_fname, 'w') as dst_fobj:
            for line in src_fobj:
                line = line.rstrip() + '\r\n'
                dst_fobj.write(line)

if __name__ == '__main__':
    unix2dos(sys.argv[1])

49 – Animation Program: @ Moving Through a Line of #

\r is carriage return without line break

import time


length = 19
count = 0


while True:
    print('\r%s@%s' % ('#' * count, '#' * (length - count)), end='')
    try:
        time.sleep(0.3)
    except KeyboardInterrupt:
        print('\nBye-bye')
        break
    if count == length:
        count = 0
    count += 1

50 – Basic Dictionary Usage

adict = dict()  # {}
dict(['ab', 'cd'])
bdict = dict([('name', 'bob'),('age', 25)])
{}.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)


for key in bdict:
    print('%s: %s' % (key, bdict[key]))


print("%(name)s: %(age)s" % bdict)


bdict['name'] = 'tom'
bdict['email'] = '[email protected]'


del bdict['email']
bdict.pop('age')
bdict.clear()

51 – Common Dictionary Methods

adict = dict([('name', 'bob'),('age', 25)])
len(adict)
hash(10)  # Check if the given data is immutable, only immutable data can be used as key
adict.keys()
adict.values()
adict.items()
# get method is commonly used, important
adict.get('name')  # Get the value corresponding to name in the dictionary, returns None if not found
print(adict.get('qq'))  # None
print(adict.get('qq', 'not found'))  # If qq is not found, return specified content
print(adict.get('age', 'not found'))
adict.update({'phone': '13455667788'})

52 – Common Set Methods

# A set is essentially a dictionary with no values, so it is also represented by {}
myset = set('hello')
len(myset)
for ch in myset:
    print(ch)


aset = set('abc')
bset = set('cde')
aset & bset  # Intersection
aset.intersection(bset)  # Intersection
aset | bset  # Union
aset.union(bset)  # Union
aset - bset  # Difference
aset.difference(bset)  # Difference
aset.add('new')
aset.update(['aaa', 'bbb'])
aset.remove('bbb')
cset = set('abcde')
dset = set('bcd')
cset.issuperset(dset)  # Is cset a superset of dset?
cset.issubset(dset)  # Is cset a subset of dset?

53 – Set Example: Extract Lines Present in the Second File but Not in the First

# cp /etc/passwd .
# cp /etc/passwd mima
# vim mima  -> Modify, differing from passwd


with open('passwd') as fobj:
    aset = set(fobj)


with open('mima') as fobj:
    bset = set(fobj)


with open('diff.txt', 'w') as fobj:
    fobj.writelines(bset - aset)

54 – Dictionary Exercise: Simulate Registration/Login

import getpass


userdb = {}

def register():
    username = input('username: ')
    if username in userdb:
        print('%s already exists.' % username)
    else:
        password = input('password: ')
        userdb[username] = password

def login():
    username = input('username: ')
    password = getpass.getpass("password: ")
    if userdb.get(username) != password:
        print('login failed')
    else:
        print('login successful')

def show_menu():
    cmds = {'0': register, '1': login}
    prompt = """(0) register
(1) login
(2) exit
Please input your choice(0/1/2): """


  while True:
           choice = input(prompt).strip()[0]
           if choice not in '012':
               print('Invalid input. Try again.')
               continue
           if choice == '2':
               break
   
           cmds[choice]()
 
if __name__ == '__main__':
    show_menu()

55 – Calculate Time for Ten Million Addition Operations

import time


result = 0
start = time.time()  # Return timestamp before operation
for i in range(10000000):
    result += i
end = time.time()   # Return timestamp after operation
print(result)
print(end - start)

56 – Common Methods of Time Related Modules

import time


t = time.localtime()  # Return current time as a tuple
 time.gmtime()  # Return current time in Greenwich Mean Time as a tuple
time.time()  # Commonly used, seconds since 1970-1-1 8:00, timestamp
time.mktime(t)  # Convert tuple time to timestamp
time.sleep(1)
time.asctime()  # If there are parameters, it is in tuple form
time.ctime()  # Return current time, parameter is timestamp, commonly used
time.strftime("%Y-%m-%d") # Commonly used
time.strptime('2018-07-20', "%Y-%m-%d")  # Return tuple time format
time.strftime('%H:%M:%S')


###########################################
from datetime import datetime
from datetime import timedelta
datetime.today()  # Return current time as a datetime object
datetime.now()  # Same as above, can use timezone as parameter
datetime.strptime('2018/06/30', '%Y/%m/%d')  # Return datetime object
dt = datetime.today()
datetime.ctime(dt)
datetime.strftime(dt, "%Y%m%d")


days = timedelta(days=90, hours=3)  # Commonly used
dt2 = dt + days
dt2.year
dt2.month
dt2.day
dt2.hour

57 – Common Methods of os Module

import os


os.getcwd()  # Show current path
os.listdir()  # ls -a
os.listdir('/tmp')  # ls -a /tmp
os.mkdir('/tmp/mydemo')  # mkdir /tmp/mydemo
os.chdir('/tmp/mydemo')  # cd /tmp/mydemo
os.listdir()
os.mknod('test.txt')  # touch test.txt
os.symlink('/etc/hosts', 'zhuji')  # ln -s /etc/hosts zhuji
os.path.isfile('test.txt')  # Check if test.txt is a file
os.path.islink('zhuji')  # Check if zhuji is a symlink
os.path.isdir('/etc')
os.path.exists('/tmp')  # Check if it exists
os.path.basename('/tmp/abc/aaa.txt')
os.path.dirname('/tmp/abc/aaa.txt')
os.path.split('/tmp/abc/aaa.txt')
os.path.join('/home/tom', 'xyz.txt')
os.path.abspath('test.txt')  # Return absolute path of test.txt in current directory

58 – Pickle Storage

import pickle
"""Previous file writing could only write strings. If you want to write any data object (numbers, lists, etc.) to a file,
use pickle to ensure data type remains unchanged when retrieved"""


# shop_list = ["eggs", "apple", "peach"]
# with open('/tmp/shop.data', 'wb') as fobj:
#     pickle.dump(shop_list, fobj)


with open('/tmp/shop.data', 'rb') as fobj:
    mylist = pickle.load(fobj)


print(mylist[0], mylist[1], mylist[2])

59 – Basic Exception Handling

try:   # Put statements that may raise exceptions in try block
    n = int(input("number: "))
    result = 100 / n
    print(result)
except ValueError:
    print('invalid number')
except ZeroDivisionError:
    print('0 not allowed')
except KeyboardInterrupt:
    print('Bye-bye')
except EOFError:
    print('Bye-bye')


print('Done')

60 – Complete Syntax of Exception Handling

try:
    n = int(input("number: "))
    result = 100 / n
except (ValueError, ZeroDivisionError):
    print('invalid number')
except (KeyboardInterrupt, EOFError):
    print('\nBye-bye')
else:
    print(result)  # Executes only if no exceptions occur
finally:
    print('Done')  # Statements that must execute regardless of whether an exception occurs


# Common forms include try-except and try-finally

60 Basic Python Exercises for Beginners (Part Three)

Recently New Courses:Common Data Structures | Excel Basics | Database Operations | Scrapy Framework | Numpy | SQL Structured Query Language | Data Analysis Practice | Object-Oriented Programming | Project Practice | Matplotlib60 Basic Python Exercises for Beginners (Part Three)

Leave a Comment