Python from rookie to expert (6): Get user input, functions and comments

Source: Internet
Author: User

1. Get user input

To write a program that has real value, you need to interact with the user. Of course, there are many ways to interact with the user, for example, the GUI (graphical user interface) is a very good way to interact with the user, but we do not discuss the GUI interaction, this section takes a primitive, but very effective way to interact with the user, this is the command line interaction, that is, The user enters the data through the command line, and the program reads the data and does further processing.

To receive input data from the user from the command line, you need to use the input function. The input function receives a parameter of type string that is used as an input hint. The return value of the input function is the value entered by the user on the command line. The input function is returned as a string regardless of what data the user has entered. If you want to get other types of values, such as integers, floating-point numbers, you need to transform them with appropriate functions. For example, a function that converts a string to an integer is an int, and a function that converts a string to a floating-point number is float.

The following example requires the user to enter a name, age, and income on the command line. Where the age is an integer and the income is a floating point number. After entering these 3 values, the 3 values are output in turn in the console. Since both age and income are numeric values, you need to use the int and float functions to convert the return value of the input function to integers and floating-point numbers, respectively, after getting the user input values. If age and income are entered as non-numeric values, an exception is thrown.

name = input("请输入你的名字:")                # 输入姓名,并把输入的结果赋给name变量age = int(input("请输入你的年龄:"))            # 输入年龄,并把输入的结果赋给age变量salary = float(input("请输入你的收入:"))       # 输入收入,并把输入的结果赋给salary变量print("姓名:", name)                      # 输出姓名print("年龄:", age)                       # 输出年龄print("收入:", format(salary, "0.1f"))        # 输出收入

Run the program, enter the name, age, and income separately, and press ENTER to output the contents as shown.

2. Functions

In the previous article, we introduced the use of the Power operator (* *) to calculate the N-squared of a number. In fact, you can use a function to replace this operator, this function is the POW, the function can pass two parameters, if you want to calculate X's Y, then the POW function's 1th parameter should be x, the 2nd parameter should be Y. The POW function returns the result of the calculation. For example, the following code calculates 2 of the 6-time square.

result = pow(2,6)           #  计算结果:64

This line of code, like the above, uses a function called a function call. Functions are equivalent to code snippets that can be reused, and if you use the code in multiple places in your program, you should put this code into a function that allows for code reuse and avoids code redundancy. We can imagine that if you do not use a function, the same code appears in many places in the program, once you want to modify the code, it is a nightmare, you need to change a lot of places.
The Python language provides a number of built-in functions, as well as more functions that are provided through the module, which can be used to a large extent for code reuse, for example, the ABS function for obtaining the absolute value of a number, rounding the round function floating-point numbers, The sin function of the Cmath module is used to calculate the sine of radians.

The following example shows how code reuse is implemented using the Python language built-in functions and the functions provided by the module.

from cmath import sin           # 导入cmath模块中的sin函数print(pow(2,5))             # 运行结果:32print(abs(-12))             # 运行结果:12print(sin(3.14 / 2))            # 运行结果:(0.9999996829318346+0j)print(round(3.6))               # 运行结果:4print(round(3.4))               # 运行结果:3

The program runs as shown in the results.

"Python from rookie to master" began, please pay attention to

3. Notes

Any programming language has the ability to annotate. A comment is a piece of text that describes the role of the Code, the author of the code, or anything else that needs to be described. Annotations are ignored at the time of program compilation, that is, comments are only reflected in the source code and are not annotated in the compiled binaries.

In the Python language, comments are divided into single-line comments and multiline comments. A single-line comment begins with a pound sign (#), and a multiline comment is enclosed in 3 quotation marks (single or double quotes). If you use a single-line comment, everything behind the pound sign is ignored when compiling the program, and if you use multiline comments, the quoted content is ignored when the program is compiled.

When using some Python IDE, the default is to save the source code file in ASCII encoded format, if the source code file contains Chinese, when running the Python program error, you need to annotate the current source code file saved encoding format.

Saving source code files in UTF-8 encoded format

# coding=utf-8

Saving source code files in GBK encoded format

# coding=gbk

It is recommended that the reader use the Utf-8 encoding format to save the source code file, because UTF8 can save not only Chinese, but also other countries ' text, such as Korean and Japanese. So the UTF-8 encoding format is more commonly used.
The following example illustrates the use of single-line comments and multiline annotations in the Python language

# coding=utf-8                          当前Python源代码文件以utf-8编码格式保存"""                                 多行注释(用双引号括起来)李宁地点:earth"""# 用于计算2的4次幂                     单行注释print(2 ** 4)'''                                 多行注释(用单引号括起来)这段代码用于计算一个表达式的值(1 + 2) * 20'''print((1 + 2) * 20)

"Python from rookie to Master" has been published, began to serial, buy send video lessons

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

Tags Index: