python作业05

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

1

Define a function that can accept an integer number as input and print the “It is an even number” if the number is even, otherwise print “It is an odd number”.

1
2
3
4
5
6
def checkValue(n):
if n%2 == 0:
print ("It is an even number")
else:
print ("It is an odd number")
checkValue(7)

image-20231008223843267

2

Define a function that can accept two strings as input and print the string with maximum length in console. If two strings have the same length, then the function should print al l strings line by line.

1
2
3
4
5
6
7
8
9
10
11
12
13
def f(s1,s2):
if len(s1)>len(s2):
print(s1)
elif len(s1)<len(s2):
print(s2)
else:
print(s1)
print(s2)
f("1","23")
print()
f("12","3")
print()
f("1","2")

image-20231008223928633

3

Define a function that can accept two strings as input and concatenate them and then print it in console.

1
2
3
4
5
6
def f(s1,s2):
s=s1+s2
return s
s1 = input("s1:")
s2 = input("s2:")
print(f(s1,s2))

image-20231008224011810

4

Define a function that can receive two integral numbers in string form and compute their sum and then print it in console.

分析:字符串转int,然后计算

1
2
3
4
5
6
def f(n1,n2):
n = int(n1)+int(n2)
return n
s1 = input("s1:")
s2 = input("s2:")
print(f(s1,s2))

image-20231008224123058

5

Define a function that can convert a integer into a string and print it in console.

int型转字符串

1
2
3
def f(n):
print(str(n))
f(15)

image-20231008224401734

6

Define a function that can convert a integer into a string and print it in console.

1
2
3
def f(n):
print(str(n))
f(6)

image-20231008224524878

7

Define a function which can compute the sum of two numbers.

1
2
3
def f(n1,n2):
return n1+n2
print(f(12,345))

image-20231008224606123

8

Define a class, which have a class parameter and have a same instance parameter

1
2
3
4
class Myclass:
def __init__(self):
pass
a = Myclass()

9

Python has many built-in functions, and if you do not know how to use it, you can read document online or find some books. But Python has a built-in document function for every built-in functions. Please write a program to print some Python built-in functions documents, such as abs(), int(), raw_input() And add document for your own function

分析:使用__doc__()方法可以输出函数内的注释

image-20231008224934341

10

Write a method which can calculate square value of number

1
2
3
def f(n):
return n**2
print(f(10))

image-20231008225059390

11

Write a program to compute the frequency of the words from the input. The output should output after sorting the key alphanumerically.

分析:字符串处理

1
2
3
4
5
6
7
8
9
10
s = input("Please input a sentence:")
words =s.split()
counts ={}
for word in words:
counts[word]=counts.get(word,0)+1
items = list(counts.items())
items.sort()
for item in items:
word,count =item
print("{}:{}".format(word,count))

image-20231008225247008


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论