1901090022-MIT60001-ProblemSet0

打卡记录

作业要求(简述):

Write a program that does the following in order:

  1. Asks the user to enter a number “x”;
  2. Asks the user to enter a number “y”;
  3. Prints out number “x”, raised to the power “y”.
  4. 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.

1
2
3
4
Enter number x: 2 
Enter number y: 3
X**y = 8
log(x) = 1

作业心得

根据提示,本章作业涉及的知识点如下:

程序的实现过程中,遇到几点需要注意的:

  1. input函数返回的是str类型,需要通过int函数转化才能进行运算,否则会报错

    TypeError: unsupported operand type(s) for ** or pow(): ‘str’ and ‘int’”

  2. 一般的数据计算,math库也足够了,numpy提供了更多更方便的函数

程序代码

1
2
3
4
5
6
7
8
9
10
11
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))))