[worthy of collection] for beginners of python, summarize the common errors at the beginning + ten copies of Python Mini applet (with code)

preface

Do not know what is the best programming language in the world?

But life is short, I use Python!

When writing code, errors are inevitable. The key is how to quickly locate errors and solve bug s. Error tips sometimes do not provide effective information

Information, especially novice programmers, often make some low-level mistakes, such as incorrect indentation, missing quotation marks, incomplete parentheses, etc. here are

Novices often make some code errors. I hope it will be helpful to the students who have just started~

Free source code: WeChat official account Python Gu Gu Muzi

In addition to summarizing the common mistakes of novice programming, some simple novice small projects will be attached for everyone to learn!

text

What are the common mistakes in novice programming?

1. Basic mistakes that novices often make

Missing colon:

a=[1,2,3,4,5,6,7,8,9]
for i in range(0,len(a))
    for j in range(i+1,len(a)):
        if a[j]<a[i]:
            a[i],a[j]=a[j],a[i]
print(a)

Error tip: # syntax error: invalid syntax

2. Incorrect indent

For class definitions, function definitions, process control statements, exception handling statements, etc., the colon at the end of the line and the indentation of the next line represent the next line

The beginning of a code block, and the end of the indentation indicates the end of the code block. Code with the same indentation is considered a code block.

num = 2
if num < 5:
print(num)

‚Äč

Error tip: # indent error: block to be indented

3. The symbol is Chinese

For example, colons and brackets are Chinese symbols.

for i in range(2,102): 
    print(i)

Error message:

4. Wrong data type

Common, such as splicing different types of data.

name = 'xiaoming'
age = 16
print(name+age)

Error message:

5. Misspelled variable or function name

6. Use keywords as file names, class names, function names, or variable names.

Class name, function name or variable name cannot use Python language keywords. The file name cannot conflict with the standard library.

Keywords of Python 3 are:

and, as, assert, break, class, continue, def, del, elif,else, except, False, finally, for, from, global, if, import, in, is, lambda,None, nonlocal, not, or, pass, raise, return, True, try, while, with, yield

Error:

7. "=" is used as "= ="

"=" is an assignment operator and "= =" is an equal to comparison operation, which is used for conditional judgment.

Error:

correct:

8. Missing argument self

Initialization function, instance function and instance variable need the default parameter self.

9. Variable undefined

Error message:

Code checklist:

The following is a simple code checklist. I hope it can be of some help to novices in programming. Just for reference, you can also summarize your own programming error prone points.

Attachment: novice entry applet try to write code?

These examples are very simple and practical, very suitable for beginners to practice. You can also try to construct your own according to the purpose and tips of the project

Build solutions and improve programming level.

1. Stone scissors paper game

Objective: to create a command line game in which players can choose between stones, scissors and cloth, and PK with the computer. If the player wins, he will score

Add until the end of the game, and the final score will be displayed to the player.

Tip: receive the player's selection and compare it with the computer's selection. The choice of the computer is randomly selected from the selection list. If the player gets

Win, add 1 point.

import random
choices = ["Rock", "Paper", "Scissors"]
computer = random.choice(choices)
player = False
cpu_score = 0
player_score = 0
while True:
    player = input("Rock, Paper or  Scissors?").capitalize()
    # Judge the choice of players and computers
    if player == computer:
        print("Tie!")
    elif player == "Rock":
        if computer == "Paper":
            print("You lose!", computer, "covers", player)
            cpu_score+=1
        else:
            print("You win!", player, "smashes", computer)
            player_score+=1
    elif player == "Paper":
        if computer == "Scissors":
            print("You lose!", computer, "cut", player)
            cpu_score+=1
        else:
            print("You win!", player, "covers", computer)
            player_score+=1
    elif player == "Scissors":
        if computer == "Rock":
            print("You lose...", computer, "smashes", player)
            cpu_score+=1
        else:
            print("You win!", player, "cut", computer)
            player_score+=1
    elif player=='E':
        print("Final Scores:")
        print(f"CPU:{cpu_score}")
        print(f"Plaer:{player_score}")
        break
    else:
        print("That's not a valid play. Check your spelling!")
    computer = random.choice(choices)

2. Send mail automatically

Purpose: write a Python script that you can use to send e-mail.

Tip: the email library can be used to send e-mail.

import smtplib 
from email.message import EmailMessage
email = EmailMessage() 
email['from'] = 'xyz name'   
email['to'] = 'xyz id'      
email['subject'] = 'xyz subject'  
email.set_content("Xyz content of email") 
with smtlib.SMTP(host='smtp.gmail.com',port=587)as smtp:     
## sending request to server 
    smtp.ehlo()        
smtp.starttls()    
smtp.login("email_id","Password") 
smtp.send_message(email)   
print("email send")   

3. Hangman games

Objective: to create a simple command line hangman game.

Tip: create a list of password words and select a word at random. Now underline each word with "" to provide the user with the opportunity to guess the word. If the user guesses the word correctly, replace "" with a word.

import time
import random
name = input("What is your name? ")
print ("Hello, " + name, "Time to play hangman!")
time.sleep(1)
print ("Start guessing...\n")
time.sleep(0.5)
## A List Of Secret Words
words = ['python','programming','treasure','creative','medium','horror']
word = random.choice(words)
guesses = ''
turns = 5
while turns > 0:         
    failed = 0             
    for char in word:      
        if char in guesses:    
            print (char,end="")    
        else:
            print ("_",end=""),     
            failed += 1    
    if failed == 0:        
        print ("\nYou won") 
        break              
    guess = input("\nguess a character:") 
    guesses += guess                    
    if guess not in word:  
        turns -= 1        
        print("\nWrong")    
        print("\nYou have", + turns, 'more guesses') 
        if turns == 0:           
            print ("\nYou Lose") 

4. Alarm clock

Purpose: write a Python script to create an alarm clock.

Tip: you can use the date time module to create an alarm clock and the playsound library to play sounds.

from datetime import datetime   
from playsound import playsound
alarm_time = input("Enter the time of alarm to be set:HH:MM:SS\n")
alarm_hour=alarm_time[0:2]
alarm_minute=alarm_time[3:5]
alarm_seconds=alarm_time[6:8]
alarm_period = alarm_time[9:11].upper()
print("Setting up alarm..")
while True:
    now = datetime.now()
    current_hour = now.strftime("%I")
    current_minute = now.strftime("%M")
    current_seconds = now.strftime("%S")
    current_period = now.strftime("%p")
    if(alarm_period==current_period):
        if(alarm_hour==current_hour):
            if(alarm_minute==current_minute):
                if(alarm_seconds==current_seconds):
                    print("Wake Up!")
                    playsound('audio.mp3') ## download the alarm sound from link
                    break

5. Guess the number

Objective: to write a Python game to guess the size.

Tip: you can use random to generate numbers.

# Guessing game man-machine battle
import random
target=random.randint(1,100)
count=0
while True:
      guess=eval(input('Please enter a guess integer (1 to 100)'))
      count+=1
      if guess>target:
            print('Guess big')
      elif guess<target:
            print('Guess it's small')
      else:
            print('You guessed right')
            break
print('The number of guesses in this round is:',count)

6. Mathematical addition and subtraction

Objective: to write a Python game of mathematical calculation.

Tip: you can use random to generate numbers, add and subtract from each other, and you can enter the next level if you answer correctly.

from random import randint
level=0                    #Level 0 start
while level<10:            #When the level is less than level 10
    a=randint(0,100)       #Randomly generate two digit integers
    b=randint(0,100)
    c=input(f"{a}+{b}=")
    c=int(c)
    if c==a+b:             #The calculation result is correct
        level+=1           #Level plus 1
        print(f"That's right! Now the level is{level}Level, you will win when you reach level 10!")
    else:                  #Calculation result error
        level-=1
        print(f"Wrong answer! Now the level is{level},If you reach level 10, you will win! make persistent efforts!")
print(f"Successfully reached level 10! Challenge success! awesome!")
#Subtraction breakthrough game, to transform the above program, you need to pay attention to the comparison of two numbers before subtraction to avoid negative numbers.
from random import randint
level=0                    #Level 0 start
while level<10:            #When the level is less than level 10
    a=randint(0,100)       #Randomly generate two digit integers
    b=randint(0,100)
    if a>=b:
        c=input(f"{a}-{b}=")
        c=int(c)
        if c==a+b:             #The calculation result is correct
            level+=1           #Level plus 1
            print(f"That's right! Now the level is{level}Level, you will win when you reach level 10!")
        else:                  #Calculation result error
            level-=1
            print(f"Wrong answer! Now the level is{level},If you reach level 10, you will win! make persistent efforts!")
print(f"Successfully reached level 10! Challenge success! awesome!")

7. Guess words

Objective: to write a Python game of English word filling.

Tip: you can use random to generate an English word. You can answer it correctly!

import random


# List of stored words (you can fill in the words you need to recite by yourself)
words = ["print", "int", "str", "len", "input", "format", "if","for","def"]

#Initialization information ↓↓↓↓↓↓↓↓
def init():
    # Declare three global variables
    global word
    global tips
    global ranList

    #Randomly get a word in the word list
    word = list(words[random.randint(0, len(words) - 1)])

    #Random number list, which stores random numbers consistent with the length of words (no repetition)
    ranList = random.sample(range(0, len(word)), len(word))

    #Store prompt information
    tips = list()
    #Initialization prompt
    #Store underscores that match the length of the word
    for i in range(len(word)):
        tips.append("_")
    #Random prompt two letters
    tips[ranList[0]] = word[ranList[0]]
    tips[ranList[1]] = word[ranList[1]]

#Function part ↓↓↓↓↓

#Display menu
def showMenu():
    print("Please enter if prompted'?'")
    print("End the game, please enter'quit!'")


#Display prompt information
def showtips():
    for i in tips:
        print(i, end=" ")
    print()


#Need prompt
def needTips(tipsSize):
    #There are at least two unknown letters
    if tipsSize <= len(word)-3:
        tips[ranList[tipsSize]] = word[ranList[tipsSize]]
        tipsSize += 1
        return tipsSize
    else:
        print("There is no prompt!")


#Main operation functions ↓↓↓↓↓↓↓
def run():
    print("------python Keyword version-------")
    init()
    tipsSize = 2
    showMenu()
    
    while True:
        print("Tips:",end="")
        showtips()
        guessWord = input("Guess the word:")
        # ''. Join (word) > converts the contents of the word list into a string
        if guessWord == ''.join(word):
            print("Congratulations, you guessed right! namely%s!"%(''.join(word)))
            print("Guess again")
            init()
            
        elif guessWord == '?':
            tipsSize = needTips(tipsSize)
        elif guessWord == 'quit!':
            break
        else:
            print("Wrong guess!")
            continue
run()

8. Face detection

Objective: to write a Python script that can detect faces in images and save all faces in a folder.

Tip: haar cascade classifier can be used to detect face. The face coordinate information it returns can be saved in a file.

import cv2
# Load the cascade
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Read the input image
img = cv2.imread('images/img0.jpg')
# Convert into grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Detect faces
faces = face_cascade.detectMultiScale(gray, 1.3, 4)
# Draw rectangle around the faces
for (x, y, w, h) in faces:
    cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
    crop_face = img[y:y + h, x:x + w]  
    cv2.imwrite(str(w) + str(h) + '_faces.jpg', crop_face)
# Display the output
cv2.imshow('img', img)
cv2.imshow("imgcropped",crop_face)
cv2.waitKey()

9. Keyboard recorder

Purpose: write a Python script to save all the keys pressed by the user in a text file.

Tip: pynput is a library in Python. It is used to control the movement of keyboard and mouse. It can also be used to make keyboard recorder. Simply read user press

And save a certain number of keys in a text file.

from pynput.keyboard import Key, Controller,Listener
import time
keyboard = Controller()


keys=[]
def on_press(key):
    global keys
    #keys.append(str(key).replace("'",""))
    string = str(key).replace("'","")
    keys.append(string)
    main_string = "".join(keys)
    print(main_string)
    if len(main_string)>15:
      with open('keys.txt', 'a') as f:
          f.write(main_string)   
          keys= []     
def on_release(key):
    if key == Key.esc:
        return False

with listener(on_press=on_press,on_release=on_release) as listener:
    listener.join()

10. Short URL generator

Purpose: write a Python script to shorten a given URL using the API.

from __future__ import with_statement
import contextlib
try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode
try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen
import sys

def make_tiny(url):
    request_url = ('http://tinyurl.com/api-create.php?' + 
    urlencode({'url':url}))
    with contextlib.closing(urlopen(request_url)) as response:
        return response.read().decode('utf-8')

def main():
    for tinyurl in map(make_tiny, sys.argv[1:]):
        print(tinyurl)

if __name__ == '__main__':
    main()
-----------------------------OUTPUT------------------------
python url_shortener.py https://www.wikipedia.org/
https://tinyurl.com/buf3qt3

ending

All right! The above is the content to share with you today. If necessary, you can collect it and read it slowly~

Try typing your own code while watching!

Come and study with me! Pay attention to Xiaobian and update the wonderful content every day~

Tags: Python

Posted on Sun, 07 Nov 2021 19:32:57 -0500 by ticallian