0% found this document useful (0 votes)
22 views7 pages

Python Data Structures and Loops Guide

The document provides a comprehensive overview of various programming concepts in Python, including lists, sets, dictionaries, loops, and functions. It demonstrates the creation and manipulation of data structures, control flow with loops and conditionals, and the use of functions for specific tasks. Additionally, it covers advanced topics such as recursion and the range function for generating sequences.

Uploaded by

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

Python Data Structures and Loops Guide

The document provides a comprehensive overview of various programming concepts in Python, including lists, sets, dictionaries, loops, and functions. It demonstrates the creation and manipulation of data structures, control flow with loops and conditionals, and the use of functions for specific tasks. Additionally, it covers advanced topics such as recursion and the range function for generating sequences.

Uploaded by

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

""" Lists"""

# Create the playlist variable


playlist = [1, "Blinding Lights", 2, "One Dance", 3, "Uptown Funk"]

# Print the list


print(playlist)
# Print all songs in the playlist
print(playlist[1::3])
hip_hop = ["Drake", "JAY-Z", "50 Cent", "Drake"]

# Create a set
indie_set = {"Kings of Leon", "MGMT", "Stereophonics"}

# Convert hip_hop to a set


hip_hop_set = set(hip_hop)

# Print the indie and hip_hop sets


print(indie_set, hip_hop_set)

# Loop through the dictionary's keys and values


for key, value in [Link]():

# Check if the value is "AI"


if value == "AI":
print(key, "is an AI course")

# Check if the value is "Programming"


elif value == "Programming":
print(key, "is a Programming course")

# Otherwise, print that it is a "Data Engineering" course


else:
print(key, "is a Data Engineering course")

""" While loop """

tickets_sold = 0
max_capacity = 10

# Create a while loop


while tickets_sold < max_capacity:

# Add one to tickets_sold in each iteration


tickets_sold+=1

# Print the number of tickets sold


print("Sold out:", tickets_sold, "tickets sold!")

""" Conditional While loop """

release_date = 26
current_date = 22

# Create a conditional loop while current_date is less than or equal to the release_date
while current_date <= release_date:
# Increment current_date by one
current_date+=1

# Promote purchases
if current_date <= 24 :
print("Purchase before the 25th for early access")

# Check if the date is equal to the 25th


elif current_date == 25 :
print("Coming soon!")
else:
print("Available now!")

""" appending a list based on a for loop """

# Create an empty list


authors_below_twenty_five = []

# Loop through the authors dictionary


for key, value in [Link]():

# Check for values less than 25


if value < 25:

# Append the author to the list


authors_below_twenty_five.append(key)

print(authors_below_twenty_five)
""" Using IN OR AND """

# Loop through the dictionary


for genre, sale in genre_sales.items():
# Check if genre is Horror or Mystery
if genre == "Horror" or genre == "Mystery":
print(genre, sale)

# Check if genre is Thriller and sale is at least 3 million


elif genre == "Thriller" and sale >= 3000000:
print(genre, sale)

"""
# Dictionary is a key value pair structure
info ={
"key": "value",
"name": "Ahmad",
"age": 24
}
print(info)
# we can store a list and tuple in a dictionary
info ={
"key": "value",
"name": "Ahmad",
"courses Enrolled": ["Python", "Java", "AICT"],
"topics": ("Loops", "Functions", "Arrays"),
"age": 24,
"is_adult": True

}
#print(info)
#print([Link]()) # to print all keys
#print([Link]()) # to print all values
#print(len(info))
#print(list([Link]())) # to print keys as a list using type casting
#print([Link]()) # returns all pairs
print([Link]("topics")) # to add a new key value pair in dictionary
info["surname"] = "Sunny"
print(info)

# You can access value using its key


print(info["name"])
print(info)
# To create an empty dictionary
empty_Dict ={}
print(empty_Dict)
# Nesting of Dictionary
student_nested_dict = {
"name": "Shahid",
"marks": {"Phy": 75,
"Math": 67,
"AICT": 98
}

}
print(student_nested_dict)
print(student_nested_dict["marks"]) # To access details of a key whose value stored as a dictionary
print(student_nested_dict["marks"]["AICT"]) # To access specific key-value of a nested dictionary
#Char considered a single string
a = 65
char = chr(a)
print(char)

# program to get 3 different marks and store in a dictionary


marks = {}
x= int (input("Enter Phy Marks:"))
[Link]({"phy":x})
x= int (input("Enter Math Marks:"))
[Link]({"Math":x})
x= int (input("Enter AICT Marks:"))
[Link]({"AICT":x})
print(marks)

# Set in Python
nums = {1,2,3,4,4} # NO duplicates in Sets and its unordered
print(nums)
print(type(nums))
null_set = set()
print(type(null_set))
[Link](5) # to add a value
print(nums)
[Link](5) # to remove a value
print(nums)
[Link]((1,2,3)) # To add a tuple is allowed
print(nums)
#[Link] ([1,2,3,4]) # LIst not allowed unhashable type error
# [Link]() # to empty the set
nums1 = {1,2,4,5,7}
nums2 = {2,3,4,7}
print([Link](nums2)) # Union of a set
print([Link](nums2)) # intersection of set
# Print a list using loop
nums = [1,4,5,9,8,7,81,100,102,110,115]
idx = 0
while idx< len(nums):
print(nums[idx])
idx+=1

# Search a number in a tuple


nums = (1,4,5,9,8,7,81,100,102,110,115,81)
x= 81
idx = 0
while idx< len(nums):
if(nums[idx]== x):
print("Found at Index", idx)
else:
print("Finding at Index", idx)
#print(nums[idx])
idx+=1

# Break statement to terminate a loop


nums = (1,4,5,9,8,7,81,100,102,110,115,81)
x= 81
idx = 0
while idx< len(nums):
if(nums[idx]== x):
print("Found at Index", idx)
break

idx+=1
print("End of Loop Search")

# Continue statement to skip current iteration of loop


i=0
while i<=5:
if(i==3):
i+=1
continue
print(i)
i+=1

"""
# For loop for sequential traversal from a list and tuple
nums = [1,4,5,9,8,7,81,100,102,110,115]
for val in nums:
print(val)
# for a string
str = "meracollege"
for char in str:
print(char)
"""

# Range function
for el in range (5):
print(el)
for el in range (1,5): # start and stop value
print(el)
for el in range (1,10,2):
print(el)
# To print first 50 even numbers
for even in range (2,101,2):
print(even)
# To print first 50 odd numbers
for even in range (1,100,2):
print(even)

# Print sum of first n numbers


n= int(input("Enter Number"))
sum =0
counter =1
while counter <=n:
sum = sum + counter
counter+=1
print(sum)

# Print factorial of first n numbers


n= int(input("Enter Number"))
factorial = 1
counter =1
while counter <=n:
factorial = factorial * counter
counter+=1
print(factorial)
Functions
# Function block of statements to perform specific task
def calc_sum(a,b): # Function with Parameters
sum = a + b
return sum
print(calc_sum(3,2)) # Function Call
# A function without parameter and return value
def print_hello():
print("HelloWorld")
print_hello()
"""
# Factorial through a Function
def fact_calc(n):
fact = 1
for i in range(1,n+1):
fact *=i
print(fact)
fact_calc(7)

# Recursion
def show(n):
if (n==0): # Base Case
return
print(n)
show(n-1)
show(4)

You might also like