Rainy
Rainy
Rainy Budhathoki
Nov 3, 2024
For Loop
Iterate over list, range (enumarator)
In [ ]: numbers = [1,1,2,3,4,5,3,11,100]
even_list = []
# iterate over list
for num in numbers:
print (num)
1
1
2
3
4
5
3
11
100
In [ ]: # To find the even and odd numbers from the given numbers
file:///C:/Users/Administrator/Downloads/Rainy.html 1/6
11/3/24, 4:04 PM Rainy
2
4
100
[2, 4, 100]
[1, 1, 3, 5, 3, 1]
2 exists in numbers
numbers=[1,1,2,3,4,5,3,1,100,2,4,7,9,100]
unique_num=[]
[1, 2, 3, 4, 5, 100, 7, 9]
H
e
l
l
o
W
o
r
l
d
file:///C:/Users/Administrator/Downloads/Rainy.html 2/6
11/3/24, 4:04 PM Rainy
total_vowels +=1
print (total_vowels)
numbers = [100,1,-10,5]
sum=0
for num in numbers:
sum += num
print(sum)
96
Range
Range(start,stop,step)
In [ ]: range_of_100 = range(1,10)
sum=0
for i in range(1,11): #for i=0; i<10, i++
print(i)
sum+=i
1
2
3
4
5
6
7
8
9
10
block of code
file:///C:/Users/Administrator/Downloads/Rainy.html 3/6
11/3/24, 4:04 PM Rainy
return expression
In [ ]: #finding the sum of two numbers
def add(x,y):
sum = x+y
return sum
sum = add(x=5, y=10)
print(sum)
15
def product(x,y):
product = x*y
return product
prod = product(5,10)
print(prod)
50
In [ ]: # Write a function # Write a function that accepts three parameters (x, y, operatio
# based on the operation (+, -, *, /)
# Perform addition, subtraction, multiplication, and division
# and then return the value of x operation y
3
1.0
In [ ]: # Establishing IP connection
def connect(ip="127.0.0.1"):
print(f"Hello connecting to {ip}")
connect()
file:///C:/Users/Administrator/Downloads/Rainy.html 4/6
11/3/24, 4:04 PM Rainy
def connect(ip="12.12.3.4"):
print(f"Hello connecting to {ip}")
connect("12.12.3.4")
In [ ]: def connect(ip="12.12.3.4"):
print(f"Hello connecting to {ip}")
connect("12.12.3.4")
add=sum(1)
print(add)
Return Statement:
functions can return values after using this statement
if no return statement is used, the function returns None by default
Lambda Function
Lambda function (anonymous function) are small, single-expression functions defined
by lambda keyboard
They are often used for short, simple operations
Extra Questions
In [ ]: # Write a function to swap two numbers without using a temporary variable
file:///C:/Users/Administrator/Downloads/Rainy.html 5/6
11/3/24, 4:04 PM Rainy
a = a - b
print(a, b)
return a, b
a, b = swap_numbers(5, 10)
print(a, b)
10 5
10 5
def count_vowels(sentence):
total_vowels = 0
vowels = "aeiouAEIOU"
for char in sentence:
if char in vowels:
total_vowels += 1
return total_vowels
def prime(number):
is_prime = True
for i in range(2, int(number / 2) + 1):
print(i) # Numbers less than or equal to 1 are not prime
if number % i == 0: # Check up to the square root of the number
is_prime = False
break # If condition matches, then loop breaks (break = earl
return is_prime
print(prime(16))
2
False
file:///C:/Users/Administrator/Downloads/Rainy.html 6/6