Python

[Exercise] Functions

grace21110 2024. 4. 5. 00:42
반응형

The following exercise was the one that I struggled and I have provided the solution as well. 

# 3. Write a function called print_pattern that takes integer number as an argument and prints following pattern if input number is 3,
# *
# **
# ***
# if input is 4 then it should print
# *
# **
# ***
# ****
# Basically number of lines it prints is equal to that number. (Hint: you need to use two for loops)

def print_pattern(n=5):
    
    for i in range (n):
        s = " "
        for j in range (i +1):
            s = s + "*"
            
        print(s)

 

This question requires you to use functions and for loops. 

 

1. You have to define print_pattern with the default argument, n = 5. 

2. Inside the function, there is a loop that iterates n times.

3. An inner loop runs i+1 times. 

4. Inside the inner loop, the variable s is initialized to an empty string (" ").

5. Within the inner loop, * charaters are concatenated to the string s, forming the sequences of stars. 

 

The more I try to solve problems, the more I get to know that it is very important to learn the fundamentals. I am excited to explore all the exercises for each chapter. 

 

Just in case you want to refer, I have attached my github below :) 

https://github.com/haeunkim48/Basics-