Location>code7788 >text

Getting Started with Python: A+B Problems

Popularity:468 ℃/2024-10-16 17:21:08

1. A + B Question I

preamble

This, the first of the course, focuses on literacy in basic Python syntax, and you will learn the following in this lesson:

importation

The task of this question is very simple, just calculate the sum of two numbers, but before calculating, one of the first questions we need to clarify is how to input these two data into the computer and read by the program?

Input is, of course, done using an input device such as a keyboard, which means that there is a program that reads both of our inputs, and in Python, this fetching of input is done by the built-in functioninput()to finish.

variant

After solving the input problem, we still have another problem to solve, that is: how does the system recognize and identify the numbers we input? For example, if we want to enter two numbers 100 and 100, and the computer system uses 100 to identify 100, how should the other 100 be identified?

So it's necessary to use something within the system to refer to and identify the input, such asx = 100、 y = 100, with x referring to 100 and y referring to another 100, where thex, yKnown as variables in math, they are also called variables in programming to refer to content.

However, in math there are integers, decimals, in addition, we also often enter a piece of text data, that the computer in the storage time should also know what type of number or text we enter x, this is what we want to talk aboutdata type

data type

There are some common basic data types in Python: here we'll start with a brief introduction, you just need to know what they mean for now.

  • Number Type: Used to represent numbers, including integer and floating point number types.
    • integer typeint: That is, we commonly use integer values, such as - 1, 0, 1 is an integer.
    • Floating-point number typefloat: Used to represent values with a decimal point, e.g. 3.14, 2.0.
  • boolean typebool: Used to denote the logical values True and False, i.e. 0 and 1 in the computer world, True means True and False means False, whileTrueis also equal to 1.Falseis also equal to 0, andTruecap (a poem)FalseCan participate in arithmetic with numeric types.
  • string typestring: Using single quotes for strings in Python''Or double quotes.""Expanded to represent a piece of text data, such as a string"hello""Hello".

variable assignment

However, having a variable without a value is not good enough. Variables in Python do not need to be declared in advance, but they must be assigned a value before they can be used, and a variable is only created if it is assigned a value; in math, we do this with the equals sign=to determine if two numbers are equal, such as1 = 3, 2 = 5to determine, but in programming, a=Often it means assigning the value on the right to the value on the left, for examplei = 3, that is, the value 3 is assigned to the left-hand side of the i

The process of assigning values is an associative process, like "connecting the dots", linking "values" and "variables" together.

name = "Zhangsan" # means assign the right value "Zhangsan" to the left variable name.
age = 22 # Assigns the right-hand value 22 to the left-hand variable age.
height = 1.68 # Defines a floating point number to be assigned to the left-hand side of the variable height.

And Python is a dynamically typed language, which means that the data types of variables can change with the values assigned to them.

x = 22 # x is an integer

x = "Zhang San" # x is now a string

In the code above, thex is first assigned to the integer 22 and then to the string "ZhangSan", the variablex The data type of the

After learning about variable assignment andinput()After the concept of

# input() takes the input and associates it with the variable user_input
user_input = input()

The above code then means that the data entered by the user is stored into the variableuser_input For example, if the user enters a string of text "hello world" (ending with the Enter key), the contents of the text string are stored in theuser_inputIn this case, it is important to note thatinputreceives always a string, even if you enter a number, for example if you enter 123, but theuser_inputReceived"123"String 123, but that's okay, you can use the type conversionint()Convert it to an integer.

# int() converts the string received by input() to an integer
user_input = int(input()) # input integer 3, input() receives "3", int("3") converts to integer 3

Additionally, you can also find out more about theinputIt's populated with information that serves as a prompt for user input:

user_input = input("Please enter some text: ")

The above code will display "Please enter some text:" in the terminal and wait for the user's input. After that the input will be stored in theuser_input in the variable.

exports

In Python, the output is also very simple, just use theprint(), in()The content to be output is filled inside and the content is displayed on the screen (terminal).

# Output 1
print(1)
# Instead of displaying 1 + 2, Python automatically calculates the result before displaying it, displaying it as 3
print(1 + 2)

print()Functions can be combined withinput()functions are combined to realize the interaction with the user.

name = input("Please enter your name: ") # prompt the user for a name
print(name) # outputs what you typed on the screen

Calculate a + b

Suppose we have only one set of data, i.e., you only need to enter an a and a b, with a space separating a and b. How do you calculate the value of these two numbers?

The first thing you should do is to use theinput()Receive a line of input from the user

data = input()

no more thaninput()Encountering a space does not stop receiving input, and the input is a string.

Suppose you enter 3 and 4, i.e. the following input.

3 4

At this point, the data data is accepted as a string"3 4"

Then we need to figure out how to split 3 and 4, and it's a good thing that strings provide a way to do that.splitFor our use

# input() means input content, input().split() means split input content based on space.
data = input().split()

splitmethod is used to split a string into multiple smaller substrings and return a list (we'll talk about this data type in the next lesson) containing the split substrings. By default, thesplit() method uses the space character as a separator to break the string into words. You can also specify a custom separator as a parameter.

persons = "Mike Jerry Tom"
result = () # Split the string into smaller substrings using the default separator (spaces)
print(result) # Output: ['Mike', 'Jerry', 'Tom']

persons = "Mike,Jerry,Tom"
result = (",") # Split the string into smaller substrings using ",".
print(result) # Output: ['Mike', 'Jerry', 'Tom']

image-20231106165130063

In conclusion.split()is to split a long string of characters into smaller strings by using the splitter symbol, in the case of the"3 4"Splitting by spaces will split into["3", "4"]

As we mentioned before, it is possible to convert data types with theint()If you convert "3" to the integer 3, then the next question is how do you get "3" and "4"?

List by Index[]is accessed and indexed from 0, with index 0 denoting the first element and index 1 denoting the second element, i.e., through thedata[0]cap (a poem)data[1]The first element "3" and the second element "4" can be obtained separately.

# data[0] represents the first element, int() performs data type conversion to integer type.
# data[1] is the second element, int() is used to convert to an integer.
# res = int(data[0]) + int(data[1]) means two data to be added, and finally assigned to res
res = int(data[0]) + int(data[1])

replacingresThe complete code is as follows

data = input().split() # Split the input string based on spaces to get a list of data.
res = int(data[0])+int(data[1]) # Once you have the elements, convert them, add them up, and assign them to res.
print(res)

Loop Input and Output

Although the above code completes the input, calculation and output of A+B, it can not meet the requirements of the calculation of multiple sets of data, which requires learning a new concept of "loop".

while A loop is a control structure that repeats the execution of a block of code when certain conditions are met, and you can do this by setting thewhileThe conditional part of the loop is true (boolean)True), so that the loop will continue until you use thebreakstatement to terminate the loop.

Note that Python is very sensitive to program indentation, and uses indentation to indicate the scope of a block of code rather than curly braces{}, extra care must be taken to ensure that all lines of code in the same block have the same level of indentation.

while True:
    data = input().split()
    res = int(data[0])+int(data[1])
    print(res)

existwhile TrueThe three lines of code that perform input, computation, and output run continuously under the control of the program; you enter a line of data, and the program processes a line of data, but the input of data doesn't go on forever, and when the input ends, the loop should terminate as well.

This can be done using thetry block (computing)to carry out the process.tryThe code in is attempted to be executed, and if no error occurs, it is executed normally. After the user stops typing, the input is not correctly split into two integers, or other possible errors occur, which will cause a program exception, which is caused by theexceptCatch exceptions and execute exception handling code

while True:
    try.
    # Try to execute the program here
    except: # Catch the exception and execute the exception code.
    # Catch the exception and execute the exception code
        break

Here.breakis a statement used inside a loop to terminate the current loop and continue executing the code after the loop, usually used to end the loop early if a condition in the loop is met, here we usebreakJumps out of the loop and ends the execution of the program.

So the complete code for this question is as follows:

💡 Warm Tip:Be sure to knock by hand, don't copy and paste, only practice will deepen the impression

# while True indicates a loop
while True.
    # Try to execute the program here and execute the program in except when an exception is encountered.
    try.
        # Split the input string into a list of characters
        data = input().split()
        # Get the first and second elements and convert them to int and add them together
        res = int(data[0])+int(data[1])
        # Print the result, res
        print(res)
    except.
        # Exit the loop if an exception is encountered
        break

Extension: Multiple Assignment

apart froma = 10In addition to this type of assignment, Python also allows multiple variables to be assigned at the same time, which is called multiple assignment, and there are several of them.

# 1. Multiple variables are assigned the same value at the same time
a = b = c = 42 # Variables a, b and c are all assigned the same value

# 2. Multiple variables are assigned different values at the same time.
x, y, z = 1, 2, 3 # Variable x is assigned the value 1, variable y is assigned the value 2, variable z is assigned the value 3

# 3. Multiple assignments can also be used to get the values in a list.
a, b = [1, 2] # Assign the elements of the list to a and b in order, with a having the value 1 and b having the value 2.

Extension: Module

Although we only write a few lines of code now, but later we will face thousands or even tens of thousands of lines of code, in order to facilitate the organization and management of these codes to be divided into different modules, just like the books in the library to be divided into different classes. In Python engineering development, we will create manypythonfile with the suffix.py(like a single word file), thus breaking down a complete program into smaller modules (apython(a file is a module), a complete program is built by combining and reusing modules.

Moreover, Python has a number of built-in modules, such asmath、sysetc. These modules provide a number of built-in functions for ease of use, such asmathThe module then provides many useful math operations.

Note that before using the module, use theimportstatement to import:

General.importstatements are written uniformly at the beginning of the program, and each module has an internal__name__attribute, through which you can get the name of the module.

# import math module
import math
# The syntax for using a variable or function defined in a module is: module. Variables/Functions
print((25)) # Use the sqrt function in the math module, which means square root.

Or you can also use thefromstatements to import specific functions, variables in the module and then use them directly.

# Import sqrt from math module
from math import sqrt
print(sqrt(25)) # Use the sqrt function directly, without math in front of it.

Extension: Master Module

In Python, the main module is the entry point for executing a Python program, and a program will only have one main module, whose name is__main__It is written in a fixed format:

Here's just a short introduction to the main module, for now all you need to know is theThe main module is the entry point to the programAnd just know how to write the main module.

# Indicates that this is the main module
if __name__ == "__main__".
    # Main module program

summarize

This article quoted part of the blogger's "Code Randomizer" article, you can pay attention to the attention of the original author:Code Randomizer
As a beginner in the Python language, in this lesson we used a Python program to solve the problem of theA+Bquestions, in this process we understand the basic concepts of input, output, variables, data types, loops, multiple assignments, modules, etc., and can use loops to control the input and output of multiple sets of data, which is a good place to start. in the next lesson, we will do a re-interpretation of loops, and I believe that some of the questions you have about this lesson will be answered in the next section.