ITPub博客

首页 > IT职业 > IT图书 > python 小目标2

python 小目标2

IT图书 作者:shinez 时间:2021-09-09 10:22:01 0 删除 编辑

Python Day 8

Problem 1: Factorial

Write a factorial function that takes a positive integer,  N as a parameter and prints the result of  N!

Solution:

def factor(n):
    a=1
    for i in range (1,n+1):
        a=a*i
    print(a)
factor(3)
6
factor(5)
120

Problem 2: Age

Create a function age() should perform the following conditional actions:

  • If n is between 0 to 12, print Young.
  • If 13 and 19, print Teenager.
  • Otherwise, print adult.
  • If age is smaller than 0, that’s Not valid
def age(n):
    if n<=0 :
        print ("Not valid")
    elif n in range (0,14):
        print ("Young")
    elif n in range (13,19):
        print ("Teenager")
    else:
        print("adult")

age(-1)
Not valid

[caption id=“attachment_1642” align=“alignnone” width=“500”]图片描述

cbaquiran / Pixabay[/caption]

Problem 3: Do Loop

Given an integer, n, print its first 10 multiples. Each multiple n x i , should be printed on a new line in the form: n x i = result

def mul2(n):
    count=0
    while count <11:
        print(count, "x", n, "=", count*n)
        count +=1
mul2(3)
0 x 3 = 0
1 x 3 = 3
2 x 3 = 6
3 x 3 = 9
4 x 3 = 12
5 x 3 = 15
6 x 3 = 18
7 x 3 = 21
8 x 3 = 24
9 x 3 = 27
10 x 3 = 30

Problem 4: Odd-Even Position

Given a string, S, of length N  that is indexed from 0 to N-1 , print its even-indexed and *odd-indexed *characters as 2 space-separated strings on a single line

def sep_string(a):
    l=list(a)
    l2=list()
    l1=list()
    index=0

    for letter in l:
        if index %2 ==1:
           l1.append(letter)
        else:
           l2.append(letter)
        index +=1
    string_even = " ".join(l2)
    string_odd=" ".join(l1)
    print(string_even.replace(" ", ""), " ",  string_odd.replace(" ",""))

sep_string("Wonderful")
Wnefl   odru

Happy Studying! ????

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3127/viewspace-2821097/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    0
  • 访问量
    932