Python Basics 01-Environment Setup and Input and Output

Zero, article directory

Python Basics 01-Environment Setup and Input and Output

1. Python overview

(1) Why learn Python
  • Technology Trend: Python has its own star attributes, and its popularity ranks among the top three programming languages.

image-20231117120901228

  • Simple and easy to learn: less development code, precise expression of demand logic; 33 keywords, 7 basic data types; simple grammar rules, close to natural language

image-20231117121011608

  • Wide application: Python language involves more than 70% of the technical fields in the IT industry

image-20231117121039299

(2) The birth of Python language
  • In 1989, in order to pass the Christmas holiday, Uncle Turtle (Guido Van Rossum) started writing a compiler for the Python language
  • In 1991, the first Python compiler was born
  • The name Python comes from Uncle Turtle’s beloved TV series Monty Python’s Flying Circus (Monty Python’s Flying Circus)

image-20231117121208512

(3) Advantages and disadvantages of Python
  • Simple: Python is a language that represents the idea of ​​simplicity. Reading a good Python program feels like reading English, and this code-based nature of Python is one of its greatest strengths. It allows you to focus on solving problems rather than figuring out the language itself.
  • Easy to learn: As you are about to see, Python is extremely easy to get started. As mentioned earlier, Python has an extremely simple syntax.
  • Free and open source: Python is open source. Simply put, you can freely read its source code and make changes to it. This is one of the reasons why Python is so good. One - it was created and constantly improved by a group of people who want to see a better Python.
  • Portability: Due to its open source nature, Python has been ported to many platforms (with modifications to enable it to work on different platforms). If you are careful to avoid using system-dependent features, then all of your Python programs will run without modification on any of the platforms listed below.
  • Rich library: The Python standard library is indeed huge. It can help you with various tasks, including regular expressions, document generation, unit testing, threads, databases, web browsers, CGI, FTP, email, XML, XML-RPC, HTML, WAV files, password systems, GUI (Graphical User Interface), Tk and other system-related operations. Remember, all of these features are available as long as Python is installed. This is called Python's "full-featured" philosophy.
  • **Disadvantages:** The Python language is very complete and has no obvious shortcomings and shortcomings. The only disadvantage is slow execution efficiency. This is common to interpreted languages. At the same time, this shortcoming will also be affected by the increasingly powerful performance of computers. compensated.

2. Python parser

(1) Python Analyzer action
  • The role of the Python interpreter: running Python files

image-20231117134118293

(2) Python Analyzer type
  • CPython, an interpreter developed in C language [official], is a widely used interpreter.
  • IPython, an interactive interpreter based on CPython.
  • Other interpreters
    • PyPy, an interpreter developed based on the Python language.
    • JPython, an interpreter running on the Java platform, directly compiles Python code into Java bytecode for execution.
    • IronPython, a Python interpreter running on the Microsoft .Net platform, can directly compile Python code into .Net bytecode.
(3) Download the Python parser

image-20231117135445457

(4) Install Python parser
  • Double-click the executable file - [Check to add environment variables] - [Install Now], and follow the prompts.

image-20231117141038053

3. PyCharm development tool

(1)PyCharmeffect
  • PyCharm is a Python IDE (Integrated Development Environment) with a set of tools that can help users improve their efficiency when developing in the Python language.

  • The internally integrated functions are as follows:

    • Project management

    • Smart reminder

    • syntax highlighting

    • code jump

    • debug code

    • Interpreted code (interpreter)

    • Frameworks and libraries

(2)PyCharmclassification
  • PyCharm is divided into professional edition (professional) and community edition (community). This article mainly uses the community edition as the basis for operation and explanation.
(3)DownloadPyCharmDownload

image-20231117142438168

(4) Install PyCharm software
  • Double-click the installation package - [Select installation location] - [Add environment variables and shortcuts, associated file extensions] --[Install] --[Finish]

image-20231117142917665

(5)PyCharmBasic usage
  • Create a new project: Open PyCharm – [New Project] – Select the item root directory and interpreter version – [Create]

image-20231117145835350

image-20231117150502047

  • Create a new file and write code: Right-click in the project root directory or anywhere inside the root directory – [New] – [Python File] – Enter the file name – [OK]. If the file is to be uploaded to the server in the future, then the file name Remember not to use Chinese.

image-20231117150917154

image-20231117151006958

  • Write Python code: Double-click to open the file and write the simplest Python code

image-20231117151146610

  • Run the file: Select the file – right click – Run, or within the file – right click – Run

image-20231117151252197

image-20231117151439166

(6)PyCharmBasic configuration
  • [File] – [Settings]–[Appearance & Behavior]

  • [Appearance & Behavior] – [Appearance]: Theme: Modify the theme, Use custom font: Modify the theme font, Size: Modify the theme font size

image-20231117193838487

  • [Editor] – [Font]: Font: modify the font, Size: modify the font size, Line Spacing: modify the line spacing

image-20231117195125110

  • [Project: project name] – [Project Interpreter] – select the target interpreter

image-20231117195742659

  • [File] – [Open]: Open the project, browse and select the root directory of the target project, and select the method to open the project. There are three ways to open the project.
    • This Window: Overwrite the current project to open the target project
    • New Window: Open PyCharm twice in a new window, each PyCharm is responsible for one project
    • Attach: Merge two projects together and put them in the same window

image-20231117202510595

  • [File] – [Close Project]: Close the project

4. Python annotations

(1) Why comments are needed
  • When we write a Python program, in order to improve the readability of the program, it is strongly recommended that you add comment information to the core code.
(2) Comparison of commented code and non-commented code
  • Commented code makes it easier for the program to read.

image-20231117203751047

(3) Classification and syntax of Python comments
  • Single-line comments: Single-line comments can only comment on one line of content.
# 注释内容
# 在Python中可以使用(# 注释内容)来表示单行注释
print('hello world')  # 单行注释,主要用于表示代码的输出结果 => hello world
  • Multi-line comments: Multi-line comments can comment on multiple lines of content and are often used for code block comments.
"""
	第一行注释
	第二行注释
	第三行注释
"""

'''
	第一行注释
	第二行注释
	第三行注释
'''
'''
注释的内容不止1行,就可以使用多行注释!
注意:这里既可以使用三个单引号也可以使用三个双引号,在注释中,两者效果完全相同!
'''

"""
多行注释在实际工作中的应用场景:
① 用于编写程序的设计逻辑
以下程序一共分为三个步骤
第一步:定义一个计数器
第二步:编写循环条件
第三步:在循环体内部更新计数器值

② 多行注释还可以用于函数的说明文档
sum_num()函数,主要用于求两个数的和
参数说明:
num1代表第一个参数,整数类型
num2代表第二个参数,整数类型
返回值说明:
当函数执行完毕后,其返回两个数的和!
"""
def sum_num(num1, num2):
    return num1 + num2
(4) PyCharm comment shortcut keys
  • You can directly use Ctrl + / to quickly generate code comments

5. Python variables

(1) What are variables
  • Variables are containers for storing data
  • The data stored in variables is temporary
  • Variables are quantities that can change while the program is running.
(2) The role of variables
  • Implement storage through variables to facilitate subsequent operations

image-20231117211322363

(3) Definition of variables
  • Basic syntax: variable name = variable value
  • Note: There must be a space on both sides of the equal sign. The variable name can be customized, but it must meet the naming rules of Identifier.
# 定义一个变量,c1变量,用于保存数据"可乐"
c1 = "可乐"
c2 = "牛奶"

# 打印输出变量
print(c1)
print(c2)
(4) Identifier naming rules
  • The identifier naming rule is a naming convention when defining variable names in Python.

    • Composed of numbers, letters, and underscores

    • Cannot start with a number

    • Strictly distinguish between upper and lower cases

    • You cannot use built-in keywords as variable names

  • Python built-in keywords are as follows

image-20231117211756137

# help('keywords')
# 定义几个变量,用于保存一个人的信息
name = '刘国晓'  # ''/""引号引起来的内容都称之为“字符串”
age = 23
address = '广州市天河区'

print(name)
print(age)
print(address)

# 在Python代码中,print()也可以同时输出多个变量
print(name, age, address)
(5) Naming habits
  • Variable naming must be clearly understood.
  • Big camel case: The first letter of each word is capitalized, for example: MyName.
  • Small camel case: The first letter of the second (inclusive) word after that is capitalized, for example: myName .
  • Underscore: For example: my_name .
(6) Use of variables
  • In Python, variables must be defined before they are used.
my_name ='YYY'
print(my_name)

schoolName ='XXX'
print(schoolName)
(7) Data type of variable
  • In Python, in order to meet different business needs, we also divide data into different types

image-20231117212851550

  • Definition and judgment of different types of variables, judgment method => type()
a = 1
print(type(a)) # <class 'int'> -- 整型
b = 1.1
print(type(b)) # <class 'float'> -- 浮点型
c = True
print(type(c)) # <class 'bool'> -- 布尔型
d = '12345'
print(type(d)) # <class 'str'> -- 字符串
e = [10, 20, 30]
print(type(e)) # <class 'list'> -- 列表
f = (10, 20, 30)
print(type(f)) # <class 'tuple'> -- 元组
h = {
    
    10, 20, 30}
print(type(h)) # <class 'set'> -- 集合
g = {
    
    'name': 'TOM','age': 20}
print(type(g)) # <class 'dict'> -- 字典

6. Bugs in Python

(1) What is a Bug?
  • The so-called bug is an error in the program. If there are errors in the program, we programmers need to troubleshoot and correct the errors in time.

image-20231117214425947

(2) Debug tools
  • The Debug tool is a tool integrated in PyCharm IDE specifically for debugging programs. Here programmers can view the execution details and processes of the program, so that we can quickly find bugs in the program!
  • Use the debug tool in two steps: ① Break point ② Debug
(3) Interruption point
  • Breakpoint location: The breakpoint should be located on the first line of the Python code segment to be debugged.
  • How to set a break point: Click in the blank space to the right of the line number of the line of code you want to debug.

image-20231117215453584

(4) Debug debugging
  • After setting the breakpoint, right-click anywhere inside the file - Debug file name - to bring up the Debug tool panel - click StepOver/F8 to execute the code step by step.

image-20231117215716182

(5) Debug output panel classification
  • Threads&Variables: Display variables and variable details
  • Console: output content

image-20231117220106490

7. Python formatted output

(1) What is the output?
  • The so-called output is the program output to the user
# 1、定义一些变量
name = '张三'
age = 25
address = '广州市天河区'

# 2、变量的输出(普通输出)
print(name)
print(age)
print(address)

# 在Python,还允许多个变量同时输出
print(name, age, address)
(2) Formatted output
  • The so-called formatted output refers to outputting content in a certain format. Format symbols:

image-20231118094803245

(3) Case demonstration
  • Formatted output in percent form
'''
如果我们想把某些变量通过一定的格式进行输出展现,可以使用百分号形式实现
基本语法:
print(变量名称)
print('字符串%格式' % (变量名称))
print('字符串%格式 %格式 %格式' % (变量名称1, 变量名称2, 变量名称3))
'''
# 案例:定义两个变量name='ly', age=18,按照如下格式进行输出:我的名字是ly,今年18岁了。
name = 'ly'
age = 18
print('我的名字是%s,今年%d岁了。' % (name, age))
# 格式化字符串除了%s,还可以写为f‘{表达式}’,f-格式化字符串是Python3.6中新增的格式化⽅法,该方法更简单易读。
print(f'我的名字是{
      
      name},明年{
      
      age + 1}岁了。')

# 案例:定义两个变量title='大白菜',price=3.5,按照如下格式进行输出:今天蔬菜特价了,大白菜只要3.5元/斤。
title = '大白菜'
price = 3.5
print('今天蔬菜特价了,%s只要%f元/斤。' % (title, price))
# 在Python中,浮点数还可以进一步格式化,比如保留2位小数 => %.2f
print('今天蔬菜特价了,%s只要%.1f元/斤。' % (title, price))

# 案例:定义两个变量id=1,name='ly',按照如下格式进行输出:姓名ly,学号000001
id = 1
stuname = 'ly'
print('姓名%s,学号%d' % (stuname, id))
# 在Python中,%d整数类型还可以进一步格式化,如保留6位,不足的在前面填充0
print('姓名%s,学号%06d' % (stuname, id))

'''
案例:由于受到俄罗斯与乌克兰战争影响,原油价格上浮5%!
记住:如果需要在百分号形式的格式化输出中输出一个百分号,我们可以通过%%来实现!
'''
num = 5
print('由于受到俄罗斯与乌克兰战争影响,原油价格上浮%d%%!' % (num))
  • output
我的名字是ly,今年18岁了。
我的名字是ly,明年19岁了。
今天蔬菜特价了,大白菜只要3.500000元/斤。
今天蔬菜特价了,大白菜只要3.5元/斤。
姓名ly,学号1
姓名ly,学号000001
由于受到俄罗斯与乌克兰战争影响,原油价格上浮5%!
  • Formatted output in format format
'''
基本语法:
print('字符串{}'.format(变量名称1))
print('{}字符串{}'.format(变量名称1, 变量名称2))

强调:.format()形式的格式化输出只能在Python3中使用!
案例:定义两个变量,name='孙悟空',mobile='18878569090',按照以下格式进行输出"姓名:孙悟空,联系方式:18878569090"
'''
name = '孙悟空'
mobile = '18878569090'
print('姓名:{},联系方式:{}'.format(name, mobile))
  • output
姓名:孙悟空,联系方式:18878569090
  • f short form formatted output
# 案例:定义两个变量,name='孙悟空',mobile='18878569090',按照以下格式进行输出"姓名:孙悟空,联系方式:18878569090"
name = '孙悟空'
mobile = '18878569090'
print(f'姓名:{name},联系方式:{mobile}')

# 案例:定义两个变量title='大白菜',price=3.5,按照如下格式进行输出:今天蔬菜特价了,大白菜只要3.5元/斤。
title = '大白菜'
price = 3.5
print(f'今天蔬菜特价了,{title}只要{price:.2f}元/斤。')

# 案例:定义两个变量id=1,name='ly',按照如下格式进行输出:姓名ly,学号000001
id = 1
name = 'ly'
print(f'姓名{name},学号{id:06d}')
  • output
姓名:孙悟空,联系方式:18878569090
今天蔬菜特价了,大白菜只要3.50元/斤。
姓名ly,学号000001
(4) Escape characters
  • \n: newline character.
  • \t: Tab character, one tab key (4 spaces) apart.
  • In Python, print() comes with end="\n" as a newline terminator by default, so every two prints will be directly displayed with a newline. Users can change the terminator according to their needs.
'''
在Python中,通过\字符表示的特殊形式就称之为转义字符。转义字符常见的有这样两种形式:
① \t :制表符,等价于一个Tab键或者4个空格
② \n :换行符,一旦在字符串中遇到了\n,则后面的内容自动另起一行

扩展:print()完整写法print(变量名称, end='\n')代表在输出变量以后,会自动在变量的后面追加一个\n
'''
print('hello\npython')
print('*')
print('*\t*')
print('*\t*\t*')
print('*\t*\t*\t*')
print('*\t*\t*\t*\t*')

# 扩展:思考一个问题,为什么每次使用print()打印变量以后都会自动换行呢?
name = '张三'
age = 23
print(name, end='')
print(age, end='')
  • output
hello
python
*
*	*
*	*	*
*	*	*	*
*	*	*	*	*
张三23

8. Python’s input() input method

(1) What is the input?
  • In Python, the function of a program receiving data input from the user is input.

image-20231118103449670

(2) Basic syntax of input
'''
在Python中,输出我们可以使用print()方法实现。接收由外部设备输入的内容,我们则可以使用input()方法实现。
基本语法:
变量名称 = input('代表提示用户输入信息:')

但是如果程序只有input()其实没有任何意义,我们一般拿到这个数据以后,还需要进一步加工,所以建议定义一个变量保存用户的输入内容
'''
password = input('请输入您要交易的交易密码:')
print(f'您好,您输入的交易密码为:{
      
      password}')
(3) Characteristics of input
  • When the program is executed toinput, it waits for user input. Only after the input is completed can the execution continue.
  • In Python,input after receiving user input, it is generally stored in variables for easy use.
  • In Python,input will treat any user input data received as a string.
'''
input()除了可以接收数据以外,还隐藏了两个特殊的功能:
① input()方法,永远都是str字符串类型
② input()方法还具有一个"暂停"功能,阻塞后续代码的继续执行,直到用户输入完成以后,代码才可以继续向下执行
'''
content = input('请输入您要显示的内容:')
print(type(content))

image-20231118150036256

Guess you like

Origin blog.csdn.net/liyou123456789/article/details/135039002