参考链接
Assignment:
Write a program that does the following in order:
- Asks the user to enter a number “x”;
- Asks the user to enter a number “y”;
- Prints out number “x”, raised to the power “y”.
- Prints out the log (base 2) of “x”.
Use Spyder to create your program, and save your code in a file named ‘ps0.py’. An example of an interaction with your program is shown below. The words printed in blue are ones the computer should print, based on your commands, while the words in black are an example of a user's input. The colors are simply here to help you distinguish the two components.
Enter number x: 2
Enter number y: 3
X**y = 8
log(x) = 1
作业心得
根据提示,本章作业涉及的知识点如下:
- print / input 函数的使用,可以参考以下文章
- python中的基础数学运算,pow函数; math库的math.pow/log2函数
- numpy库的log2函数
程序的实现过程中,遇到几点需要注意的:
- input函数返回的是str类型,需要通过int函数转化才能进行运算,否则会报错
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'"
- 一般的数据计算,math库也足够了,numpy提供了更多更方便的函数
程序代码
import math
import numpy
# 因为要参与计算,所以需要使用int函数来转化
x = int(input("Enter number x:"))
y = int(input("Enter number y:"))
# 使用内置函数和math库来实现程序
print("x**y = {}\nlog(x) = {}".format(pow(x, y), int(math.log2(x))))
# 使用numpy库来实现程序
print("x**y = {}\nlog(x) = {}".format(numpy.power(x, y), int(numpy.log2(x))))
网友评论