60 Basic Python Exercises for Beginners (Part 2)

60 Basic Python Exercises for Beginners (Part 2)Click the image below to search for the secret code[Interview Guide], claim nowinterview questions + resume template.

60 Basic Python Exercises for Beginners (Part 2)

21-while-break

break ends the loop, and the code inside the loop will not execute after break.

while True:
    yn = input('Continue(y/n): ')
    if yn in ['n', 'N']:
        break
    print('running...')

22-while-continue

Calculate the sum of even numbers within 100.

continue skips the remaining part of the current loop and goes back to the loop condition.

sum100 = 0
counter = 0


while counter < 100:
    counter += 1
    # if counter % 2:
    if counter % 2 == 1:
        continue
    sum100 += counter


print(sum100)

23-for Loop Traversal of Data Objects

astr = 'hello'
alist = [10, 20, 30]
atuple = ('bob', 'tom', 'alice')
adict = {'name': 'john', 'age': 23}


for ch in astr:
    print(ch)


for i in alist:
    print(i)


for name in atuple:
    print(name)


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

24-range Usage and Number Accumulation

# range(10)  # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> list(range(10))
# range(6, 11)  # [6, 7, 8, 9, 10]
# range(1, 10, 2)  # [1, 3, 5, 7, 9]
# range(10, 0, -1)  # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
sum100 = 0


for i in range(1, 101):
    sum100 += i


print(sum100)

25-List Implementation of Fibonacci Sequence

Start with two numbers in the list, and each subsequent number is the sum of the previous two.

fib = [0, 1]


for i in range(8):
    fib.append(fib[-1] + fib[-2])


print(fib)

26-Multiplication Table

for i in range(1, 10):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()


# i=1 ->j: [1]
# i=2 ->j: [1,2]
# i=3 ->j: [1,2,3]
# Specified by the user up to which number to multiply
n = int(input('number: '))


for i in range(1, n + 1):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()

27-Step-by-Step List Comprehension

# Store the result of 10+5 in a list
[10 + 5]
# The expression 10+5 is calculated 10 times
[10 + 5 for i in range(10)]
# 10+i where i comes from the loop
[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]
# Filter with if, only those that meet the if condition participate in the calculation of 10+i
[10 + i for i in range(1, 11) if i % 2 == 1]
[10 + i for i in range(1, 11) if i % 2]
# Generate a list of IP addresses
['192.168.1.%s' % i for i in range(1, 255)]

28-Best of Three Rock-Paper-Scissors

import random


all_choices = ['Rock', 'Scissors', 'Paper']
win_list = [['Rock', 'Scissors'], ['Scissors', 'Paper'], ['Paper', 'Rock']]
prompt = """(0) Rock
(1) Scissors
(2) Paper
Please choose (0/1/2): """
cwin = 0
pwin = 0


while cwin < 2 and pwin < 2:
    computer = random.choice(all_choices)
    ind = int(input(prompt))
    player = all_choices[ind]


    print("Your choice: %s, Computer's choice: %s" % (player, computer))
    if player == computer:
        print('\033[32;1m Draw, \033[0m')
    elif [player, computer] in win_list:
        pwin += 1
        print('\033[31;1mYou WIN!!!\033[0m')
    else:
        cwin += 1
        print('\033[31;1mYou LOSE!!!\033[0m')

29-Basic File Object Operations

# The three steps of file operations: open, read/write, close
# cp /etc/passwd /tmp
f = open('/tmp/passwd')  # Open text file in read mode by default
data = f.read()  # read() reads all contents
print(data)
data = f.read()  # As reading and writing proceed, the file pointer moves forward.
# Because the first f.read() has already moved the file pointer to the end, reading again yields no data
# So data is an empty string
f.close()


f = open('/tmp/passwd')
data = f.read(4)  # Read 4 bytes
f.readline()  # Read until newline, ends at n
f.readlines()  # Read each line of data into a list
f.close()


################################
f = open('/tmp/passwd')
for line in f:
    print(line, end='')
f.close()


##############################
f = open('image_path', 'rb')  # Open non-text file with b parameter
f.read(4096)
f.close()


##################################
f = open('/tmp/myfile', 'w')  # Open file in 'w' mode, creates if not exist
f.write('hello world!\n')
f.flush()  # Immediately sync cached data to disk
f.writelines(['2nd line.\n', 'new line.\n'])
f.close()  # Save data to disk when closing the file


##############################
with open('/tmp/passwd') as f:
    print(f.readline())


#########################
f = open('/tmp/passwd')
f.tell()  # Check the position of the file pointer
f.readline()
f.tell()
f.seek(0, 0)  # The first number is the offset, the 2nd is the relative position.
              # Relative position 0 means start, 1 means current, 2 means end
f.tell()
f.close()

30-Copying Files

Copying files means opening the source file in r mode, opening the target file in w mode, reading data from the source file, and writing it to the target file.

The following is a [not recommended] method, but it works:

f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')


data = f1.read()
f2.write(data)


f1.close()
f2.close()

31-Copying Files

Read 4K each time, until finished:

src_fname = '/bin/ls'
dst_fname = '/root/ls'


src_fobj = open(src_fname, 'rb')
dst_fobj = open(dst_fname, 'wb')


while True:
    data = src_fobj.read(4096)  # Read 4K each time
    if not data:
        break
    dst_fobj.write(data)


src_fobj.close()
dst_fobj.close()

32-Position Parameters

Note: The numbers in position parameters are in string form

import sys


print(sys.argv)  # sys.argv is the argv list in the sys module


# python3 position_args.py
# python3 position_args.py 10
# python3 position_args.py 10 bob

33-Function Application – Fibonacci Sequence

def gen_fib(l):
    fib = [0, 1]


    for i in range(l - len(fib)):
        fib.append(fib[-1] + fib[-2])


    return fib  # Return list, not variable fib


a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n))  # n is assigned to parameter, not passed as variable n

34-Function – Copy Files

import sys


def copy(src_fname, dst_fname):
    src_fobj = open(src_fname, 'rb')
    dst_fobj = open(dst_fname, 'wb')


    while True:
        data = src_fobj.read(4096)
        if not data:
            break
        dst_fobj.write(data)


    src_fobj.close()
dst_fobj.close()


copy(sys.argv[1], sys.argv[2])
# Execution method
# cp_func.py /etc/hosts /tmp/zhuji.txt

35-Function – Multiplication Table

def mtable(n):
    for i in range(1, n + 1):
        for j in range(1, i + 1):
            print('%s*%s=%s' % (j, i, i * j), end=' ')
        print()


mtable(6)
mtable(9)

36-Module Basics

Every file with a .py extension is a module.

star.py:
hi = 'hello world!'


def pstar(n=50):
    print('*' * n)


if __name__ == '__main__':
    pstar()
    pstar(30)

To call the star module in call_star.py:

import star


print(star.hi)
star.pstar()
star.pstar(30)

37-Generate Password/Verification Code

This file is named: randpass.py

Idea:

1. Set a base string for randomly selecting characters, using uppercase and lowercase letters plus digits in this example

2. Loop n times, randomly select a character each time

3. Concatenate the characters and save to the variable result

from random import choice
import string


all_chs = string.ascii_letters + string.digits  # Uppercase and lowercase letters plus digits

def gen_pass(n=8):
    result = ''


    for i in range(n):
        ch = choice(all_chs)
        result += ch


    return result


if __name__ == '__main__':
    print(gen_pass())
    print(gen_pass(4))
    print(gen_pass(10))

38-Sequence Object Methods

from random import randint


alist = list()  # []
list('hello')  # ['h', 'e', 'l', 'l', 'o']
list((10, 20, 30))  # [10, 20, 30]  Convert tuple to list
astr = str()  # ''
str(10)  # '10'
str(['h', 'e', 'l', 'l', 'o'])  # Convert list to string
atuple = tuple()  # ()
tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
num_list = [randint(1, 100) for i in range(10)]
max(num_list)
min(num_list)

39-Sequence Object Methods 2

alist = [10, 'john']
# list(enumerate(alist))  # [(0, 10), (1, 'john')]
# a, b = 0, 10   # a->0  ->10


for ind in range(len(alist)):
    print('%s: %s' % (ind, alist[ind]))


for item in enumerate(alist):
    print('%s: %s' % (item[0], item[1]))


for ind, val in enumerate(alist):
    print('%s: %s' % (ind, val))


atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)
sorted(atuple)
sorted('hello')
for i in reversed(atuple):
    print(i, end=',')

40-String Methods

py_str = 'hello world!'
py_str.capitalize()
py_str.title()
py_str.center(50)
py_str.center(50, '#')
py_str.ljust(50, '*')
py_str.rjust(50, '*')
py_str.count('l')  # Count occurrences of l
py_str.count('lo')
py_str.endswith('!')  # Ends with !?
py_str.endswith('d!')
py_str.startswith('a')  # Starts with a?
py_str.islower()  # Are all letters lowercase? Ignore other characters
py_str.isupper()  # Are all letters uppercase? Ignore other characters
'Hao123'.isdigit()  # Are all characters digits?
'Hao123'.isalnum()  # Are all characters alphanumeric?
'  hello\t    '.strip()  # Remove whitespace from both ends, commonly used
'  hello\t    '.lstrip()
'  hello\t    '.rstrip()
'how are you?'.split()
'hello.tar.gz'.split('.')

60 Basic Python Exercises for Beginners (Part 2)

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

Leave a Comment