0% found this document useful (0 votes)
35 views51 pages

My First Python Codes - Jupyter Notebook

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)
35 views51 pages

My First Python Codes - Jupyter Notebook

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
You are on page 1/ 51

5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

FEB 3, 2024

PRINT FUNCTION
In [1]: print ("Hello world!")

Hello world!

In [2]: print ("hello everyone??")

hello everyone??

In [3]: print (1234567890)

1234567890

In [4]: print ("1234567890")

1234567890

In [5]: print ("HELLO gyus I am Haniyah Abdul Samad!!!!!")

HELLO gyus I am Haniyah Abdul Samad!!!!!

In [7]: print ("how are you fine? me too............")

how are you fine? me too............

In [8]: print ("fueuuehh123")

fueuuehh123

In [ ]: print ("code" 29 "first!")

In [10]: print ("code", 29, "first!")

code 29 first!

In [1]: print ("hiufefehduuvfy3932j u8911jj119199iwjenueueuduehwbwjjw")

hiufefehduuvfy3932j u8911jj119199iwjenueueuduehwbwjjw

Feb 10, 2024

localhost:8888/notebooks/My First Python Codes.ipynb 1/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [4]: print("Haniyah samad", 15, "october", 29)


print("Haniyah Samad", 15, "October", 29)

Haniyah samad 15 october 29


Haniyah Samad 15 October 29

In [5]: print("Name" , " ", "Marks(100)")


print("Haniyah", " ", 100)
print("Salahuddin", " ", 99)

Name Marks(100)
Haniyah 100
Salahuddin 99

In [6]: print("haniyah samad", 15 "october", 29, sep = " **** ")

Cell In[6], line 1


print("haniyah samad", 15 "october", 29, sep = " **** ")
^
SyntaxError: invalid syntax. Perhaps you forgot a comma?

In [3]: print ("Haniyah Samad", 15, "October", 29, sep = " **** ")

Haniyah Samad **** 15 **** October **** 29

In [4]: print ("Haniyah Samad", 15, "October", 29, sep = " :)) ")

Haniyah Samad :)) 15 :)) October :)) 29

In [7]: print ("Haniyah Samad", 15, "October", 29, sep = "\n")

Haniyah Samad
15
October
29

In [8]: print("Haniyah samad", 15, "october", 29, end = " Next Statement ")
print("Haniyah Samad", 15, "October", 29)

Haniyah samad 15 october 29 Next Statement Haniyah Samad 15 October 29

In [9]: print("Haniyah samad", 15, "october", 29, end = " *** Next *** ")
print("Haniyah Samad", 15, "October", 29)

Haniyah samad 15 october 29 *** Next *** Haniyah Samad 15 October 29

VARIABLE

localhost:8888/notebooks/My First Python Codes.ipynb 2/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [10]: # Variable is just like a box in which you can store any type of data.
# Variables are used to store values.

In [1]: a = 10

In [2]: print (a)

10

In [2]: print ("a")

In [14]: print ("value of a is", a)

value of a is 10

In [15]: a = 12.2
print ("value of a is", a)

value of a is 12.2

In [21]: type(a)

Out[21]: float

In [24]: country = "pakistan"

In [25]: print ("country name is", country )

country name is pakistan

In [26]: type (country)

Out[26]: str

In [27]: # Variable name can be anything, but it should not start with a number.

In [28]: name = "Inayah"

In [30]: print (name)

Inayah

In [31]: abc = "Inayah"


print (abc)

Inayah

localhost:8888/notebooks/My First Python Codes.ipynb 3/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [32]: abc123 = "Inayah"


print (abc123)

Inayah

In [30]: name = "Inayah"

In [5]: Hani = "Inayah"


print (Hani)

Inayah

DATA TYPES
In [35]: # Integers data types
# Integers are numbers (0,1,2,3,4,5,99,34567)

# Float data types
# Float data types are for decimals numbers (1.56 , 76.567)

# String data type
# string data type is for characters (any words or sentences or any combinatio

TYPES OF VARIABLES
In [7]: a = 12
b = 1.5
c = "Salahuddin"

print ("Type of variable a is", type(a))
print ("Type of varialbe b is", type(b))
print ("Type of variable c is", type(c))

Type of variable a is <class 'int'>


Type of varialbe b is <class 'float'>
Type of variable c is <class 'str'>

OPERATERS
In [ ]: # ADD: +
# SUBTRACTION: -
# MULTIPLICATION: *
# Integers DIVISION: //
# Float DIVISION: /

localhost:8888/notebooks/My First Python Codes.ipynb 4/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

ADDITION OF VARIABLES
In [1]: # Addition of Strings (known as concatination)

First_Name = "Haniyah"
Middle_Name = "Abdul"
Last_Name = "Samad"

# Task: Print Full Name.

Full_Name = First_Name + Middle_Name + Last_Name

print ("Full_Name is", Full_Name)

Full_Name is HaniyahAbdulSamad

In [10]: Full_Name = First_Name + " " + Middle_Name + " " + Last_Name



print ("Full_Name is", Full_Name)

Full_Name is Haniyah Abdul Samad

In [3]: # Addition of Integers



num1 = 70
num2 = 25

sum = num1 + num2

print ("sum of", sum)

sum of 95

In [4]: print ("sum of" , num1, "and", num2 , "is", sum)

sum of 70 and 25 is 95

In [6]: print (sum)

95

In [8]: print ("Sum:", sum)

Sum: 95

In [9]: print ("Sum of", "num1", "and", "num2", "is", "sum")

Sum of num1 and num2 is sum

localhost:8888/notebooks/My First Python Codes.ipynb 5/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [15]: # Subtraction of Integers



num1 = 70
num2 = 25

Difference = num1 - num2

print ("Difference of", num1, "and", num2, "is", Difference)

Difference of 70 and 25 is 45

In [17]: print ("Difference is", Difference)

Difference is 45

In [18]: # Multiplication of Integers



num1 = 8
num2 = 7

Product = num1 * num2

print ("Product of", num1, "and", num2, "is", Product)

Product of 8 and 7 is 56

In [19]: print (Product)

56

In [20]: print ("Product is", Product)

Product is 56

In [21]: # Multiplication of Integers



num1 = 8
num2 = 7

#Product = num1 * num2

print ("Product of", num1, "and", num2, "is", num1*num2)

Product of 8 and 7 is 56

18 FEB, 2023

localhost:8888/notebooks/My First Python Codes.ipynb 6/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [1]: # DIVISION

# "/" == FLOATING POINT DIVISION
# "//" == INTEGER DIVISION

In [5]: # FLOAT

num1 = 50
num2 = 5

Quotient = num1 / num2
print ("quotient of", num1, "and", num2, "is", Quotient)

quotient of 50 and 5 is 10.0

In [6]: # FLOAT

num1 = 50
num2 = 4

Quotient = num1 / num2
print ("quotient of", num1, "and", num2, "is", Quotient)

quotient of 50 and 4 is 12.5

In [7]: # INTEGER

num1 = 50
num2 = 5

Quotient = num1 // num2
print ("quotient of", num1, "and", num2, "is", Quotient)

quotient of 50 and 5 is 10

In [8]: # INTEGER

num1 = 50
num2 = 4

Quotient = num1 // num2
print ("quotient of", num1, "and", num2, "is", Quotient)

quotient of 50 and 4 is 12

localhost:8888/notebooks/My First Python Codes.ipynb 7/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [10]: # TASK

# Take 8 different numbers in 8 different variables.
# Add first 2 numbers and print the sum.
# Subtract 3rd and 4th numbers and print the difference.
# Multiply 5th and 6th numbers and print the product.
# Divide (integer division) 7th & 8th numbers and print the Quotient.

# Note: print function should be in detail


# 8 variables
num1 = 68
num2 = 13
num3 = 43
num4 = 73
num5 = 23
num6 = 67
num7 = 13
num8 = 15

# Add
Sum = num1 + num2
print ("Sum of", num1, "and", num2, "is", Sum)

# Subtract
Difference = num3 - num4
print ("Difference between", num3, "and", num4, "is", Difference)

# Product
Product = num5 * num6
print ("product of", num5, "and", num6, "is", Product)

# Division

Quotient = num7 // num8
print ("Quotient of", num7, "and", num8, "is", Quotient)

Sum of 68 and 13 is 81
Difference between 43 and 73 is -30
product of 23 and 67 is 1541
Quotient of 13 and 15 is 0

IF STATEMENT
In [13]: Bank_Balance = 20000
Withdaw_Amount = 5000
if (Bank_Balance > Withdaw_Amount):
print("Transaction Successful.")
print("Remaining Balance:" , Bank_Balance - Withdaw_Amount)

Transaction Successful.
Remaining Balance: 15000

localhost:8888/notebooks/My First Python Codes.ipynb 8/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [14]: Bank_Balance = 2400


Withdaw_Amount = 500

if (Bank_Balance > Withdaw_Amount):
print("Transaction Successful.")
print("Remaining Balance:" , Bank_Balance - Withdaw_Amount)

Transaction Successful.
Remaining Balance: 1900

In [15]: Haniyah = 15
Musab = 8

if (Haniyah > Musab):
print ("Haniyah is senior.")

Haniyah is senior.

24 FEB, 2023

if - else statement
In [16]: Bank_Balance = 20000
Withdaw_Amount = 5000

if (Bank_Balance > Withdaw_Amount):
print("Transaction Successful.")
print("Remaining Balance:" , Bank_Balance - Withdaw_Amount)
else:
print ("Insufficient Balance")

Transaction Successful.
Remaining Balance: 15000

In [17]: Bank_Balance = 20000


Withdaw_Amount = 50000

if (Bank_Balance > Withdaw_Amount):
print("Transaction Successful.")
print("Remaining Balance:" , Bank_Balance - Withdaw_Amount)
else:
print ("Insufficient Balance")

Insufficient Balance

localhost:8888/notebooks/My First Python Codes.ipynb 9/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [18]: # Issue: Need of >= oprater



Bank_Balance = 20000
Withdaw_Amount = 20000

if (Bank_Balance > Withdaw_Amount):
print("Transaction Successful.")
print("Remaining Balance:" , Bank_Balance - Withdaw_Amount)
else:
print ("Insufficient Balance")

Insufficient Balance

if - elif statement
In [19]: # Issue (Wrong Example, need of elif statement)
# Task: Take 2 numbers in 2 different variables.
# Find out, which number is greater

num1 = 10
num2 = 10

if (num1 > num2):
print ("first number", num1, "is greater than second number", num2)
else:
print ("second number", num2 , "is greater than first number", num1)

second number 10 is greater than first number 10

In [20]: num1 = 100


num2 = 100

if (num1 > num2):
print ("First number", num1, "is greater than second number", num2)
elif (num2 > num1):
print ("Second number", num2, "is greater than First number", num1)
else:
print ("Both numbers are equal.")

Both numbers are equal.

25 FEB, 2023

localhost:8888/notebooks/My First Python Codes.ipynb 10/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [21]: # Task: find out the grades of students (Marks = 83)



# Grading Policy:
# greater than 90 = A*
# 81 - 90 = A
# 71 - 81 = B
# 61 - 70 = C
# 51 - 60 = D
# Less than 50 = F

Marks = 43

if (Marks > 90):
print ("A* Grade.")

elif (Marks > 80):
print ("A Grade.")

elif (Marks > 70):
print ("B Grade.")

elif (Marks > 60):


print ("C Grade.")

elif (Marks > 50):


print ("D Grade.")

else:
print ("F Grade.")

F Grade.

SIMPLE CALCULATOR

localhost:8888/notebooks/My First Python Codes.ipynb 11/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [12]: num1 = 88
operater = "*"
num2 = 50

if (operater == "+"):
add = num1 + num2
print ("Sum of" , num1 , "and" , num2 , "is" , add)

elif (operater == "-"):


subt = num1 - num2
print ("Difference between", num1, "and", num2, "is", Subt)

elif (operater == "*"):


Product = num1 * num2
print ("Product of", num1, "and", num2, "is", Product)

elif (operater == "/"):


div = num1 / num2
print ("Quotient of", num1, "and", num2, "is", div)

Product of 88 and 50 is 4400

March 2nd , 2023


In [16]: # Task: Make a program for mobile password unlock.

savedPassword = "1122"

userpin = input ("Type your 4 digit pincode ")

if (savedPassword == userpin):
print ("correct PIN. screen unlocked")
else:
print ("Incorrect PIN")

Type your 4 digit pincode 1234


Incorrect PIN

In [25]: #Task: Find out either "1234" (str) == 1234 (int)



code = 1234

userInput = (input ("Enter 1234."))

if (code == userInput):
print ("1234 (str) is equal to 1234 (int)")
else:
print ("1234 (str) is not equal to 1234 (int)")

Enter 1234.1234
1234 (str) is not equal to 1234 (int)

localhost:8888/notebooks/My First Python Codes.ipynb 12/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [23]: # Use of int() function



savedPassword = "1122"

userpin = int(input("Type your 4 digit pincode "))

if (savedPassword == userpin):
print ("correct PIN. screen unlocked")
else:
print ("Incorrect PIN")

Type your 4 digit pincode 1234


Incorrect PIN

In [26]: # Make a program to get email and password from user and check either its corr
# Hint: (Save yor email & password as default in your code.)

saved_email = "abc@gmail.com"
saved_password = "hani123"

input_email = input("Enter your email id:")
input_password = input("Enter your password:")

if (saved_email == input_email):
if (saved_password == input_password):
print ("Login Successful.")
else:
print ("Wrong password.")
else:
print ("Wrong email.")

Enter your email id:abc@gmail.com


Enter your password:hani123
Login Successful.

SIMPLE CALCULATOR

localhost:8888/notebooks/My First Python Codes.ipynb 13/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [1]: num1 = int(input("Enter 1st number:"))


operater = input("+ , - , * , /")
num2 = int(input("Enter 2nd number:"))

if (operater == "+"):
add = num1 + num2
print ("Sum of" , num1 , "and" , num2 , "is" , add)

elif (operater == "-"):


subt = num1 - num2
print ("Difference between", num1, "and", num2, "is", subt)

elif (operater == "*"):


Product = num1 * num2
print ("Product of", num1, "and", num2, "is", Product)

elif (operater == "/"):


div = num1 / num2
print ("Quotient of", num1, "and", num2, "is", div)

Enter 1st number:748


+ , - , * , /*
Enter 2nd number:646
Product of 748 and 646 is 483208

ATM MACHINE CODE

localhost:8888/notebooks/My First Python Codes.ipynb 14/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

localhost:8888/notebooks/My First Python Codes.ipynb 15/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [ ]: # Account Detailes
Account1_name = "Haniyah Samad"
Account1_ATM = "20081029"
Account1_PIn = "3456"
Account1_Balance = 90000

Account2_name = "Muhammad Musab"
Account2_ATM = "498765"
Account2_PIn = "9876"
Account2_Balance =80000

Account3_name = "Naimah Baji"
Accont3_ATM = "202026"
Account3_PIn = "1234"
Account3_Balance = 70000

# Enter ATM card
user_ATM = input("Please Enter your ATM Card Number:")
# Account_1
if (user_ATM == Account1_ATM):
print (Account1_name)
user_PIn = input("Enter your 4-Digit PIn:")
if (user_PIn == Account1_PIn):
option = input ("Press 1 to check Balance , Press 2 to Withdraw Cash."
if (option == "1"):
print ("Your available Balance: Rs" , Account1_Balance)
elif (option == "2"):
Withdraw_Amount = int(input("Enter Amount to Withdraw:"))
if (Withdraw_Amount <= Account1_Balance):
Account1_Balance = Account1_Balance - Withdraw_Amount
print ("Withdraw Successful")
print ("Take Your ATM Card.")
print ("Take Your Cash.")
print ("Your remaining Balance is" , Account1_Balance)
else:
print ("Insufficient Balance.")
else:
print ("Invalid Balance.")
else:
print ("Wrong PIn Code.")


#Account 2
elif (user_ATM == Account2_ATM):
print (Account2_name)
user_PIn = input("Enter your 4-Digit PIn:")
if (user_PIn == Account2_PIn):
option = input ("Press 1 to check Balance , Press 2 to Withdraw Cash."
if (option == "1"):
print ("Your available Balance: Rs" , Account2_Balance)
elif (option == "2"):
Withdraw_Amount = int(input("Enter Amount to Withdraw:"))
if (Withdraw_Amount <= Account2_Balance):
Account2_Balance = Account2_Balance - Withdraw_Amount
print ("Withdraw Successful")
print ("Take Your ATM Card.")
print ("Take Your Cash.")
localhost:8888/notebooks/My First Python Codes.ipynb 16/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook
print ("Your remaining Balance is" , Account2_Balance)
else:
print ("Insufficient Balance.")
else:
print ("Invalid Balance.")
else:
print ("Wrong PIn Code.")

# Account 3
elif (user_ATM == Account3_ATM):
print (Account3_name)
user_PIn = input("Enter your 4-Digit PIn:")
if (user_PIn == Account3_PIn):
option = input ("Press 1 to check Balance , Press 2 to Withdraw Cash."
if (option == "1"):
print ("Your available Balance: Rs" , Account3_Balance)
elif (option == "2"):
Withdraw_Amount = int(input("Enter Amount to Withdraw:"))
if (Withdraw_Amount <= Account3_Balance):
Account3_Balance = Account3_Balance - Withdraw_Amount
print ("Withdraw Successful")
print ("Take Your ATM Card.")
print ("Take Your Cash.")
print ("Your remaining Balance is" , Account3_Balance)
else:
print ("Insufficient Balance.")
else:
print ("Invalid Balance.")
else:
print ("Wrong PIn Code.")

Mar 16, 2024


In [ ]: # Save all siblings names.

Sibling1 = "Haniyah"
Sibling2 = "Salahuddin"
Sibling3 = "Shaheedu"
Sibling4 = "Zaeemu"

LIST
In [ ]: # List is used store multiple values in a single variable.
# We use [] to make a list.

# Syntax:
# ListName = [value1 , value2 , value3 , value4 , .......]

localhost:8888/notebooks/My First Python Codes.ipynb 17/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [1]: # Save all siblings names


# Creat a list of siblings

Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu"]
print ("List of Siblings:" , Siblings)

List of Siblings: ['Haniyah', 'Salahuddin', 'Shaheedu', 'Zaeemu']

In [2]: # Creat a List of 9 random numbers



numbs = [29 , 24 , 17 , 10 , 1 , 21 , 9 , 2 , 13 ]
print (numbs)

[29, 24, 17, 10, 1, 21, 9, 2, 13]

In [3]: Account1 = ["Haniyah" , "20081029" , "3456" , 90000]


Account2 = ["Haniyah" , "20081029" , "3456" , 90000]

In [4]: print ("Account1:" , Account1)


print ("Account2:" , Account2)

Account1: ['Haniyah', '20081029', '3456', 90000]


Account2: ['Musab', '498765', '9876', 80000]

INDEX NUMBER
In [5]: # Index no is the address of each value in the list
# First value has index no 0, next value has index no 1, and so on.....

# List = [Value1 , Value2 , Value3 , Value4......]
# Index = 0 1 2 3 ......

HOW TO ACCESS LIST ELEMENTS?


In [12]: # Name ATM PIN Balance
Account1 = ["Haniyah" , "20081029" , "3456" , 90000]
Account2 = ["Musab" , "498765" , "9876" , 80000]
# Index 0 1 2 3

In [14]: # Access list elements


# Syntax
# ListName[index no]

print ("Account Holder Nmae:" , Account1)
print ("Account Holder Nmae:" , Account2)

Account Holder Nmae: ['Haniyah', '20081029', '3456', 90000]


Account Holder Nmae: ['Musab', '498765', '9876', 80000]

localhost:8888/notebooks/My First Python Codes.ipynb 18/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [17]: # Task:
# Print Account Holder Names with Account Balance

print ("Account1 :" , Account1[0] , ":" , Account1[3])
print ("Account2 :" , Account2[0] , ":" , Account2[3] )

Account1 : Haniyah : 90000


Account2 : Musab : 80000

MAR 17, 2024

Length of the List


In [20]: # Syntax:
# Len(ListName)

Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu" , "Inayah"]
print ("Length of the list is" , len(Siblings))

Length of the list is 5

In [21]: numbs = [1,2,3,4,5,67,89,56,43]


print ("Length :" , len(Siblings))

Length : 5

Functions of List
In [18]: Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu"]

In [22]: # Siblings.append ("value") # Add a new value


# Siblings.clear () # Clear the list
# Siblings.copy () # Create a copy of list
# Siblings.count () # It will count how many times a specific value is in the
# Siblings.index () # Give index number of any specific value.
# Siblings.insert () # Add a new value at specific index.
# Siblings.pop () # It will delete and return the value.
# Siblings.remove () # It will remove the value
# Siblings.reverse () # Reverse the order of the list
# Siblings.sort () # Sort the list in descending order

APPEND

localhost:8888/notebooks/My First Python Codes.ipynb 19/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [23]: # Append function is use to add any value in the list


# Append function will add the value at the enf of the list.

# Syntax:
# ListName.append(Value)

In [24]: Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu"]



# Task: Add "Ammar" In the list of siblings and print the list.

Siblings.append("Ammar")
print (Siblings)

['Haniyah', 'Salahuddin', 'Shaheedu', 'Zaeemu', 'Ammar']

In [25]: Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu"]



# Task: Add "Naimah" In the list of siblings and print the list.

Siblings.append("Naimah")
print (Siblings)

['Haniyah', 'Salahuddin', 'Shaheedu', 'Zaeemu', 'Naimah']

MAR 24, 2024

INSERT
In [1]: # Difference between Append and Insert

# Append
# It will add the new value at the end of the list
# Syuntax: ListName.append(value)

# Insert
# It will add the new value at any given index number
# Syntax: Listname.insert(index no , value)

In [2]: Siblings = ["Haniyah" , "Salahuddin" , "Shaheedu" , "Zaeemu"]

In [3]: # Task: Add "Naimah" at the start of the list



Siblings.insert(0 , "Naimah")
print ("Siblings List:" , Siblings)

Siblings List: ['Naimah', 'Haniyah', 'Salahuddin', 'Shaheedu', 'Zaeemu']

localhost:8888/notebooks/My First Python Codes.ipynb 20/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [4]: # Task: Add "Inayah" at index 4



Siblings.insert(4 , "Inayah")
print ("Siblings list:" , Siblings)

Siblings list: ['Naimah', 'Haniyah', 'Salahuddin', 'Shaheedu', 'Inayah', 'Za


eemu']

In [2]: # Task:
# Create a list of your 3 Friends.
# Add a new friend name "Samreen" at first place in previous list.
# Add "END" at the last of the list.
# Print the list

Friends = ["Sarah" , "Zurwah" , "Saqia"]
Friends.insert(0 , "Samreen")
Friends.append("END")
print (Friends)

['Samreen', 'Sarah', 'Zurwah', 'Saqia', 'END']

CLEAR
In [7]: # IT will remove all the values from the list
# It will make the list empty

In [8]: print(Friends)

['Samreen', 'Sarah', 'Zurwah', 'Saqia', 'END']

In [10]: # Task: Remove all the lines from the Friends list

Friends.clear()
print ("List:" , Friends)

List: []

COPY
In [23]: # Copy by value
# After creating a new copy of of list, any changes in main list will not effe
# Syntax: CopiedListName = MainListName.Copy()

# Copy by refference
# After creating a copy of list, any changes in main list will also gets chang
# CopiedlistName = MainListName

Copy By Value
localhost:8888/notebooks/My First Python Codes.ipynb 21/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [24]: friends = ["Hareem" , "Hala" , "Inayah" , "Hiba"]


CopyFriends = friends.copy()

In [26]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba']

In [27]: # Task: Append a new value "Naimah" into the main list and print both lists

friends.append("Naimah")

In [29]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba']

In [30]: # Task: Append a new value "Mirha" into the copied list and print both list

CopyFriends.append("Mirha")

In [31]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Mirha']

Copy By Reference
In [32]: friends = ["Hareem" , "Hala" , "Inayah" , "Hiba"]
CopyFriends = friends

In [33]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba']

In [34]: # Task: Append a new value "Naimah" into the main list and print both lists

friends.append("Naimah")

In [35]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah']

localhost:8888/notebooks/My First Python Codes.ipynb 22/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [36]: # Task: Append a new value "Mirha" into the copied list and print both list

CopyFriends.append("Mirha")

In [37]: print ("Main List" , friends)


print ("Copied List" , CopyFriends)

Main List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah', 'Mirha']


Copied List ['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah', 'Mirha']

Count
In [ ]: # It will count, how many time any specific value occurs in the list

In [1]: friends = ["Sarah" , "Haniayh" , "Sana" , "Haniayh" , "Zara" , "Fatimah"]

In [2]: # Count how many, times "Haniyah" is in the friends list



friends.count("Haniayh")

Out[2]: 2

In [3]: # Count how many, times "Sana" is in the friends list



friends.count("Sana")

Out[3]: 1

EXTEND
In [4]: # It is use to add multiple values together in the list.

In [5]: friends = ["Hareem" , "Hala" , "Inayah" , "Hiba"]



# Task: add "Naimah" , "Mirha" , "Irha" , "Maham" in the friends list.

# friends.append("Naimah")
# friends.append("Mirha")
# friends.append("Irha")
# friends.append("Maham")

friends.extend(["Naimah" , "Mirha" , "Irha" , "Maham"])

print (friends)

['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah', 'Mirha', 'Irha', 'Maham']

localhost:8888/notebooks/My First Python Codes.ipynb 23/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [22]: friends = ["Hareem" , "Hala" , "Inayah" , "Hiba"]



# Task: add "Naimah" , "Mirha" , "Irha" , "Maham" in the friends list.

new_friends = ["Naimah" , "Mirha" , "Irha" , "Maham"]

friends.extend(new_friends)

print (friends)

['Hareem', 'Hala', 'Inayah', 'Hiba', 'Naimah', 'Mirha', 'Irha', 'Maham']

31 MAR, 2024

INDEX
In [33]: # Return index number of the value

friends = ["Usman" , "Ali" , "Usama" , "Salman"]

# Find out index number of "Usama"

friends.index("Usama")

Out[33]: 2

In [34]: friends.index("Ali")

Out[34]: 1

In [35]: friends.extend(["Usman" , "Nial" , "Mikael" , "Atiq" , "Ali"])

In [36]: friends

Out[36]: ['Usman', 'Ali', 'Usama', 'Salman', 'Usman', 'Nial', 'Mikael', 'Atiq', 'Al
i']

In [37]: # Find index number of "Usman"



friends.index("Usman")

Out[37]: 0

In [38]: friends.count("Usman")

Out[38]: 2

localhost:8888/notebooks/My First Python Codes.ipynb 24/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [39]: # Find the index number of 2nd occurrence of name "Usman"



friends.index("Usman" , friends.index("Usman")+1)

Out[39]: 4

In [40]: friends = ['Ali', 'Usama', 'Salman', 'Usman', 'Nial', 'Mikael', 'Atiq', 'Ali'

In [41]: # Find the index number of 2nd occurrence of name "Usman"



friends.index("Usman" , friends.index("Usman")+1)

Out[41]: 8

In [42]: # Find index number of "Ali"



friends.index("Ali")

Out[42]: 0

In [43]: # Find the index number of 2nd occurrence of name "Ali"



friends.index("Ali" , friends.index("Ali")+1)

Out[43]: 7

In [44]: # Example:
friends = ['Ali', 'Usama', 'Salman', 'Usman', 'Nial', 'Mikael', 'Atiq', 'Ali']

print (friends)

user_input = input("Enter a name to find out it's index number:")

c = friends.count(user_input)

if (c == 0):
print ("Value not found!")
elif (c == 1):
i = friends.index(user_input)
print ("Index no of" , user_input , "is" , i)
elif (c == 2):
print ("2 Values found")
i1 = friends.index(user_input)
print ("Index no of first occurence is" , i1)

i2 = i = friends.index(user_input , i1 + 1)
print ("Index no of 2nd occurence is" , i2)

['Ali', 'Usama', 'Salman', 'Usman', 'Nial', 'Mikael', 'Atiq', 'Ali']


Enter a name to find out it's index number:Ali
2 Values found
Index no of first occurence is 0
Index no of 2nd occurence is 7

localhost:8888/notebooks/My First Python Codes.ipynb 25/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

Pop Function
In [45]: # Pop function is used to remove any value from the list
# It will return you the value
# By defualt, it remves the last value
# It can also remove a value by any index number

# Syntax:
# Variable = ListName.pop() // remove the last value
# Variable = LisrName.pop(index no) // removes the value at given index number

In [46]: students = ["Ibrahim" , "Abaan" , "Haniyah"]



# Task: Remove the last value and print it
# Print the list.

RemovedValue = students.pop()
print ("Removed Value is" , RemovedValue)
print ("Updated list is" , students)

Removed Value is Haniyah


Updated list is ['Ibrahim', 'Abaan']

In [48]: friends = ["Usman" , "Usama" , "Asad" , "Abeera" , "Ibrahim"]



# Task: Remove the value and print it
# Print the list

RemovedValue = friends.pop(3)
print ("Removed Value is" , RemovedValue)
print ("Updated list is" , friends)

Removed Value is Abeera


Updated list is ['Usman', 'Usama', 'Asad', 'Ibrahim']

In [50]: friends = ["Usman" , "Usama" , "Asad" , "Abeera" , "Ibrahim"]



# Task: Remove the value "Ibrahim" and print it
# Print the list

i = friends.index("Ibrahim")
RemovedValue = friends.pop(i)
print ("Removed Value is" , RemovedValue)
print ("Updated list is" , friends)

Removed Value is Ibrahim


Updated list is ['Usman', 'Usama', 'Asad', 'Abeera']

localhost:8888/notebooks/My First Python Codes.ipynb 26/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [51]: Section_A = ["Saad" , "Sadiq" , "Burair"]


Section_B = ["Umair" , "Fatimah"]

# Task:
# Remove "Burair" from Section_A and add it in Section_B.

i = Section_A.index("Burair")
RemovedValue = Section_A.pop(i)

Section_B.append(RemovedValue)

print ("Section_A:" , Section_A)
print ("Section_B:" , Section_B)

Section_A: ['Saad', 'Sadiq']


Section_B: ['Umair', 'Fatimah', 'Burair']

REMOVE
In [52]: # remove function is use to remove any value from the list.
# It will remove Specific value given as parameter.
# It will not return the Value

# Syntax:
# ListName.remove(value)

In [54]: friends = ["Usman" , "Usama" , "Asad" , "Abeera" , "Ibrahim"]


print ("Friends list:" , friends)friends =

Friends list: ['Usman', 'Usama', 'Asad', 'Abeera', 'Ibrahim']

In [55]: # Task: Remove "Asad" from the list.



friends.remove("Asad")
print ("Updated List:" , friends)

Updated List: ['Usman', 'Usama', 'Abeera', 'Ibrahim']

localhost:8888/notebooks/My First Python Codes.ipynb 27/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [57]: # Task:

friends = ["Usman" , "Usama" , "Asad" , "Abeera" , "Ibrahim"]

# Take input a name from user and remove it from the list.

print (friends)
name = input("Enter a name to remove from the list: ")

if (name in friends):
friends.remove(name)
else:
print ("Value not found!")
print ("Updated List:" , friends)

['Usman', 'Usama', 'Asad', 'Abeera', 'Ibrahim']


Enter a name to remove from the list: Haniyah
Value not found!
Updated List: ['Usman', 'Usama', 'Asad', 'Abeera', 'Ibrahim']

REVERSE
In [59]: # It will reverse the order of the list

friends = ["Usman" , "Usama" , "Asad" , "Abeera" , "Ibrahim"]
friends.reverse()

print (friends)

['Ibrahim', 'Abeera', 'Asad', 'Usama', 'Usman']

In [61]: # Example
nums = [0,1,2,3,4,5,6,7,8,9]
nums.reverse()
print (nums)

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

SORT
In [62]: # It will sort the list items in ascending order

In [64]: nums = [9,56,8,94,2,34,56,7,834,786]


nums.sort()
print ("Sorted list:" , nums)

Sorted list: [2, 7, 8, 9, 34, 56, 56, 94, 786, 834]

localhost:8888/notebooks/My First Python Codes.ipynb 28/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [66]: # Sort the list in descending order



nums = [9,56,8,94,2,34,56,7,834,786]
nums.sort(reverse = True)
print ("Sorted list:" , nums)

Sorted list: [834, 786, 94, 56, 56, 34, 9, 8, 7, 2]

In [67]: # Sort the list in descending order



nums = [9,56,8,94,2,34,56,7,834,786]
nums.sort()
nums.reverse()
print ("Sorted list:" , nums)

Sorted list: [834, 786, 94, 56, 56, 34, 9, 8, 7, 2]

localhost:8888/notebooks/My First Python Codes.ipynb 29/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

localhost:8888/notebooks/My First Python Codes.ipynb 30/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [5]: TAsk: Give 1-10 options to the user to select any, and perform the task.
# 1. Create a list of friends(Add your name too).
# 2. Take input a new name from the user and add it in the list.
# 3. Delete your name from the list.
# 4. Take input 3 more names from the user and add it in the list.
# 5. Take input a name from the user and delete it.
# 6. Take input name from the user and find out it's index number.
# 7. Create a copy of the list.
# 8. Sort the list in descending order.
# 9. Print the friends list.
# 10. Print the copied list.


print("1. Create a list of your friends")
print("2. Take input a new friends name from the user and add it in the list."
print("3. Delete your name from the list.")
print("4. Take input 3 more names from the user and add it in the list.")
print("5. Take input a name from the user and delete it.")
print("6. Take input name from the user and find out it's index number.")
print("7. Create a copy of the list.")
print("8. Sort the list in descending order.")
print("9. Print the friends list.")
print("10. Print the copied list.")

option = int(input("Select any option from 1 - 10: "))


if (option == 1):
friends = ["Usman" , "Usama" , "Salman" , "Mubashar"]
print("Task 1: Friends List:" , friends)

elif (option == 2):
new_name = input("Enter a new friend name: ")
friends.append(new_name)
print("Task 2: Friends List:" , friends)

elif (option == 3):
friends.remove("Mubashar")
print("Task 3: Friends List:" , friends)

elif (option == 4):
name1 = input("Enter 1st name: ")
name2 = input("Enter 2nd name: ")
name3 = input("Enter 3rd name: ")
friends.extend([name1 , name2, name3])
print("Task 4: Friends List:" , friends)

elif (option == 5):
name = input("Enter a name to delete: ")
if (name in friends):
friends.remove(name)
else:
print("Value not found!")
print("Task 5: Friends List:" , friends)

elif (option == 6):
name = input("Enter a name to find it's index number: ")
localhost:8888/notebooks/My First Python Codes.ipynb 31/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook
if (name in friends):
i = friends.index(name)
print("Task 6: Index No:" , i)
else:
print("Value not found!")

elif (option == 7):
copy_friends = friends.copy()
print("Task 7: Copied List:" , copy_friends)

elif (option == 8):
friends.sort(reverse = True)
print("Task 8: Friends List:" , friends)

elif (option == 9):
print("Task 9: Friends List:" , friends)

elif (option == 10):
print("Task 10: Copied List:" , copy_friends)

else:
print("Invalid Option")

File <tokenize>:70
print("Task 8: Friends List:" , friends)
^
IndentationError: unindent does not match any outer indentation level

APR 21, 2024

localhost:8888/notebooks/My First Python Codes.ipynb 32/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

localhost:8888/notebooks/My First Python Codes.ipynb 33/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [51]: # Task:
# Create a Blood group directory (having 3 names and their Blood Group)
# and give user an option.
# Press 1 to search Blood Group by name.
# Press 2 to delete a contact by name.
# Press 3 to Blood Group of any contact by name.
# Press 4 to print all the details.
# Press 5 to add any new name and it's Blood Group .
# Hint: Create a separate list of Names and Blood Groups.

Names = ["Abaan" , "Haniyah" , "Ali"]
Blood_Groups = ["B+" , "O-" , "A+"]

print ("Press 1 to search Blood Group by name")
print ("Press 2 to delete a contact by name")
print ("Press 3 to change Blood Group of any contact by name")
print ("Press 4 to print all the details")
print ("Press 5 to add any new name and it's Blood Group")

option = input("Select any option (1 - 5)")

if (option == "1"):
name_input = input("Enter a name:")
if (name_input in Names):
i = Names.index(name_input)
Blood = Blood_Groups[i]
print(name_input , ":" , Blood)
else:
print ("Name is not in the list!")

elif (option == "2"):


name_input = input("Enter a name to delete:")
if (name_input in Names):
i = Names.index(name_input)
Names.pop(i)
Blood_Groups.pop(i)
print (Names , ":" , Blood_Groups)
else:
print ("Name is not in the list!")

elif (option == "3"):


name_input = input("Enter a name to change it's Blood:")
if (name_input in Names):
i = Names.index(name_input)
print (name_input , ":" , Blood_Groups[i])
new_BG = input("Enter new Blood Group: ")
Blood_Groups[i] = new_BG
print (Names , ":" , Blood_Groups)
else:
print ("Name is not in the list!")


elif (option == "4"):
print (Names , ":" , Blood_Groups)


elif (option == "5"):
localhost:8888/notebooks/My First Python Codes.ipynb 34/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook
new_name = input("Enter new contact name: ")
new_BG = input("Enter Blood Group:")
Names.append(new_name)
Blood_Groups.append(new_BG)
print (Names , ":" , Blood_Groups)

else:
("Wrong option selected!")

Press 1 to search Blood Group by name


Press 2 to delete a contact by name
Press 3 to change Blood Group of any contact by name
Press 4 to print all the details
Press 5 to add any new name and it's Blood Group
Select any option (1 - 5)5
Enter new contact name: Maryam
Enter Blood Group:AB+
['Abaan', 'Haniyah', 'Ali', 'Maryam'] : ['B+', 'O-', 'A+', 'AB+']

SLICING
In [1]: nums = [2,4,7,9,12,15,19,24,28,31,39,46,53,72]

# Task: print 4th to 10th value of above list with index number.

print(nums[3] , nums[4] ,nums[5] , nums[6] , nums[7] , nums[8] , nums[9])

9 12 15 19 24 28 31

In [3]: # Slicing will give you all the values of list within its range
# Syntax: ListName[starting index : ending index + 1]
# Slicing will give you the value of starting index
# But, it will not give you value of ending index (will end before it, use + 1

nums = [2,4,7,9,12,15,19,24,28,31,39,46,53,65]

# Task: Print 4th to 10th value of above list with index number.

print(nums[3 : 9 + 1])

[9, 12, 15, 19, 24, 28, 31]

In [5]: # Task: Print 5th to 10th value


print(nums[4 : 10])

[12, 15, 19, 24, 28, 31]

In [7]: # Task: Print 1st to 9th value


print(nums[0 : 9])

[2, 4, 7, 9, 12, 15, 19, 24, 28]

localhost:8888/notebooks/My First Python Codes.ipynb 35/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [9]: # Task: Print 1st to 9th value


print(nums[ : 9])

[2, 4, 7, 9, 12, 15, 19, 24, 28]

In [11]: # Task: Print 3rd value to last value


print(nums[2 : ])

[7, 9, 12, 15, 19, 24, 28, 31, 39, 46, 53, 65]

In [13]: # Task: Print 3rd and last value only



print ("Frist Value" , nums[0])

print ("Last Value" , nums[-1])

Frist Value 2
Last Value 65

In [14]: #index 0 1 2 3 4..............


nums = [2 , 4 , 7 , 9 , 12 , 15 , 19 , 24 , 28 , 31 ]
#index ...................-4 -3 -2 -1

In [16]: # Print 4th Last value



print(nums[-4])

19

In [18]: # Print from the 4th to last value



print(nums[3 : -3 + 1])

[9, 12, 15, 19, 24]

In [19]: # Print last 5 values



print(nums[-5 : ])

[15, 19, 24, 28, 31]

ARL 27, 2024

TUPLE

localhost:8888/notebooks/My First Python Codes.ipynb 36/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [1]: # Difference between tuple and list



#LIST
# We use [] (square brackets)
# List is changable

#TUPLE
# We use () (samll brackets)
# Tuple values are not changable

In [14]: List_Names = ["Haniyah" , "Salahudddin" , "Musab"]


Tuple_Names = ("Haniyah" , "Maryam" , "Musab" , "Shaheedu")

In [15]: print ("List:" , List_Names)


print ("Tuple:" , Tuple_Names)

List: ['Haniyah', 'Salahudddin', 'Musab']


Tuple: ('Haniyah', 'Maryam', 'Musab', 'Shaheedu')

In [16]: # Add a new name Shaheedu in the list



List_Names.append("Shaheedu")
print ("List:" , List_Names)

List: ['Haniyah', 'Salahudddin', 'Musab', 'Shaheedu']

In [8]: # We cannot appened or remove any value in Tuple

Functions of Tuple (count , index)


In [11]: Tuple_Names = ("Shaheedu" , "Haniyah" , "Maryam" , "Inayah" , "Musab" , "Shahe

In [13]: # Task: Take input a name from user and check,


# how many times it appears in the Tuple.

name = input("Enter a name to get it's count:")
Tuple_Names.count(name)

Enter a name to get it's count:Shaheedu

Out[13]: 2

In [33]: # Task: Take input a name from user and find it's index number.

name = input("Enter a name to get it's index no:")
Tuple_Names.index(name)

Enter a name to get it's index no:Musab

Out[33]: 2

localhost:8888/notebooks/My First Python Codes.ipynb 37/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

localhost:8888/notebooks/My First Python Codes.ipynb 38/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [18]: # Account Detailes


#Account1_name = "Haniyah Samad"
#Account1_ATM = "20081029"
#Account1_PIn = "3456"
#Account1_Balance = 90000

#Account2_name = "Muhammad Musab"
#Account2_ATM = "498765"
#Account2_PIn = "9876"
#Account2_Balance =80000

#Account3_name = "Naimah Baji"
#Accont3_ATM = "202026"
#Account3_PIn = "1234"
#Account3_Balance = 70000

#List

#Account1 = ["Haniyah Samad" , "20081029" , "3456" , 90000]
#Account2 = ["Muhammad Musab" , "498765" , "9876" , 80000]
#Account3 = ["Naimah Baji" , "202026" , "1234" , 70000]

# Lists os Lists

Accounts = [["Haniyah Samad" , "20081029" , "3456" , 90000] , ["Muhammad Musab
Name = 0
ATM = 1
PIn = 2
Balnce = 3

# Enter ATM card
user_ATM = input("Please Enter your ATM Card Number:")

# Account_1
if (user_ATM == Accounts[0][ATM]):
print (Accounts[0][Name])
user_PIn = input("Enter your 4-Digit PIn:")
if (user_PIn == Accounts[0][Name]):
option = input ("Press 1 to check Balance , Press 2 to Withdraw Cash."
if (option == "1"):
print ("Your available Balance: Rs" , Accounts[0][Balnce])
elif (option == "2"):
Withdraw_Amount = int(input("Enter Amount to Withdraw:"))
if (Withdraw_Amount <= Accounts[0][Balance]):
Accounts[0][Balance] = Accounts[0][Balance] - Withdraw_Amount
print ("Withdraw Successful")
print ("Take Your ATM Card.")
print ("Take Your Cash.")
print ("Your remaining Balance is" , Accounts[0][Balance])
else:
print ("Insufficient Balance.")
else:
print ("Invalid Balance.")
else:
print ("Wrong PIn Code.")

# elif Account[1]
localhost:8888/notebooks/My First Python Codes.ipynb 39/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

# elif Account[2]

# else

Please Enter your ATM Card Number:20081029


Haniyah Samad
Enter your 4-Digit PIn:3456
Wrong PIn Code.

In [26]: Accounts = [["Haniyah Samad" , "20081029" , "3456" , 90000] , ["Muhammad Musab

In [27]: Accounts[0]

Out[27]: ['Haniyah Samad', '20081029', '3456', 90000]

In [29]: Accounts[2]

Out[29]: ['Naimah Baji', '202026', '1234', 70000]

In [30]: Accounts[0][1]

Out[30]: '20081029'

In [31]: Accounts[1][0]

Out[31]: 'Muhammad Musab'

In [32]: Accounts[0][0]

Out[32]: 'Haniyah Samad'

Loops
In [35]: # Loop is used to repeat any instruction/s multiple times.
# Repitation depends on range of the Loop

localhost:8888/notebooks/My First Python Codes.ipynb 40/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [36]: # Why we need Loops in Python?



print (1 , "Haniyah")
print (2 , "Haniyah")
print (3 , "Haniayh")
print (4 , "Haniyah")
print (5 , "Haniyah")

# But what if we had to repeat it 5000 times

1 Haniyah
2 Haniyah
3 Haniayh
4 Haniyah
5 Haniyah

In [37]: # Types of Loops



# 1. For Loop
# 2. While Loop

FOR LOOP
In [38]: # It will repeat itself until a specific range gets false.

# Syntax:
# for variable in range(repitation value):
# instruction/s

In [41]: # Print your name 5 times with numbering.



for num in range(5):
print ("Haniyah")

Haniyah
Haniyah
Haniyah
Haniyah
Haniyah

In [42]: for num in range(5):


print (num)

0
1
2
3
4

localhost:8888/notebooks/My First Python Codes.ipynb 41/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [43]: for num in range(5):


print (num , "Haniyah")

0 Haniyah
1 Haniyah
2 Haniyah
3 Haniyah
4 Haniyah

In [44]: for num in range(5):


print (num+1 , "Haniyah")

1 Haniyah
2 Haniyah
3 Haniyah
4 Haniyah
5 Haniyah

In [3]: # Take input 5 numbers from user and check each number either it's even/odd

for a in range(5):
num = int(input(f"Enter {a+1} number: "))

if (num % 2 == 0):
print(f"Number {num} is even.")
else:
print(f"Number {num} is odd.")

Enter 1 number: 3
Number 3 is odd.
Enter 2 number: 6
Number 6 is even.
Enter 3 number: 45
Number 45 is odd.
Enter 4 number: 78
Number 78 is even.
Enter 5 number: 23
Number 23 is odd.

localhost:8888/notebooks/My First Python Codes.ipynb 42/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [5]: # Take input a number from user and print it's multiples/tables(upto 10)
# Format: if num is 8 , then print 8 x 1 = 8 ,......

num = int(input("Enter a number to print it's multiples: "))

#print(num*1)
#print(num*2)
#print(num*3)

for a in range(10):
print(f"{num} x {a+1} = {num*(a+1)}")

Enter a number to print it's multiples: 7


7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

MAY 11 , 2024
In [7]: # Range of for loop can be a value, list, string, tuple, etc........

In [1]: # Marks of different students



marks = [90 , 83 , 75 , 100 , 23 , 45]

# Print marks of each students with student numbering.

# Print("Student 1:" , marks[0])
# Print("Student 2:" , marks[1])

num = 1
for a in marks:
print("Student" , num , ":" , a)
num = num + 1

Student 1 : 90
Student 2 : 83
Student 3 : 75
Student 4 : 100
Student 5 : 23
Student 6 : 45

localhost:8888/notebooks/My First Python Codes.ipynb 43/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [2]: num = 1
for a in [90, 82, 67, 45, 76, 23,]:
print("Student" , num , ":" , a)
num = num + 1

Student 1 : 90
Student 2 : 82
Student 3 : 67
Student 4 : 45
Student 5 : 76
Student 6 : 23

In [4]: country = "Pakistan"



for a in country:
print(a)

P
a
k
i
s
t
a
n

In [6]: ​
for a in "Pakistan":
print(a)

P
a
k
i
s
t
a
n

In [8]: for a in ("Pakistan" , "China"):


print(a)

Pakistan
China

localhost:8888/notebooks/My First Python Codes.ipynb 44/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [10]: marks = [90 , 82 , 100 , 45 , 23 , 76 , 99 , 56 , 76]



# Add all marks of student and print his total obtained marks.
# Print the percentage (Total marks: 900)

sum = 0
for a in marks:
sum = sum + a

print("Total Obtained Marks:" , sum)


p = (sum/900) * 100
print ("Percentage:" , int(p) , "%")

Total Obtained Marks: 647


Percentage: 71 %

In [11]: # Add all numbers from 1 tp 100 and print the sum.

sum = 0
for a in range(101):
sum = sum + a
print("Sum =" , sum)

Sum = 5050

WHILE LOOP
In [12]: # It will repeat itself until a specific condition gets false:

# Syntax
# while(condition):
# instruction/s

In [15]: flag = True


while(flag):
print("While Loop")
flag = False

print("Outside while loop.")

While Loop
Outside while loop.

localhost:8888/notebooks/My First Python Codes.ipynb 45/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [17]: num = 0

while(num < 11):
print(num)
num = num + 1

0
1
2
3
4
5
6
7
8
9
10

In [2]: # Simple Calculator



flag = True

while (flag):
num1 = int(input("Enter 1st number:"))
operater = input("+ , - , * , /")
num2 = int(input("Enter 2nd number:"))

if (operater == "+"):
sum = num1 + num2
print ("Sum =" , sum)

elif (operater == "-"):


diff = num1 - num2
print ("Difference =" , diff)

elif (operater == "*"):


product = num1 * num2
print ("Product = " , product)

elif (operater == "/"):


div = num1 / num2
print ("Quotient =" , div)

user_input = input("Press c to continue or Q to quite: ")


if (user_input == "Q"):
flag = False

Enter 1st number:45


+ , - , * , /+
Enter 2nd number:34
Sum = 79
Press c to continue or Q to quite: Q

BREAK STATEMENT
localhost:8888/notebooks/My First Python Codes.ipynb 46/51
5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [3]: # It will end the loop at any iteration

In [3]: # Task: You have a students list having only your name as the first value.
# Use while loop
# Ask the user to either Enter a new student name or "Q" to quite:
# If input is "Q" , end the loop. Else append the value in list.

students = ["Haniyah"]

while(True):
user_input = input("Enter a new student name or 'Q' to quite:")
if (user_input == 'Q'):
break
else:
students.append(user_input)

print(students)

Enter a new student name or 'Q' to quite:Inayah


Enter a new student name or 'Q' to quite:Q
['Haniyah', 'Inayah']

MAY 12 , 2024
In [4]: # It will skip that particular iteration of loop

In [1]: students = ["Haniyah"]



while(True):
user_input = input("Enter a new student name or 'Q' to quite:")
if (user_input == 'Q'):
break
elif (user_input == ""):
continue
else:
students.append(user_input)

print(students)

Enter a new student name or 'Q' to quite:


Enter a new student name or 'Q' to quite:
Enter a new student name or 'Q' to quite:aina
Enter a new student name or 'Q' to quite:saleha
Enter a new student name or 'Q' to quite:
Enter a new student name or 'Q' to quite:
Enter a new student name or 'Q' to quite:naimah
Enter a new student name or 'Q' to quite:
Enter a new student name or 'Q' to quite:Q
['Haniyah', 'aina', 'saleha', 'naimah']

localhost:8888/notebooks/My First Python Codes.ipynb 47/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [6]: nums = [1,2,7,0,45,143,23,96,0,13,45,463]



# Print all the values of list, exept 0.

for a in nums:
if (a == 0):
continue
else:
print(a)

1
2
7
45
143
23
96
13
45
463

UPPER CASE
In [8]: # ALL LETTERS CAPITAL

country = input("Enter your country name:")
print("Your country name is" , country.upper())

Enter your country name:pakistan


Your country name is PAKISTAN

In [10]: students = ["HANIYAH"]



while(True):
user_input = input("Enter a new student name or 'Q' to quite:")
if (user_input == 'Q'):
break
elif (user_input == ""):
continue
else:
students.append(user_input.upper())

print(students)

Enter a new student name or 'Q' to quite:sara


Enter a new student name or 'Q' to quite:samreen
Enter a new student name or 'Q' to quite:Q
['HANIYAH', 'SARA', 'SAMREEN']

lower case

localhost:8888/notebooks/My First Python Codes.ipynb 48/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [12]: # all letters are small



fruit = input("Enter your favourite fruit")
print("your favourite fruit is" , fruit.lower())

Enter your favourite fruitAPPLE


your favourite fruit is apple

In [2]: students = ["HANIYAH"]



while(True):
user_input = input("Enter a new student name or 'Q' to quite:")
if (user_input.lower() == 'q'):
break
elif (user_input == ""):
continue
else:
students.append(user_input.upper())

print(students)

Enter a new student name or 'Q' to quite:inayah


Enter a new student name or 'Q' to quite:musab
Enter a new student name or 'Q' to quite:Q
['HANIYAH', 'INAYAH', 'MUSAB']

Title case
In [14]: # Only First Letter Capital Of Each

country = input("Enter your country name:")
print("Your country name is" , country.title())

Enter your country name:pakistan


Your country name is Pakistan

NESTED LOOP
In [15]: # Loop inside another loop

In [17]: # Task: print numbers from 0 to 5.



for a in range(6):
print(a)

0
1
2
3
4
5

localhost:8888/notebooks/My First Python Codes.ipynb 49/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [18]: # Print numbers from 0 to 5.


# Sequence: print 0 for 0 time , 1 for 1 time , 2 for 2 time and so on........

for a in range(6):
for b in range(a):
print(a)

1
2
2
3
3
3
4
4
4
4
5
5
5
5
5

In [19]: # Task:

# Print

# * * *
# * * *
# * * *

for a in range(5):
print("* * *")

* * *
* * *
* * *
* * *
* * *

localhost:8888/notebooks/My First Python Codes.ipynb 50/51


5/17/24, 10:41 PM My First Python Codes - Jupyter Notebook

In [21]: # Task:
# Take input a number from user and print a square of "*"
# Square is a shape with equal sides.
# Hint: if user enters 3, then.....

# * * *
# * * *
# * * *

size = int(input("Enter size of square: "))

for a in range(size):
for b in range(size):
print("*" , end = " ")

print()

Enter size of square: 5


* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

In [3]: #Print

# *
# * *
# * * *
# * * * *
# * * * * *

In [ ]: ​

localhost:8888/notebooks/My First Python Codes.ipynb 51/51

You might also like