0% found this document useful (0 votes)
18 views11 pages

Python Basics: Functions, Arrays, and Loops

Uploaded by

zainfayyaz498
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views11 pages

Python Basics: Functions, Arrays, and Loops

Uploaded by

zainfayyaz498
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

# Basic

'''a = int(input("Enter the first number"))


b = int(input("Enter the second number"))

# a = int(a)
# b= int(b)

c = a+b
print(c)
'''
from typing import List

# F funtion
'''
f function (To write the string and variable value together

name = "python"
number = int(123)
number2 = int(10)

print(f"This is the programming languge {number} + {number2} = {number + number2}")


'''

# Arrays in python
'''
# Arrys in python
in pyhton we can store different type of data in an array

data = ['zain', 123 ]

0 1 2 ---> positive indexing


names = ['zain','zain2', 'zain3']
-3 -2 -1 ---> negative indexing

print(names[1])

# Array Slicing
print(names[0:3]) ----> it will give the items from 0 to 2, it excludes
the written index

#in and not operators

fruits = ['apple', 'mango', 'grapes']


print('apple2' in fruits)
print('apple2' not in fruits)

#Other functions

to show length
len()

to add something in array


fruits. insert(1, "Watermelon") ---> first one is the index and second one is
what to insert

to add at the end in array, also works to add an arry in to another array
[Link]('watermelon')

to add array item in an array


[Link](["hello world", "hi world"])

to remove an item
[Link]("apple")

[Link]() ---> removes the last item of the array

to find index
[Link]("apple")

to find a maximum number


numbers = [1,2,3,4,5,60,90,180,20,90]
max(numbers)

to find minimum number


min(numbers)

to concate two arrays values


a = [1,2,3]
b = [4,5,6]
a + b

to replicate array elements


a = [1,2,3]
print( a * 3)

multidimention arrays

a = [ 1,2,3,[4,5],6,7,[8,9],10]
print(a[6][1]) ----> at access 9 from the list

three dimentional arrays


[ 1,2,3,[4,5,[122,155,180]],6,7,[8,9],10]
print(a[3][2][2]) ------> to access 180

to modify array
a = [1,2,3]
a[0:3] = [10,20,30]
Lists(arrays) are modifyable but Tuples are not
#Tuples
fruits = ("mango","apple","banana","grapes")

# Dictionary (it has a key and value, it is not accessed by index, it is accessed
by key) (Dictionary is also changeable)
people = {
"John":32 , -------> (john is key and 32 is value )
"Rob":40 ,
"Tim":20
}
print(people['John'])

Another way to create a dictionary

people = dict(
John:32,
Ron:40,
Rox:60
)
// to add something in dictionary

people["Richard"] = 45 //if the key is already present, then it updates


the value, if it is not present, it adds it in the dictionary

// to delete an entry in dictionary

del people["John"]

// get method
[Link]("John") // it does not crash the program if a certain
value in not presnet in the dictionary, but accessing it with the people["John"],
will crash the program if it is not present in it

//to update or add a dictionary into another dictionary

prices = {"iphone":500, "mac":600}


new_prices = {"iphone":800, "watch":500}
[Link](new_prices)
print(prices)

// to remove something from a dictionary


prices = {"iphone":500, "mac":600}
[Link]("mac")

//to get all the values of a dictionary

//------------------------Key value in dictionary------------------------

prices = {'iphone':500, 'ipad':400, 'imac':1500}


//method to get the values in a dictionary
[Link]()

//method to get keys

[Link]()

//methond to get all keys and values

[Link]()

//------------------------Sets in python------------------------

// A set in python in similar to set in mathematics which includes collection of


unique elements

//method to define a set

numbers = set([1,2,3,4,5,6])

//another way to define a set

numbers = {1,2,3,4,5,6}

//a set cannot have a duplicate value, if there is a duplicate value, the set
ignores it and writes it only once
//order in a set is not retained, if you write {1,3,2}, it will set it in
ascending order

//* empty set--------------

s = set()
// write an empty set like {}, it will not be an empty set, it will be a
dictionay which will have key value pair

*// Operations on set---------

-> to find any element in the set


s = set(['John','Rob','Time'])
print('John' in s)

*// Union of sets--------------

seta = {1,2,3,4,5}
setb = {5,6,7,8,9}
seta | setb

*// Intersection of two sets


seta = {1,2,3,4,5}
setb = {5,6,7,8,9}
seta & setb

*// Difference (minus)


seta = {1,2,3,4,5}
setb = {5,6,7,8,9}
seta - setb

*// Symmetric difference (minus) ----> it will remove the common elemnts

seta = {1,2,3,4,5}
setb = {5,6,7,8,9}
seta ^ setb

*// To add a number in a set


seta = {1, 2, 3, 4, 5}
[Link](50)
print(seta)

*// To remove a number in a set


seta = {1, 2, 3, 4, 5}
[Link](5) *---> if you remove a value that is not present in the
set, it will crash the program, so you will use discard method to avoid the crash
print(seta)

*// To remove a number in a set and prevent the crash if the value is not
present in the set
seta = {1, 2, 3, 4, 5}
[Link](50)
print(seta)

*// To remove a random element in a set


seta = {1, 2, 3, 4, 5}
[Link]()

*// To delete all the element in a set


[Link] = {1, 2, 3, 4, 5}

//------------------------Code to search items in a


list------------------------
products = ['phone','tablet','laptop','books ']
item = input('Enter product to search:')
print(item in products) ---------> it is case sensitive

//------------------------Code to remove item in a list------------------------


products = ['phone', 'tablet', 'laptop', 'books ']
item = input("Enter the product to remove: ")
[Link](item)
print(products)
//-----------------------IF statement------------------------
age = 16
if age>16:
print("your are eligible")
else:
print("not eligible")

//-----------------------Else IF (elif) statement------------------------

marks = int(input("Enter marks: "))

if marks>=90:
print("Grade A+")
elif marks>=70:
print("grade b")

//-----------------------Range Function------------------------

numbers = list(range(3,11)) ------> numbers from 3 to 10


numbers = list(range(10)) ------> numbers from 0 to 9
numbers = list(range(3,11,4)) ------> the last number skips counting
print(numbers)

//-----------------------For loop------------------------
for x in range(5):
print(x)

for x in range(1,11):
print(x)

//*looping through a list

fruits = ["Apple","Grapes","Banana"]
for fruit in fruits:
print(fruit)

//*looping through a dictionay

people = {"Tim":300, "Robert":200, "James":500}


for x in people:
print(x) -----------> To access the keys
print(people[x]) ------> To access the values

//-----------------------While loop------------------------
counter = 0
while counter<=10:
print(counter)
counter=counter+1
//-----------------------Adding multiple items in a cart using for
loop------------------------
cart = []
n = int(input("Enter the number of item you want to add: "))
for x in range(n):
item = input("Enter the item you want to add to the cart: ")
[Link](item)
print(cart)

//-----------------------Adding multiple items in a cart using while loop with


choice to add more items------------------------

cart = []
while True:
choice = input("Do you want to add an item to the cart?")
if choice == "yes":
item = input("Add the item to the cart")
[Link](item)
print(cart)

else:
break

//-----------------------Adding multiple items in a cart using while loop with


choice to add more items with all attributes+
products=[
{"name": "Laptop", "price": 1000, "description": "portable personal computer"},
{"name": "Tablet", "price": 300, "description": "touchscreen device"},
{"name": "Smartwatch", "price": 200, "description": "wearable timepiece with
smart features"},
{"name": "Bluetooth Speaker", "price": 150, "description": "portable wireless
speaker"},
{"name": "Gaming Console", "price": 400, "description": "entertainment system
for playing video games"},
{"name": "Headphones", "price": 100, "description": "audio device for personal
listening"},
{"name": "Smart TV", "price": 800, "description": "television with internet and
smart features"},

cart =[]
while True:
choice = input("Do you want to continue shopping? ")
if choice == "yes":
for index,product in enumerate(products):
print(f"{index} : {product['name']} : ${product['price']}:
{product['description']}" )
index_id = int(input("Enter the id of the product you want to add to the
cart"))

#check if the item is already present in the cart


if products[index_id] in cart:
products[index_id]['quantity'] +=1
else:
products[index_id]['quantity'] = 1
[Link](products[index_id])
total = 0
print(f"your new cart items are:")
for product in cart:
print(f"{product['name']} : {product['price']} :
{product['quantity']}")
total = total + product['price']*product['quantity']
print(total)

else:
break
print(f"Thank you for shopping, your cart items are{cart}")

//-----------------------Functions ----------------------
def hello():
print("hi")
print("bye")

hello()

//*Arguements
def add(a,b):
return a+b

print(add(90,78))

//*Keywords

def speed(distance, time):


return distance/time

print(speed(distance=100,time=2))
print(speed(time=2, distance=100))

//*Default arguements

def area(raduis, PI=3.14): ----> it should be placed on left


print(PI*raduis*raduis)

area(10)

//*Passing list in function

scores=[1,2,3,4,5]

def add(numbers):
for number in numbers:
return number

print(add(scores))

//*Accesing global variable in a function, using global keyword

count = 10
def increment():
global count
count =count+1
print(count)

increment()

//*Fucntion to check if the given string is palindrom or not

words ="kook"
lenght = len(words)
palindrome = True
for i in range(lenght):
if words[i] != words[lenght-i-1]:
palindrome =False
break
else:
palindrome =True
if palindrome:
print("The string is a palindrome")

else:
print("The string is not a palindrome")

//to pass many arguments in function, use *args


def add(*args):
sum = 0
for n in args:
sum = sum + n
return sum

print(add(9,2,4))

//*to pass many arguments in function as keywords, use **args

def product(**kwargs):
for key,value in [Link]():
print(key + ":" + value)

product(name='iphone', price='500')
product(name='ipad',price='800',description='this is an ipad')

//*decorator function

def chocolate():
print("Chocolate")
def decorator(func):
def wrapper():
print("Chocolate upper wrapper")
func()
print("chocolate lower wrapper")
return wrapper()

decorator(chocolate)

//* Another way to use decorator with @decorator


def decorator(func):
def wrapper():
print("Chocolate upper wrapper")
func()
print("chocolate lower wrapper")
return wrapper()

@decorator
def chocolate():
print("Chocolate")
@decorator
def cake():

def decorator(func):
def wrapper():
print("Chocolate upper wrapper")
func()
print("chocolate lower wrapper")
return wrapper()

@decorator
def chocolate():
print("Chocolate")
@decorator
def cake():
print("cake")

chocolate()
cake()

'''
# class Solution:
# def solve(self,board):
# position_dict = {}
# for position in board:
# position_dict[position] = 0

# class Solution:
# def solve(self, board):
# # Example board: [(row1, col1), (row2, col2), ...]
# for position in board:
# row, col = position
# # Process each position on the board
# print(f"Processing position at row {row}, col {col}")
# # Further logic to solve the problem goes here
#
# # Example usage
# board = [(0, 0), (1, 2), (2, 1)]
# solution = Solution()
# [Link](board)

You might also like