程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

The logical judgment of getting started with Python

編輯:Python

Catalog

One 、 Judge (if) sentence

Two 、 Logical operations

3、 ... and 、if Sentence advance

Four 、 Comprehensive application -- Rock-paper-scissors

5、 ... and 、 loop

One 、 Judge (if) sentence

1. Judgment statement drill -- To determine the age

"""
demand
1. Define an integer variable to record age
2. Judge whether it is full 18 year (>=)
3. If full 18 year , Allow to enter the Internet bar hi pi
"""
#1. Define the age variable
age = 18
#2. Judge whether it is full 18 year
# if Statement and indented part of the code is a complete code block
if age >= 18:
#3. If the full 18 year , You can go to the Internet cafe. Hi, pi
print(" You can enter the Internet cafe hi pi ")
#3. reflection !- Whether the conditions are met or not, it will execute
print (" When will this code execute ?")

2. Operator

Compare ( Relationship ) Operator

3.else Deal with situations where conditions are not met

If necessary, when the conditions are not met , Do something , have access to else Deal with situations where conditions are not met

if The conditions to judge :
When conditions are met , What to do
......
else:
When conditions do not hold , What to do
......

Be careful :if and else Statements and their indented parts together are a complete block of code

4. Judgment statement drill -- Judging age improves

"""
demand :
1. Enter the age of the user
2. Judge whether it is full 18 year (>=)
3. If full 18 year , Allow to enter the Internet bar hi pi
4. If not full 18 year , Prompt to go home and do your homework
"""
# 1. Enter the age of the user
age = int(input(" How old is this year ?"))
# 2. Judge whether it is full 18 year
if age >= 18:
print(" You can go to the Internet cafe. Hi, pi ")
else:
print(" You haven't grown up yet , You should go home and do your homework !")

Two 、 Logical operations

In program development , Usually when judging conditions , You will need to judge multiple conditions at the same time , Only multiple conditions are met , To execute subsequent code , At this time, you need to use logical operators .

Logical operators can connect multiple conditions logically , Become more complex conditions .

python The logical operators in include : And and/ or or/ Not not Three .

1.and

 Conditions 1 and Conditions 2

And / also , Two conditions are satisfied at the same time , return True, As long as there is one dissatisfaction , Just go back to False.

  Logic operation drill :

"""
practice 1: Define an integer variable age, Write code to determine whether the age is correct
The required person's age is 0-120 Between
"""
age = int(input(" Please enter age :"))
if age >= 0 and age <= 120:
print(" The right age ")
else:
print(" Age is not right ")
"""
practice 2: Define two integer variables python_score、c_score, Write code to judge performance
Require only one grade >60 Points are qualified
"""
python_score = int(input(" Please enter python achievement :"))
c_score = int(input(" Please enter c achievement :"))
if python_score > 60 or c_score > 60:
print(" Pass the exam ")
else:
print(" I failed in the exam , Continue to work hard ")
"""
practice 3: Define a boolean variable is_employee, Write code to judge whether it is an employee of the company
If not prompted, you are not allowed to enter
"""
# Be careful :python Interpret a non empty string as True, Therefore, the program only returns when entering enter False
is_employee = bool(input(" Please enter your certificate :"))
# If not prompted, you are not allowed to enter
if not is_employee:
print(" Non company personnel , No Admittance ")

3、 ... and 、if Sentence advance

1.elif

In development , Use if You can judge the conditions , Use else You can handle situations where conditions are not tenable , however , If you want to add some more conditions , Different conditions , The code to be executed is also different , You can use elif.

The syntax is as follows :

if Conditions 1:
Conditions 1 Satisfy the executed code
……
elif Conditions 2:
Conditions 2 When satisfied , Executed code
……
elif Conditions 3:
Conditions 3 When satisfied , Executed code
……
else:
When none of the above conditions are met , Executed code
……

Compare the code of logical operators

if Conditions 1 and Conditions 2:
Conditions 1 Satisfy also Conditions 2 Satisfy Executed code
……

Be careful :elif and else And if A combination of , It can't be used alone ; Can be if、elif and else And their indented code , As a complete block of code .

"""
demand :
1. Definition holiday_name String variable records the name of the festival
2. If it's Valentine's day, you should buy roses / See a movie
3. If it's Christmas Eve, you should buy apples / Have a big dinner
4. If it's a birthday, you should buy a cake
5. Other days are festivals every day ......
"""
holiday_name = input(" What festival is today ?")
if holiday_name == " Valentine's Day ":
print(" Buy roses ")
print(" See a movie ")
elif holiday_name == " On Christmas Eve ":
print(" Buy apples ")
print(" Have a big dinner ")
elif holiday_name == " Birthday ":
print(" Buy cake ")
else:
print(" Every day is a festival ......")

2.if Nesting of

elif The application scenario of is : Judge multiple conditions at the same time , All conditions are equal .

In development , Use if Make condition judgment , If you want to add condition judgment in the execution statement where the condition is true , You can use if Nesting of .

if The nested application scenario is : On the premise that the previous conditions are met , Add additional judgment .

if Nested syntax format , It's no different from the previous one except indentation .

The syntax is as follows :


if Conditions 1:
Conditions 1 Satisfy the executed code
……
if Conditions 1 Conditions based on 2:
Conditions 2 When satisfied , Executed code
……
# Conditions 2 Treatment of dissatisfaction
else:
Conditions 2 When not satisfied , Executed code
# Conditions 1 Treatment of dissatisfaction
else:
Conditions 1 When not satisfied , Executed code
……

2.1 if Nested walkthrough for -- Train station security

"""
demand :
1. Define Boolean variables has_ticket Means there is a ticket
2. Defining integer variables knife_length Indicates the length of the knife , Company : centimeter
3. First, check whether there is a ticket , If there is , To allow security checks
4. At security check , The length of the knife needs to be checked , Judge whether it exceeds 20 centimeter
If exceeded 20 centimeter , Tip the length of the knife , It's not allowed to get on the bus
If not more than 20 centimeter , Pass the security check
5. If you don't have a ticket , No entry allowed
"""
# Define Boolean variables has_ticket Indicates whether there is a ticket
has_ticket = True
​
# Define integer variables knife_length Indicates the length of the knife , Company : centimeter
knife_length = 20
​
# First, check whether there is a ticket , If there is , To allow for Security check
if has_ticket:
print(" There are tickets , You can start security ...")
​
# At security check , The length of the knife needs to be checked , Judge whether it exceeds 20 centimeter
# If exceeded 20 centimeter , Tip the length of the knife , It's not allowed to get on the bus
if knife_length >= 20:
print(" It is not allowed to carry %d Cm long knife " % knife_length)
# If not more than 20 centimeter , Pass the security check
else:
print(" Pass the security check , Bon Voyage ……")
​
# If you don't have a ticket , No entry allowed
else:
print(" eldest brother , You have to buy a ticket first ")

Four 、 Comprehensive application -- Rock-paper-scissors

The goal is :1. Strengthen the logical operation of multiple conditions ;2. experience import The import module (“ tool kit ”) Use

1. Rock-paper-scissors - Simple version of

"""
demand :
1. Enter the punch you want from the console -- stone (1)/ scissors (2)/ cloth (3)
2. Let's assume that computers can only make stones , Complete the overall code function
3. Compare the outcome
"""
# Enter the punch you want from the console - stone (1)/ scissors (2)/ cloth (3)
player = int(input(" Please input your fist stone (1)/ scissors (2)/ cloth (3):"))
# The computer Random Punch - Let's assume that computers can only make stones , Complete the overall code function
computer = 1
print(" The fist players choose is %d - The punch of the computer is %d" % (player,computer))
# Players win
if ((player == 1 and computer == 2)
or (player == 2 and computer == 3)
or(player == 3 and computer == 1)):
print(" Oh yeah , The computer is weak !")
# It ends in a draw
elif player == computer:
print(" It's so clever , Another plate ")
# Computers are better than
else:
print(" Not convinced , We fight until dawn !")

2. Rock-paper-scissors - Upgraded version ( random number )

stay pthon in , To use random numbers , First, you need to import the module of random numbers --“ tool kit ”

import random

After importing the module , You can type a... Directly after the module name . Then press Tab key , All functions included in the module will be prompted

random.randint(a,b), return [a,b] Integer between , contain a and b

for example :

import random
random.randint(12,20) # Generated random number n:12 <= n <= 20
random.randint(20,20) # The result will always be 20
random.randint(20,10) # The statement is wrong , The lower limit must be less than the upper limit
"""
demand :
1. Enter the punch you want from the console -- stone (1)/ scissors (2)/ cloth (3)
2. The computer punches at random , Complete the overall code function
3. Compare the outcome
"""
# Import random toolkit
# Be careful : When importing the toolkit , The imported statement should be , Put it at the top of the file
# because , This can facilitate the following code , Whenever necessary , Use the tools in the toolkit
import random
# Enter the punch you want from the console - stone (1)/ scissors (2)/ cloth (3)
player = int(input(" Please input your fist stone (1)/ scissors (2)/ cloth (3):"))
# The computer Random Punch - Let's assume that computers can only make stones , Complete the overall code function
computer = random.randint(1,3)
print(" The fist players choose is %d - The punch of the computer is %d" % (player,computer))
# Players win
if ((player == 1 and computer == 2)
or (player == 2 and computer == 3)
or(player == 3 and computer == 1)):
print(" Oh yeah , The computer is weak !")
# It ends in a draw
elif player == computer:
print(" It's so clever , Another plate ")
# Computers are better than
else:
print(" Not convinced , We fight until dawn !")

5、 ... and 、 loop

1. The three processes of the program

In program development , There are three processes :

The order -- From top to bottom , Sequential execution of code

Branch -- Judge according to the conditions , Decide which branch of code to execute

loop -- Let specific code repeat

2.while Basic use of recycling

The function of loop is to make the specified code execute repeatedly

while The most common application scenario of loop is to let the executed code execute repeatedly for a specified number of times

2.1 while Sentence basic syntax

 Initial condition setting - It is usually a counter executed repeatedly
while Conditions ( Judge Counter Whether to achieve Target times ):
When conditions are met , Do the things 1
When conditions are met , Do the things 2
When conditions are met , Do the things 3
...( Omit )...
Treatment conditions ( Counter + 1)

Be careful :

while Statements and indented parts are a complete block of code

first while loop

"""
demand :
Print 5 All over Hello Python
"""
# 1. Define repetition counter
i = 0
# 2. Use while Judge the condition
while i < 5:
# Code to be executed repeatedly
print("Hello Python")
# Processing calculator i
i = i + 1
print(" At the end of the cycle i = %d" % i)

Be careful : At the end of the cycle , The value of the previously defined counter condition still exists

Dead cycle

Because of the programmers , Forget to modify the judgment conditions of the loop inside the loop , Causes the loop to continue to execute , The program cannot be terminated ! 

2.2 Assignment operator

stay python in , Use = You can assign values to variables

In arithmetic operations , In order to simplify the code writing ,python A series of assignment operators corresponding to arithmetic operators are also provided

Be careful : You cannot use spaces between assignment operators

2.3 python Count method in

There are two common counting methods , They can be called :

Natural counting ( from 1 Start )-- More in line with human habits

Program counting ( from 0 Start )-- Almost all programming languages choose from 0 Start counting

2.4 Cycle calculation

In program development , There is often a need to use circular recalculation

Meet this demand , Sure :

1. stay while Define a variable above , Used to store the final calculation

2. Inside the circulatory body , Each cycle uses the latest calculation results , Update previously defined variables

# demand :
# Calculation 0~100 The cumulative sum of all the numbers between
# 0. Variables that define the final result
result = 0
# 1. Define the number of times an integer's variable records a loop
i = 0
# 2. Start the cycle
while i <= 100:
# Every cycle , Are so result This variable and i This counter adds up
result += i
# Processing counter
i += 1
print("0~100 The sum of the numbers between :%d" % result)
# Demand advanced
# Calculation 0~100 The cumulative sum of all even numbers between
"""
Development steps :
1. Write a cycle to confirm the number to be calculated
2. Add result variable , Process the calculation results inside the loop
"""
# 0. final result
result = 0
# 1. Counter
i = 0
# 2. Start the cycle
while i <= 100:
# Determine whether the counter is even
if i % 2 == 0:
# i When it's even , Are so result This variable and i This counter adds up
result += i
# Processing counter
i += 1
print("0~100 The sum of even numbers between :%d" % result)

3.break and continue

break and continue It's a keyword that's specifically used in loops

break When a certain condition is met , Exit loop , No more subsequent code repeats

continue When a certain condition is met , Do not execute subsequent duplicate code

break and continue Only valid for the current loop

i = 0
while i < 10:
if i == 3:
break
print(i)
i += 1
print("over")
i = 0
while i < 10:
if i == 3:
# Before using keywords , It is necessary to confirm whether the count of the loop is modified , Otherwise, it may lead to an endless cycle
i += 1
continue
print(i)
i += 1

 4.while A nested loop

4.1 A nested loop

while Nesting is :while There are also while

while Conditions 1:
When conditions are met , Do the things 1
When conditions are met , Do the things 2
When conditions are met , Do the things 3
......
while Conditions 2:
When conditions are met , Do the things 1
When conditions are met , Do the things 2
When conditions are met , Do the things 3
......
Treatment conditions 2
Treatment conditions 1

 4.2 Loop nesting drill -- multiplication table

The first 1 Step : Use nesting to print little stars

# Output five lines continuously in the console *, The number of asterisks in each row increases in turn
# *
# **
# ***
# ****
# *****
# 1. Define a counter variable , From numbers 1 Start
row = 1
# 2. Start the cycle
while row <= 5:
print("*" * row)
row += 1

The first 2 Step : Use loop nesting to print little stars

By default ,print After the function outputs the contents , Will automatically add a new line at the end of the content

If you don't want to add line breaks at the end , Can be in print The output of the function is followed by ,end=""

among "" You can specify print After the function outputs the contents , Continue what you want to show

The syntax is as follows :

# After outputting content to the console , Don't wrap
print("*", end="")
# A simple line break
print("")

end="" After the output to the console , Don't wrap

# hypothesis python No string provided * operation ( Multiplication operation ) String concatenation
# demand : Output five lines continuously in the console *, The number of asterisks in each row increases in turn
# *
# **
# ***
# ****
# *****
row = 1
while row <= 5:
# hypothesis python No strings provided * operation
# Inside the loop , Add another cycle , Print stars on each line
col = 1
while col <= row:
print("*",end="")
col += 1
# After each line of asterisk output is completed , Add another line feed
print("")
row += 1

The third step : multiplication table

# demand : Output the multiplication table
"""
1. Print 9 OK, little star
2. Replace the stars with each multiplication
"""
row = 1
while row <= 9:
col = 1
while col <= row:
# print("*", end="")
print("%d * %d = %2d "% (col,row,col * row), end=" ")
col += 1
print("")
row += 1

  Escape character in string

\t  Output a tab at the console , Helps maintain vertical alignment when outputting text

\n Output a newline character on the console

The tab function aligns text vertically in columns without using tables

# \t  Output a tab at the console , Helps maintain vertical alignment when outputting text
row = 1
while row <= 9:
col = 1
while col <= row:
# print("*", end="")
print("%d * %d = %d "% (col,row,col * row), end="\t")
col += 1
print("")
row += 1

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved