Python- Day6
2 min readJul 14, 2024
Functions, and While Loop:
Functions:
Functions in Python are blocks of reusable code that perform a specific task. They allow you to organize your code into manageable sections and promote code reuse.
Defining a Function:
def function_name(parameters):
# Function body
function_name()
def my_function(name= input("What is your name? - ")):
print(f"Hello, {name}!")
my_function() # Output: Hello, Guest!
my_function("Welcome !") # Output: Hello, Welcome!
>>
What is your name? - Nidhi
Hello, Nidhi!
Hello, Welcome !!
We can call a Function within a function:
def my_function(name= input("What is your name? - ")):
print(f"Hello, {name}!")
def fun():
print(f"This is for calling def my_function.")
my_function()
fun()
>>
What is your name? - Nidhi
This is for calling def my_function.
Hello, Nidhi!
We have learned about the “for in” loop, let's use it:
def my_function(name= input("What is your name? - ")):
print(f"Hello, {name}!")
def fun():
print(f"This is for calling def my_function.")
my_function()
for say in range(6):
fun()
>>
What is your name? - Nidhi
This is for calling def my_function.
Hello, Nidhi!
This is for calling def my_function.
Hello, Nidhi!
This is for calling def my_function.
Hello, Nidhi!
This is for calling def my_function.
Hello, Nidhi!
"While"
loop:
while something_is_true: #Condition
#Do it repeatedly
#Mentioned here
#Defining value in code
number = 1
# While loop to print numbers from 1 to 10
while number <= 10:
print(number)
# Increment the number by 1
number += 1
>>
1
2
3
4
5
6
7
8
9
10
#Asking user for input
user_number = int(input("Enter the number - "))
num = 1 #start number from
# While loop to print numbers from 1 to 10
while num <= user_number:
print(num)
# Increment the number by 1
num += 1
>>
Enter the number - 5
1
2
3
4
5
While not/ !=
correct_password = "secret"
user_input = ""
while not user_input == correct_password: # We can use while not / !=
user_input = input("Enter the password: ")
print("Access granted!")
correct_password = "secret"
user_input = ""
while user_input != correct_password: # We can use while not / !=
user_input = input("Enter the password: ")
print("Access granted!")
Adding If/else :
correct_password = "secret"
user_input = ""
while user_input != correct_password:
user_input = input("Enter the password: ")
if user_input == correct_password:
print("Access granted!")
else:
print("Incorrect password, please try again.")
>>
Enter the password: 123
Incorrect password, please try again.
Enter the password: 258
Incorrect password, please try again.
Enter the password: adda
Incorrect password, please try again.
Enter the password: secret
Access granted!
If you found this guide helpful then do click on 👏 the button.
Follow for more Learning like this 😊
If there’s a specific topic you’re curious about, feel free to drop a personal note or comment. I’m here to help you explore whatever interests you!