继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Python 小目标2

乌然娅措
关注TA
已关注
手记 64
粉丝 21
获赞 12

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! 🤙

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP