Python Little Goal 2

 

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

 

cbaquiran / Pixabay

 

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

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Social media & sharing icons powered by UltimatelySocial
%d bloggers like this: