0% found this document useful (0 votes)
8 views

Python-Lec-1

Python is a general-purpose, high-level programming language created by Guido van Rossum, known for its readability and versatility in applications like data science and web development. It features a dynamic typing system, extensive libraries, and a supportive community, making it an ideal choice for beginners and professionals alike. Python's core philosophy emphasizes simplicity and readability, encapsulated in 'The Zen of Python'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python-Lec-1

Python is a general-purpose, high-level programming language created by Guido van Rossum, known for its readability and versatility in applications like data science and web development. It features a dynamic typing system, extensive libraries, and a supportive community, making it an ideal choice for beginners and professionals alike. Python's core philosophy emphasizes simplicity and readability, encapsulated in 'The Zen of Python'.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 94

What is Python?

Python is a general-purpose high-level programming


language and is widely used among the developers’
community.

General Purpose means it can be used for multiple


application such as Data Science, Scripts, Machine Learning,
Desktop Application, Web Application, etc.

High Level Programming Language means human


understandable language (with strong abstraction from the
details of the computer.)
What is Python?

Python was developed by Guido van Rossum in the late


eighties and early nineties at the National Research
Institute for Mathematics and Computer Science in the
Netherlands.

Why is it called Python?


When Guido van Rossum began implementing Python,
was also reading the published scripts from “Monty
Python’s Flying Circus”, a BBC comedy series from the
1970s. Van Rossum thought he needed a name that was
short, unique, and slightly mysterious, so he decided to
call the language Python.
Python version
Python 1.0 (1994 Jan)
Python 2.0 (2000 Oct)
Python 3.0 (2000 Dec)
Python 3.11.4 (6 June 2023)
Python 3.12.7(20 April 2025)

Python does not support backward compatibility as feature in 3.0


were not available in Python 2.0
What is Python?
Python has many reasons for being popular and in
demand. A few of the reasons are mentioned below.
• Emphasis on code readability, shorter codes, ease
of writing.
• Programmers can express logical concepts imparted
with Python fewer lines of code in comparison to
languages such as C++ or Java.
• Python supports multiple programming
paradigms, like object-oriented, imperative and
functional programming or procedural.
• It provides extensive support libraries (Django for
web development, Pandas for data analytics etc.)
• Dynamically typed language(Data type is based on
value assigned)
• Philosophy is “Simplicity is the best”.
What is Python?
The core philosophy of Python is summarized in the
document
The Zen of Python (PEP 20), which includes aphorisms
such as:

• Beautiful is better than ugly.


• Explicit is better than implicit.
• Simple is better than complex.
• Complex is better than complicated.
• Readability counts.

https://peps.python.org/pep-0020
Reasons to learn Python
1. Simplicity

Python is one of the easiest languages to start your


journey. Also, its simplicity does not limit your functional
possibilities.
• Python is a free and open-source language
• Easy-to-learn − Python has few keywords, simple
structure, and a clearly defined syntax. This allows the
student to pick up the language quickly.
• Easy-to-read − Python code is more clearly defined and
visible to the eyes.
• Python is interpreted
• Dynamically typed
Reasons to learn Python
1. Simplicity
• Python is interpreted

It has internal compiler. First interpreter will interpret the code if


error any will notify if not it will execute.
• There are no separate compilation and execution steps
like C and C++.
• Directly run the program from the source code.
• Internally, Python converts the source code into an
intermediate form called bytecodes which is then
translated into native language of specific computer to
run it.
• No need to worry about linking and loading with
libraries, etc.
Reasons to learn Python
1. Simplicity
• Dynamically typed
We do not need to specify the type of the variable while
declaration.
It will implicitly decide what type of values is this and thus will
assign the type at the run time.
Reasons to learn
Python
1. Simplicity
Reasons to learn Python
2. Scalability

Python is a programming language that scales very fast.


Among all available languages, Python is a leader in
scaling. That means that Python has more and more
possibilities.
Saying that Python provides the best options for newbies
because there are many ways to decide the same issue.
Even if you have a team of non-Python programmers, who
knows C+ +design patterns, Python will be better for
them in terms of time needed to develop and verify code
correctness.
It happens fast because you don`t spend your time to find
memory leaks, work for compilation or segmentation
faults.
Reasons to learn Python
3. Libraries and Frameworks

Due to its popularity, Python has hundreds of different


libraries and frameworks which is a great addition to your
development process. They save a lot of manual time and can
easily replace the whole solution.

As a geo-scientist, you will find that many of these libraries


will be focused on data visualization, data analytics, Machine
Learning, etc.
Reasons to learn Python
4. Huge Community

Python has a powerful community. You might think that it


shouldn`t be one of the main reasons why you need to
select Python. But the truth is vice versa.

If you don`t get support from other specialists, your


learning path can be difficult. That`s why you should
know that this won`t happen with your Python learning
journey.
Reasons to learn Python
5. Jobs and Salary

…………………………………..
Application Areas
Getting started
Finding an Interpreter
Before we start Python programming, we need to have an
interpreter to interpret and run our programs.
• There are many interpreters available freely to run
Python scripts like IDLE (Integrated Development
Environment) that comes bundled with the Python
software downloaded from http://python.org.
Examples: Spyder, Pycharm, Jupyter Notebook, etc.
• Online interpreters like https://ide.geeksforgeeks.org
that can be used to run Python programs without
installing an interpreter.
• Anaconda (https://www.anaconda.com) – a distribution
of the Python and R programming languages for
scientific computing, that aims to simplify package
management and deployment.
Visual Studio Code (VS Code)

• Install the latest version of Python


https://www.python.org
• Install VS Code
https://code.visualstudio.com/download

For Mac OS: https://www.youtube.com/watch?v=NirAuEAblvo


For Windows: https://www.youtube.com/watch?v=cUAK4x_7thA
Getting started

•Writing our first program:

•Just type in the following code after you start


the interpreter.

print(“Hello World")
Fundamentals of Python
Python Comments
Comments are useful information that the developers
provide to make the reader understand the source code.
It explains the logic or a part of it used in the code. There
are two types of comment in Python:
• Single line comments: Python single line comment
starts with hashtag symbol with no white spaces.
# This is Comment
Fundamentals of Python
Python Comments
Comments are useful information that the developers
provide to make the reader understand the source code.
It explains the logic or a part of it used in the code. There
are two types of comment in Python:
• Multi-line string as comment:
Python multi-line comment is a piece of text enclosed in
“””a delimiter (“””) on each end of the comment.
This would be a multiline comment
in Python that
spans several lines,
Hanji
“””
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Integers
An integer (int type) is a whole number such as 1, 5, 1350
or -34.
1.5 is not an integer because it has a decimal point.
Numbers with decimal points are floating-point numbers.
Even 1.0 is a floating-point number and not an integer.
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Floating-point numbers
Floating-point numbers (float type) are numbers with a
decimal point or an exponent (or both). Examples are 5.0,
10.24, 0.0, 12. and .3
Fundamentals of Python
Built-in types
There are many kinds of information that a computer can
process, like numbers and characters. In Python (and
other programming languages), the kinds of information
the language is able to handle are known as types. Many
common types are built into Python – for example
integers, floating-point numbers and strings.
Strings
A string (type str) is a sequence of characters.
Strings in python are surrounded by either single
quotation marks, or double quotation marks.
print("Hello")
print('Hello')
Fundamentals of Python
Exercise
Which of the following numbers are valid Python integers?
110, 1.0, 17.5, -39, -2.3, “-1”, 11.0
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
To define a new variable in Python, we simply assign a
value to a label. For example, this is how we create a
variable called count, which contains an integer value of
zero:
# define variable count
count = 0
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
To define a new variable in Python, we simply assign a
value to a label. For example, this is how we create a
variable called count, which contains an integer value of
zero:
# define variable count
count = 0
# redefine variable count
count = 2
Fundamentals of Python
Variables
Variable is a label for a location in memory.
It can be used to hold a value.
Python has some rules that you must follow when forming
an identifier:
• it may only contain letters (uppercase or lowercase),
numbers or the underscore character (_) (no spaces!).
• it may not start with a number.
• it may not be a keyword.
Fundamentals of Python
Variables
Variables in Python are not “statically typed”. We do not
need to declare variables before using them or declare
their type. A variable is created the moment we first
assign a value
# An integer to it.
assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)
Fundamentals of Python
Operators
Operators are the main building block of any
programming language. Operators allow the programmer
to perform different kinds of operations on operands.
These operators can be categorized based upon their
different functionality.
Fundamentals of Python
# Examples of Arithmetic Operator
a=9
Operators b=4
• Arithmetic operators: # Addition of numbers
Arithmetic operators are add = a + b
# Subtraction of numbers
used to perform sub = a - b
mathematical operations # Multiplication of number
like addition, subtraction, mul = a * b
# Division(float) of number
multiplication and division. div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulus (remainder)
mod = a % b
# Exponent (power)
pwr = a ** b
Fundamentals of Python
# Examples of Arithmetic Operator
a=9
Operators b=4
• Arithmetic operators # Addition of numbers
Operator precedence add = a + b
• Python has a specific and predictable # Subtraction of numbers
way to determine the order in which it sub = a - b
performs operations. For integer # Multiplication of number
operations, the system will first handle mul = a * b
brackets (), then **, then *, // and %, # Division(float) of number
and finally + and -. div1 = a / b
# Division(floor) of number
• If an expression contains multiple div2 = a // b
operations which are at the same level # Modulus (remainder)
of precedence, like *, // and %, they mod = a % b
will be performed in order, either from # Exponent (power)
left to right (for left-associative pwr = a ** b
operators) or from right to left (for
right-associative operators).
All these arithmetic operators are left-
associative, except for **, which is
right-associative.
Fundamentals of Python
# Examples of Relational Operators
a = 13
Operators b = 33

• Relational Operators: # a > b is False


Relational operators print(a > b)

compares the values. It # a < b is True


either returns True or False print(a < b)
according to the condition. # a == b is False
• == equal to print(a == b)
• != not equal to
# a != b is True
• > greater than print(a != b)
• < less than
• >= greater than or equal # a >= b is False
print(a >= b)
to
• <= less than or equal to # a <= b is True
print(a <= b)
Fundamentals of Python
Operators
• Logical Operators: # Examples of Logical Operator
Logical operators perform a = True
Logical AND, Logical OR b = False
and Logical NOT # Print a and b is False
operations. print(a and b)

# Print a or b is True
print(a or b)

# Print not a is False


print(not a)
Fundamentals of Python
Exercise
What are the results of the following operations and
explain why:
15 + 20 * 3 = ?
13 // 2 + 3 = ?
31 + 10 // 3 = ?
20 % 7 // 3 = ?
Fundamentals of Python
Basics of data Input
• input(): This function first
takes the input from the
user and then evaluates # input() example
the expression, which name = input(“Enter your name:”)
print(name)
means Python
automatically identifies
whether the user entered a
string or a number or list.
Fundamentals of Python
Python Indentation
Python uses indentation to highlight the blocks of code.
Whitespace is used for indentation in Python. All
statements with the same distance to the right belong to
the same block of code. If a block has to be more deeply
nested, it is simply indented further to the right. You can
understand
# Pythonitprogram
better by looking at the following lines of
showing
code. # indentation
university = ‘CU'

if university == ‘CU’:
print(‘Hi, CU student!')
else:
print(‘The university is not CU')
print('All set !')
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement

mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
elif mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement

mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
else:
if mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Fundamentals of Python
Selection
Selection in Python is made using the two keywords ‘if’
and ‘elif’ and else (elseif)
# Python program to illustrate
# selection statement

mark = 34
if mark >= 80:
print(“Grade is A”)
elif mark >= 65:
print(“Grade is B”)
else:
if mark >= 50:
print(“Grade is C”)
else:
print(“Grade is D”)
Recommended Books and Materials

1. Python Programming: An Introduction to Computer Science


by John M. Zelle, Ph.D.

2. Python Crash Course: A Hands On, Project-Based, Introduction to


Programming
by Eric Matthes

3.https://www. w3schools.com
Let’s Calculate for basic arithmetic operations

a) Write a Python program to add two numbers entered by the user.


b) Write a program to calculate simple interest using the formula:
Simple Interest=

c) Write a Python program to find the average of three numbers.

d) Write a Python program to convert temperature from Celsius to Fahrenheit using: ​


Let’s Calculate the area, circumference of a circle

Equation to calculate area:

Equation to calculate circumference:

Perimeter of a half-circle: +
Let’s Calculate using Python..in a ways
def test1():
pi=3.14
r=float(input("enter the value: "))
area=pi*r*r
print("your area of a circle is:",area)
test1()

import math
def test2():
r=float(input("Enter the second valus of radius: "))
circum=math.pi*2*r
print("The circumference of a circle is:",circum)
test2()
Let’s Calculate using Python..in a ways

import numpy as np # type: ignore


def test3():
r=float(input("Enter the third valus of radius: "))
perimeter=np.pi*r+2*r
print("The perimeter of a semicircle is:",perimeter)
test3()
Global Variables
• Variables that are created outside of a function are known as global
variables
• Global variables can be used by everyone, both inside of functions and
outside
x = "awesome"

def myfunc():
x = "awesome" x = "fantastic"
print("Python is " + x)
def myfunc():
print("Python is " + x) myfunc()

myfunc() print("Python is " + x)


The global Keyword

Normally, when you create a variable inside a function, that variable is


local, and can only be used inside that function.
• To create a global variable inside a function, you can use
the global keyword.

def myfunc(): Also, use the global keyword if you want to change
global x a global variable inside a function.
x = "fantastic"
x = "awesome"
myfunc()
def myfunc():
print("Python is " + x) global x
x = "fantastic"

myfunc()

print("Python is " + x)
Python Numbers, Type Conversion
You can convert from one type to another with
the int(), float(), and complex() methods:
There are three
x = 1 # int
numeric types in y = 2.8 # float
Python: z = 1j # complex
• int #convert from int to float:
a = float(x)
• float
• complex #convert from float to int:
b = int(y)

x = 1 #convert from int to complex:


y = 35656222554887711 c = complex(x)
z = -35.59
p = 3+5j print(a)
print(b)
print(c)
print(type(x))
print(type(y)) print(type(a))
print(type(z)) print(type(b))
print(type(p)) print(type(c))
The Random Number
Python does not have a random() function to make a random
number, but Python has a built-in module called
random that can be used to make random numbers:

import random

print(random.randrange(1, 10))
Python Strings
Strings in python are surrounded by either single quotation marks, or double
quotation marks.
You can assign a multiline string to a variable by using three quotes ””” Or
three single quotes ’’’
a = """Lorem ipsum dolor sit
amet,
consectetur adipiscing elit,
Python does not have a character data type, a
sed do eiusmod tempor incididunt
single character is simply a string with a length
ut labore et dolore magna
of 1.
aliqua."""
Square brackets can be used to access elements
print(a)
of the string.
b = '''Lorem ipsum dolor sit
amet,
consectetur adipiscing elit, a = "Hello, World!"
sed do eiusmod tempor incididunt print(a[1])
ut labore et dolore magna
Strings
we can loop through the characters in a for x in "banana":
string, with a for loop. print(x)

To get the length of a string, use a = "Hello, World!"


the len() function. print(len(a))

txt = "The best things in life


To check if a certain phrase or character is are free!"
present in a string, we can use the print("free" in txt)
keyword in.

txt = "The best things in life are


Use it in an if statement: free!"
if "free" in txt:
print("Yes, 'free' is present.")
Strings
You can return a range of characters by using
the slice syntax.
b = "Hello, World!"
Specify the start index and the end index, print(b[2:5])
separated by a colon, to return a part of the
string.

By leaving out the start index, the range will b = "Hello, World!"
start at the first character: print(b[:5])

By leaving out the end index, the range will b = "Hello, World!"
go to the end: print(b[2:])

Use negative indexes to start the slice


from the end of the string: b = "Hello, World!"
From: "o" in "World!" (position -5) print(b[-5:-2])
to, but not included: "d" in "World!"
(position -2):
Python: Modify Strings
The upper() method returns the string in upper a = "Hello, World!"
case: print(a.upper())

The lower() method returns the string in lower a = "Hello, World!"


case: print(a.lower())

The strip() method removes any whitespace a = " Hello, World! "
from the beginning or the end: print(a.strip())

The replace() method replaces a string with a = "Hello, World!"


another string: print(a.replace("H", "J"))

The split() method splits the string into


a = "Hello, World!"
substrings if it finds instances of the print(a.split(","))
separator:
Python: String Concatenation

To concatenate, or combine, two strings you a = "Hello"


can use the + operator. b = "World"
Merge variable a with variable b into c = a + b
variable c: print(c)

a = "Hello"
To add a space between them, add a " ": b = "World"
c = a + " " + b
print(c)
Python: Format Strings
we cannot combine strings and numbers.
But we can combine strings and numbers by using f-strings or
the format() method!
To specify a string as an f-string, simply put an f in front of the string literal and
add curly brackets {} as placeholders for variables and other operations.

age = 36
txt = f"My name is John, I am {age}"
print(txt)

A placeholder can contain variables, price = 59


operations, functions, and modifiers to format txt = f"The price is {price}
the value. dollars"
print(txt)
Python: Format String
A placeholder can include a modifier to price = 59
format the value. txt = f"The price is {price:.2f}
Display the price with 2 decimals: dollars"
print(txt)

A placeholder can contain Python code, like


math operations:
txt = f"The price is {20 * 59}
dollars"
Perform a math operation in the placeholder,
print(txt)
and return the result:
Escape Characters

The escape character allows you to use double


quotes when you normally would not be
allowed:

txt = "We are the so-called \"Vikings\" from the


north."
String
Methods
String
Methods
String
Methods
Let’s have some fun exercise
😄 1. "Name Flip"
Problem:
Write a program that asks the user for their first and last name and then prints it in reverse order —
like a spy code name.

# Sample Output
# Enter your first name: James
# Enter your last name: Bond
# Output: Hello, Agent Bond James!

🍔 2. "Burger Password Generator"


Problem:
Ask the user their favourite food and lucky number. Then generate a “burger-style” password using
string joining.

# Sample Output
# Favorite food: Pizza
# Lucky number: 7
# Output: Your password is: 🍔Pizza#7!
Let’s have some fun exercise
🤯 3. "Mind Reader"
Problem:
Ask the user to enter a sentence. Show the first word, last word, and the number of words in
the sentence.

# Input: I love pineapple on pizza


# Output:
# First word: I
# Last word: pizza
# Total words: 5
🤖 4. "Robot Speak Translator"
Problem:
Take any sentence from the user and convert all vowels to "🔋" (like a robot would speak!).

# Sample Input: Hello, I am learning Python!


# Output: H🔋ll🔋, 🔋 🔋m l🔋🔋rn🔋ng Pyth🔋n!
Let’s have some fun exercise
👻 5. "Haunted Mirror"
Problem:
Take the user’s name and show it repeated 3 times in reverse with "👻" between
them.

# Sample Input: Sarah


# Output: haraS👻haraS👻haraS

🧪 6. "String Potion Lab"


Problem:
Let students mix strings like potions!

# Input:
# Enter your favorite color: Blue
# Enter your favorite animal: Dragon

# Output: Your magical creature is: Blueragon \


Windows Key + . OR
Windows Key + ; (for Emoji in Win)
Solutions
Control + Command + Space (for Mac)
Change Encoding → Select UTF-8
text = input("Enter a sentence: ")
robot_text = text
for vowel in 'aeiouAEIOU':
first = input("Enter your first name: ")
robot_text = robot_text.replace(vowel, '🔋')
last = input("Enter your last name: ")
print("Robot says:", robot_text)
print("Hello, Agent", last, first + "!")
sentence = input("Enter a sentence: ")

food = input("Favorite food: ") words = sentence.split()


number = input("Lucky number: ") first_word = words[0]
last_word = words[-1]
password = "🍔" + food + "#" + number + "!" total = len(words)
print("Your password is:", password)
print("First word:", first_word)
print("Last word:", last_word)
print("Total words:", total)
Windows Key + . OR
Windows Key + ; (for Emoji in Win)
Solutions
Control + Command + Space (for Mac)
Change Encoding → Select UTF-8

name = input("Enter your name: ")

reversed_name = name[::-1]
ghost_name = f"{reversed_name}👻{reversed_name}👻{reversed_name}"

print("👻 Mirror says:", ghost_name)

color = input("Enter your favorite color: ")


animal = input("Enter your favorite animal: ")

creature = color + animal[1:] # Remove first letter of animal


print("Your magical creature is:", creature, "\")
Python Boolean
print(10 > 9)
print(10 == 9)
You can evaluate any Boolean expression in
print(10 < 9)
Python, and get one of two
answers, True or False. a = 200
b = 33
When you run a condition in an if statement,
if b > a:
Python returns True or False: print("b is greater than a")
else:
print("b is not greater than
a")
• Almost any value is evaluated to True if it
has some sort of content.
• Any string is True, except empty strings. bool("abc")
bool(123)
• Any number is True, except 0. bool(["apple", "cherry", "banana"
• Any list, tuple, set, and dictionary ])
are True, except empty ones.
Python Boolean
def myFunction() :
return True
You can create functions that returns a
Boolean Value: print(myFunction())

def myFunction() :
return True
You can execute code based on the
Boolean answer of a function: if myFunction():
print("YES!")
else:
print("NO!")
Python also has many built-in functions
that return a boolean value, like
the isinstance() function, which can be x = 200
used to determine if an object is of a print(isinstance(x, int
certain data type: ))
Python Operators

Python divides the operators in the following groups:


•Arithmetic operators
•Assignment operators
•Comparison operators
•Logical operators
•Identity operators
•Membership operators
•Bitwise operators
Operator Precendence
Python Collections
Python Lists
To determine how many items a list thislist =
has, use the len() function: ["apple", "banana", "cherry"]
print(len(thislist))

list1 = ["apple", "banana", "cherry"]


List items can be of any data type: list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

It is also possible to use


thislist =
the list() constructor when creating list(("apple", "banana", "cherry"))
a new list. # note the double round-brackets
Using the list() constructor to make a print(thislist)
List:
Python Lists: Access List Items
List items are indexed and you can
thislist =
access them by referring to the
["apple", "banana", "cherry"]
index number: print(thislist[1])
The first item has index 0.

Negative indexing means start from


the end thislist =
-1 refers to the last item, -2 refers ["apple", "banana", "cherry"]
print(thislist[-1])
to the second last item etc.

You can specify a range of indexes by


thislist =
specifying where to start and where ["apple", "banana", "cherry", "orange", "ki
to end the range. wi", "melon", "mango"]
The search will start at index 2 print(thislist[2:5])
(included) and end at index 5 (not
included).
Python Lists: Access List Items
By leaving out the start value, the
thislist =
range will start at the first item. ["apple", "banana", "cherry", "orange
This example returns the items from ", "kiwi", "melon", "mango"]
the beginning to, but NOT including, print(thislist[:4])
"kiwi":

By leaving out the end value, the thislist =


range will go on to the end of the ["apple", "banana", "cherry", "orange
", "kiwi", "melon", "mango"]
list. This example returns the items
print(thislist[2:])
from "cherry" to the end:

thislist = ["apple", "banana", "cherry"]


To determine if a specified item is if "apple" in thislist:
present in a list use the in keyword: print("Yes, 'apple' is in the fruits
list")
Python Lists: Access List Items
By leaving out the start value, the
thislist =
range will start at the first item. ["apple", "banana", "cherry", "orange
This example returns the items from ", "kiwi", "melon", "mango"]
the beginning to, but NOT including, print(thislist[:4])
"kiwi":

By leaving out the end value, the thislist =


range will go on to the end of the ["apple", "banana", "cherry", "orange
", "kiwi", "melon", "mango"]
list. This example returns the items
print(thislist[2:])
from "cherry" to the end:

To determine if a specified item is thislist = ["apple", "banana", "cherry"]


if "apple" in thislist:
present in a list use the in keyword:
print("Yes, 'apple' is in the fruits
list")
Python: Change List Items
thislist =
To change the value of a specific item,
["apple", "banana", "cherry"]
refer to the index number: thislist[1] = "blackcurrant"
print(thislist)
To change the value of items within a thislist =
specific range, define a list with the new ["apple", "banana", "cherry", "orange", "ki
values, and refer to the range of index wi", "mango"]
numbers where you want to insert the thislist[1:3] =
new values: ["blackcurrant", "watermelon"]
print(thislist)

To insert a new list item, without thislist =


replacing any of the existing values, ["apple", "banana", "cherry"]
we can use the insert() method. thislist.insert(2, "watermelon")
print(thislist)
Python: Add List Items
thislist =
To add an item to the end of the list,
["apple", "banana", "cherry"]
use the append() method: thislist.append("orange")
print(thislist)

To append elements from another thislist =


["apple", "banana", "cherry"]
list to the current list, use
tropical =
the extend() method. ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
The extend() method does not have to thislist =
append lists, you can add any ["apple", "banana", "cherry"]
iterable object (tuples, sets, thistuple = ("kiwi", "orange")
dictionaries etc.). thislist.extend(thistuple)
print(thislist)
Python: Remove List Items
thislist =
The remove() method removes the
["apple", "banana", "cherry"]
specified item. thislist.remove("banana")
print(thislist)
thislist =
If there are more than one item with ["apple", "banana", "cherry", "banana
the specified value, the remove() method ", "kiwi"]
removes the first occurrence: thislist.remove("banana")
print(thislist)

The pop() method removes the specified thislist =


index. ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
thislist =
If you do not specify the index, ["apple", "banana", "cherry"]
the pop() method removes the last item. thislist.pop()
print(thislist)
Python: Remove List Items
thislist =
The del keyword also removes the ["apple", "banana", "cherry"]
specified index: del thislist[0]
print(thislist)

The del keyword can also delete the list thislist =


completely. ["apple", "banana", "cherry"]
del thislist

The clear() method empties the list. thislist =


The list still remains, but it has no ["apple", "banana", "cherry"]
content. thislist.clear()
print(thislist)
Python: Loop List
thislist =
You can loop through the list items by
["apple", "banana", "cherry"]
using a for loop: for x in thislist:
print(x)
You can also loop through the list items thislist =
by referring to their index number. ["apple", "banana", "cherry"]
Use the range() and len() functions to for i in range(len(thislist)):
create a suitable iterable. print(thislist[i])
thislist =
["apple", "banana", "cherry"]
You can loop through the list items by i = 0
using a while loop. while i < len(thislist):
print(thislist[i])
i = i + 1
List Comprehension offers the shortest
thislist =
syntax for looping through lists: A short ["apple", "banana", "cherry"]
hand for loop [print(x) for x in thislist]
Let's have some funny problem!

🥇 1. Is the Party Fun?


You are throwing a party and you have:
people = ["Alice", "Bob", "Charlie", "Daisy"]
food = ["Pizza", "Burger", "Salad"]
music = False
Tasks:
•If there are more than 3 people and food list has at least 2 items and music
is True, print "This party is lit!"
•Otherwise, print "Boring party... 😴"
Let's have some funny problem!
🥈 2. Lost Socks Problem
You have a list of socks:
socks = ["Red", "Blue", "Green", "Red", "Blue", "Black"]

Tasks:
Tasks:
•Add a "Yellow" sock to the list.
•Remove one "Red" sock from the list.
•Check if "Pink" sock is in the list. Print a happy face if yes, sad face if no.
•Print out all socks one by one with the message:
"Found a [Color] sock!"
🥉 3. Magical Number Game
Let's have some funny You are a wizard ‍ and you have a list of magic
numbers:
magic_numbers = [2, 5, 8, 11, 14, 17, 20]
Tasks:
•Print only the numbers which are divisible by 2.
problem!

•Multiply each number by 3 and print the new list.


•Remove any number greater than 30.
4. Pet Store Madness
You own a small pet store.
pets = ["dog", "cat", "parrot", "rabbit"]
Tasks:
•A "hamster" arrives. Add it to the list.
•One "cat" runs away. Remove it from the list.
•Check if "dragon" is available in your pet store.
•For every pet in the store, print:
"We have a lovely [pet]!"
5. Treasure Hunt
You are organizing a treasure hunt!
Let's have some funny treasure_spots = ["cave", "beach", "forest", "mountain"]
Tasks:
•Add "desert" to the treasure spots.
•If "beach" is in the list, print " Get your sunscreen ready!"
problem!

•Loop through each spot and print:


"Searching the [spot]..."

🧹 6. Messy Room Problem


Your room is messy.
messy_items = ["socks", "books", "plates", "blanket", "phone", "pen"]
Tasks:
•Remove "plates" (you cleaned them).
•Add "laundry" (you just threw it there 🤣).
•Check if "phone" is still there. If yes, print "At least I can call for help!"
•Loop through all items and print:
"Still messy: [item]"
Solutions!! socks = ["Red", "Blue", "Green", "Red", "Blue",
"Black"]

# Add a Yellow sock


people = ["Alice", "Bob", "Charlie", "Daisy"] socks.append("Yellow")
food = ["Pizza", "Burger", "Salad"]
music = False # Remove one Red sock
socks.remove("Red")
# Let's make the party more fun
music = True # Check if Pink sock is in the list
if "Pink" in socks:
if len(people) > 3 and len(food) >= 2 and print("😊 Found a Pink sock!")
music: else:
print("This party is lit!") print("😢 No Pink sock found.")
else:
print("Boring party... 😴") # Print all socks one by one
for sock in socks:
print(f"Found a {sock} sock!")
Solutions!!
magic_numbers = [2, 5, 8, 11, 14, 17, 20]

# Print numbers divisible by 2


print("Numbers divisible by 2:")
for num in magic_numbers:
if num % 2 == 0:
print(num)

# Multiply each number by 3


magic_times_three = [num * 3 for num in magic_numbers]
print("Magic numbers multiplied by 3:", magic_times_three)

# Remove numbers greater than 30


filtered_numbers = [num for num in magic_times_three if num <= 30]
print("Filtered magic numbers (<=30):", filtered_numbers)
pets = ["dog", "cat", "parrot", "rabbit"] Solutions!!
# Add a hamster
pets.append("hamster") treasure_spots = ["cave", "beach", "forest", "mountain"]

# Remove a cat # Add desert


pets.remove("cat") treasure_spots.append("desert")

# Check if dragon is available # Check for beach


if "dragon" in pets: if "beach" in treasure_spots:
print("We have a dragon! 🐉") print(" Get your sunscreen ready!")
else:
print("No dragons yet... 🥲") # Loop through each spot
for spot in treasure_spots:
# Print all pets print(f"Searching the {spot}...")
for pet in pets:
print(f"We have a lovely {pet}!")
messy_items = ["socks", "books", "plates", "blanket", "phone", "pen"]
Solutions!!
# Remove plates
messy_items.remove("plates")

# Add laundry
messy_items.append("laundry")

# Check if phone is there


if "phone" in messy_items:
print("At least I can call for help!")

# Print all messy items


for item in messy_items:
print(f"Still messy: {item}")

You might also like