编程语言基础
高级提示词工程师| 第二部分:编程和算法
| 第一节:编程语言基础
| 知识点详解:
Python语法基础
- 变量声明与使用
1
2
3
4a = 10
b = 20.5
name = "Alice"
is_valid = True - 基本数据类型:整数(int)、浮点数(float)、字符串(str)、布尔值(bool)
- 变量声明与使用
控制流
- 条件语句:if、elif、else
1
2
3
4
5
6
7x = 5
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but not more than 10")
else:
print("x is 5 or less") - 循环语句:for循环、while循环
1
2
3
4
5for i in range(5):
print(i)
while not condition:
# 循环体 - 循环控制语句:break、continue
- 条件语句:if、elif、else
函数
- 函数定义:def关键字
1
2def my_function(param1, param2):
# 函数体 - 参数传递
- 返回值:return语句
1
2def add(a, b):
return a + b
- 函数定义:def关键字
模块和包
- 导入模块:import语句
1
import math
- 导入模块:import语句
基本输入输出
- 输入函数:input()
1
name = input("Enter your name: ") - 输出函数:print()
1
print("Hello, " + name)
- 输入函数:input()
注释
- 单行注释
1
# This is a single-line comment - 多行注释
1
2"This is a
multi-line comment"
- 单行注释
异常处理
- 异常捕获:try…except块
1
2
3
4try:
# 尝试执行的代码
except SomeException:
# 异常处理代码 - 异常抛出:raise关键字
- 异常捕获:try…except块
检验问题:
问题一:请写出一个Python函数,该函数接收两个参数,分别是整数a和b,返回它们的和。
1
2
3
4
5def add(a, b):
return a + b
# 测试函数
print(add(3, 5)) # 应该输出 8问题二:如何使用for循环遍历一个字符串中的每个字符,并打印出来?
1
2
3s = "Hello"
for char in s:
print(char)问题三:编写一个Python函数,该函数接收一个字符串作为参数,检查这个字符串是否是回文,如果是,则返回True,否则返回False。
1
2
3
4
5
6def is_palindrome(s):
s = s.lower() # 转换为小写
return s == s[::-1] # 比较字符串和它的反转
# 测试函数
print(is_palindrome("Racecar")) # 应该输出 True问题四:使用while循环实现一个猜数字游戏,程序随机生成一个1到10之间的整数,用户输入猜测的数字,程序提示用户猜得太高或太低,直到猜中为止。
1
2
3
4
5
6
7
8
9
10
11
12
13import random
number = random.randint(1, 10)
guess = 0
while guess != number:
guess = int(input(f"Guess the number between 1 and 10: "))
if guess < number:
print("Too low, try again.")
elif guess > number:
print("Too high, try again.")
print("Congratulations! You guessed it right.")问题五:解释以下Python代码的功能,并指出它可能遇到的错误类型:
1
2
3
4def divide(x, y):
return x / y
result = divide(10, 0) # 这里会抛出异常- 功能:尝试将x除以y并返回结果。
- 可能的错误类型:
ZeroDivisionError,因为除数为0。
问题六:如何导入Python的math模块,并使用它来计算一个数的平方根?
1
2
3
4
5import math
number = 16
square_root = math.sqrt(number)
print(f"The square root of {number} is {square_root}")问题七:在Python中,如何写一个注释来解释你的代码块的功能?
1
2
3
4
5
6# This code block is responsible for calculating the factorial of a number.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
通过完成这些具体的代码案例和检验问题,你将能够巩固和检验你对Python编程基础的掌握程度。
编程语言基础
http://example.com/2024/06/21/关卡1:编程语言基础/