Python 官方文档:入门教程 => 点击学习
1、使用while循环实现输出2 - 3 + 4 - 5 + 6 ... + 100的和 #方法一 #从2开始计算 i = 2 #定义一个变量用于保存结果 sum=0 while i
#方法一
#从2开始计算
i = 2
#定义一个变量用于保存结果
sum=0
while i <= 100:
if i % 2 == 0:
sum = sum + i
else:
sum = sum - i
i += 1
print("2-3+4-5+6...+100=",sum)
#方法二
n=3
sum=2
while n<=100 :
#n对2取余
if n % 2 != 0:
sum = sum - n
n = n + 1
else:
sum = sum + n
n = n + 1
print("2-3+4-5+6...+100=",sum)
运行结果:
提示:
1!等于1
2!等于1*2
3!等于1*2*3
n!等于1*2*3*...*n
n = int(input("请输入一个非负的数字:")) # 负数不算阶乘
def factorial(n):
if n == 0:
return 1 # 0的阶乘是1
else:
return n * factorial(n - 1)
if __name__ == '__main__':
result=factorial(n)
print("{}的阶乘为:{}".fORMat(n,result))
try:
score=float(input('请输入考试成绩:'))
if score>=90:
print('A')
elif 80<=score<90:
print('B')
elif 70<=score<80:
print('C')
elif 60<=score<70:
print('D')
else:
print('E')
except Exception as e:
print('您输入有误!')
save_money = float(input("请输入你要存入银行的钱:"))
print("你存了{}元到银行".format(save_money))
total_money = save_money * 2 # 定义变量用于保存总钱数
year = 1 # 定义变量用于记录年份
while save_money < total_money:
save_money *= (1 + 0.0352)
year += 1
print("定期利率为3.52%,需要{}年本金和利息才能翻一番!".format(year))
# 方法一 字符串函数调用
a = ["I","T","e","s","t","e","r"]
print("".join(a))
#方法二 for循环
a = ["I","T","e","s","t","e","r"]
s = ""
for item in a:
s += item
print(s)
--结束END--
本文标题: Python必考的5道面试题集合
本文链接: https://www.lsjlt.com/news/119099.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0