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

_Basic guide of Python Programming Language_

This document is a comprehensive tutorial on Python, covering its history, syntax, data types, and practical applications. It includes examples of code, explanations of variables, functions, and data manipulation techniques, making it suitable for both beginners and experienced programmers. Key topics include web development, data analysis, machine learning, and the use of Python libraries.

Uploaded by

delvisgg86
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)
3 views

_Basic guide of Python Programming Language_

This document is a comprehensive tutorial on Python, covering its history, syntax, data types, and practical applications. It includes examples of code, explanations of variables, functions, and data manipulation techniques, making it suitable for both beginners and experienced programmers. Key topics include web development, data analysis, machine learning, and the use of Python libraries.

Uploaded by

delvisgg86
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/ 36

Python Tutorial

Learn Python
• Python is a popular programming language.
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.

An example

print("Hello, world!")

Hello, world!

Python Introduction
Python is a popular programming language. It was created by Guido van Roussum, and released
in 1991.

Python is easy to learn and has a simple syntax. It supports object-oriented programming and
functional programming.

Python is widely used in various fields, including web development, data analysis, machine
learning, and artificial intelligence.

Here are some reasons why Python is popular:

• Easy to learn: Python has a simple syntax and a readable syntax. It is easy to read
and write.

• Easy to read and write: Python's syntax is easy to read and write, making it easy for
beginners and experts to learn.

• Widespread community: Python has a large and active community, which means
there are many resources and support available.

• High-level language: Python is a high-level language, which means it has a simple


and readable syntax, making it easier for programmers to understand and write
code.
It is used for:

• Web development: Python can be used to create web applications, such as web
frameworks like Django and Flask.

• Data analysis: Python can be used to analyze data, such as using libraries like
NumPy and Pandas for data manipulation and analysis.
• Machine learning: Python can be used to build machine learning models, such as
using libraries like TensorFlow and PyTorch for deep learning.

• Artificial intelligence: Python can be used to build artificial intelligence models, such
as using libraries like TensorFlow and PyTorch for deep learning.

• Scientific computing: Python can be used to perform scientific computing, such as


using libraries like NumPy and SciPy for numerical calculations and data analysis.

Python Codes
• To check the version of Python:
import sys

print(sys.version)

3.9.20 (main, Oct 3 2024, 07:38:01) [MSC v.1929 64 bit (AMD64)]

• Execute Python Syntax:


print("Hello, World!")

Hello, World!

• Python Indentation:
if 5 > 2:
print("5 is greater than 2")

5 is greater than 2

if 3 > 2:
print("3 is greater than 2")
if 3 > 2:
print("3 is greater than 3")

3 is greater than 2
3 is greater than 3

• Python Comments:
– Comments in Python are denoted by the # symbol.
– Comments can be placed anywhere in the code, and they are ignored by the
interpreter.
– Comments can span multiple lines, and they can also be used to document code
using the triple quotes.
– Comments can be used to explain the Python code.
# This is a comment.
print("Hello, world!")
print('I love Pakistan.') #This is a comment.

# This is a multiline comment.


# My name is Muhammad Anas.
# I am a student of 9th class.

print("My name is Muhammad Anas.")

Hello, world!
I love Pakistan.
My name is Muhammad Anas.

'''I love Pkaistan, because


I live in Pakistan. I am a student of
BS Artificial Intelligence.'''

print("I am a student of BS Artificial Intelligence.")

I am a student of BS Artificial Intelligence.

Python Variables
Python variables are used to store values. They can be of any data type, such as integers, floats,
complex numbers, strings and other objects that represent values in Python.

• Variable naming rules:


– A variable name must start with a letter or underscore.

– It can contain letters, numbers, and underscores.


– It cannot start with a number.
– Variable names are case-sensitive.
– Variable naming conventions:
– Use lowercase letters and underscores to separate words in variable names.
– Use a single underscore prefix to indicate a private variable (e.g.,
_my_private_variable).
• Variable types:
– Integer: A whole number, e.g., 1, 2, 3,
– Float: A decimal number, e.g., 3.14, -0.5,
– Complex: A number with a real and imaginary part, e.g., 3+4j
– String: A sequence of characters, e.g., "hello", 'hello', "hello world
• Examples
x = 5
y = "Anas"

print(x)
print(y)
5
Anas

• Casting with Examples:


x = str(3)
y = int(4)
z = float(5)

print(x)
print(y)
print(z)

3
4
5.0

• Getting the Types of Variables:


x = 5
y = "Anas"
z = 9.0

print(type(x))
print(type(y))
print(type(z))

<class 'int'>
<class 'str'>
<class 'float'>

c = 'Jhon'

k = "India"

# We can also use the single or double quotes.

print(c)
print(k)

Jhon
India

• Case Sensitive

Variables names are case sensitive. For example, x and X are two different variables.

a = 4
A = 4

print(a)
print(A)

4
4

Variable Names in Python


• Variable names can contain letters, numbers, and underscores.
• Variable names cannot start with a number.
• Variable names are case-sensitive.
• Variable names can be used to store values that can change during the execution of a
program.
• Examples

Legal variables names:

myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John2"

print(myvar)

print(my_var)

print(_my_var)

print(myVar)

print(MYVAR)

print(myvar2)

John
John
John
John
John
John2

# Camel Case Variables:


myVariablesName = "John"

print(myVariablesName)

# Pascal Case Variables:


MyVariablesName = "John"
print(MyVariablesName)

# Snake Case Variables:


my_variables_name = "John"
print(my_variables_name)

John
John
John

Assign Multiple Variables


x, y, z = 1, 2, 3

print(x)

print(y)

1
2

# One variable to multiple variables:


x = y = z = "Mango"

print(x)
print(y)

Mango
Mango

# Unpack a collection of variables

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

fruit1, fruit2, fruit3 = fruits

print(fruit1)
print(fruit2)
print(fruit3)

apple
banana
cherry

#### Output variables

x = "Python is awesome"
print(x)

Python is awesome
x = "Python"
y = "is"
z = "awesome"

print(f"{x} {y} {z}")

Python is awesome

x = "Python"
y = "is"
z = "awesome"
print(x + " " + y + " " + z) # Output: Python is awesom

Python is awesome

x = 5
y = 10
print(x + y)

15

Global Variables
Variables that are created outside of a function (as in all of the examples in the previous pages)
are known as global variables.

x = "awesome"

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

myfunc()

Python is awesome

x = "awesome"

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

print("Python is " + x)

Python is fantastic
Python is awesome

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

Python is fantastic

x = "awesome"

def myfunc():
global x
x = "fantastic"

myfunc()

print("Python is " + x)

Python is fantastic

Python Data Types


Python has several built-in data types that can be used to store and manipulate data. Here are
som e of the most common data types in Python:

1. Integers

Integers are whole numbers, either positive, negative, or zero. They are used to represent counts
or quantities.

Example: 10, -5, 0

2. Floats

Floats are decimal numbers. They are used to represent real numbers, such as measurements or
financial amounts

Example: 3.14, -0.5, 0.0

3. Strings

Strings are sequences of characters, such as words or phrases. They are used to represent text
data.

Example: "Hello", "World", "AI"

4. Booleans

Booleans are true or false values. They are used to represent logical conditions or outcomes.

Example: True, False

5. Lists

Lists are ordered collections of items that can be of any data type, including strings, integers,
floats
Example: [1, 2, 3, "apple", 4.5], []

6. Tuples

Tuples are ordered, immutable collections of items that can be of any data type, including
strings, integers, floats

Example: (1, 2, 3, "apple", 4.5), ()

7. Dictionaries

Dictionaries are unordered collections of key-value pairs. They are used to represent data with
key-value relationships.

Example: {"name": "John", "age": 30, "city": "New York"}, {}

8. Sets

Sets are unordered collections of unique items. They are used to represent data with no
duplicates.

Example: {1, 2, 3, "apple", 4.5}, set()

9. NoneType

NoneType is a special data type in Python that represents the absence of a value.

Example: None

10. Type Conversion

Type conversion is the process of converting a value from one data type to another. Python has
several built in functions for type conversion, such as int(), float(), str(), bool(), list(), tuple(), dict(),
set(), and None.

# interger types:

x = 10
print(type(x))

# String types:
y = "string"
print(type(y))

# float types:
z = 2.5
print(type(z))

# Complex types:

a = 1 + 2j
print(type(a))
# Boolean types:
b = True
print(type(b))

# List types:
c = [1, 2, 3, 4, 5]

print(type(c))

# Tuple types:

d = (1, 2, 3, 4, 5)
print(type(d))

# Dictionary types:
e = {"name": "John", "age": 30}

print(type(e))

# Set types:
f = {1, 2, 3, 4, 5}

print(type(f))

# None type:

g = None

print(type(g))

<class 'int'>
<class 'str'>
<class 'float'>
<class 'complex'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'dict'>
<class 'set'>
<class 'NoneType'>

Python Numbers
Python has several built-in number types, including integers, floating-point numbers, and
complex numbers.

• Integers: These are whole numbers, such as 1, 2, 3, etc.


• Floating-point numbers: These are numbers with decimal points, such as 3.14 or -
• Complex numbers: These are numbers with both real and imaginary parts, such as 3 + 2.
# Integers:

x = 10

print(type(x))

# Floats:
x = 10.5
print(type(x))

# Complex numbers:
x = 3 + 5j

print(type(x))

<class 'int'>
<class 'float'>
<class 'complex'>

Python Casting
# Integers:

x = int(10.5)
print(x)

# Floats:
y = float(19)

print(y)

# Complex numbers:
z = complex(3, 4)

print(z)

10
19.0
(3+4j)

Python Strings
# Simple strings:

x = "Hello, World!"
print(x)

print(type(x))

# Multiline strings:
y = """Hello, World!
This is a multiline string."""
print(y)
print(type(y))

# Strings with escape characters:


z = "Hello, World!\nThis is a new line."
print(z)
print(type(z))

# Strings with unicode characters:


v = "Hello, \u263A World!"
print(v)
print(type(v))

# Strings with binary data:


f = b"Hello, World!"
print(f)

print(type(f))

# Strings with hexadecimal data:


l = b'\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64!'
print(l)
print(type(l))

# Strings with octal data:

j = b'\141\142\143\144\145\146'

print(j)
print(type(j))

# Strings with raw strings:


c = r"Hello, World!\nThis is a new line."

print(c)

print(type(c))

# Strings with f-strings:


n = f"Hello, {42} World!"

print(n)

print(type(n))

# Strings with bytearray data:


m = bytearray(b"Hello, World!")

print(m)
print(type(m))

Hello, World!
<class 'str'>
Hello, World!
This is a multiline string.
<class 'str'>
Hello, World!
This is a new line.
<class 'str'>
Hello, ☺ World!
<class 'str'>
b'Hello, World!'
<class 'bytes'>
b'Hello, World!'
<class 'bytes'>
b'abcdef'
<class 'bytes'>
Hello, World!\nThis is a new line.
<class 'str'>
Hello, 42 World!
<class 'str'>
bytearray(b'Hello, World!')
<class 'bytearray'>

# String length:
x = "Pakistan"
print(len(x))

y = "United States"

print(y[2])

# Check string:
txt = "I am Pakistan"

print("Pakistan" in txt)

# String concatenation:
print("Hello, " + "world!")

# String formatting:

name = "John"

age = 30

print(f"My name is {name}, and I am {age} years old.")


8
i
True
Hello, world!
My name is John, and I am 30 years old.

# Print if statement in a string:


txt = "I am from Pakistan."
if "Pakistan" in txt:
print("Yes, Pakistan is in the text.")

# Not in text format:


t = "I am from Pakistan."
print("English" not in t)

Yes, Pakistan is in the text.


True

Slicing format
# String in slicing format:

x = "Hello, World!, I am Pakistani."

print(x[2:5])

print(x[:5])

print(x[2:])

print(x[-5:])

print(x[::2])

print(x[::-1])

llo
Hello
llo, World!, I am Pakistani.
tani.
Hlo ol! mPksai
.inatsikaP ma I ,!dlroW ,olleH

Modify String
# Modify String:

x = "Hello, World!"

x = x.replace("Hello", "Goodbye")

print(x)
# Upper case:

y = "Hello, World!"
print(y.upper())

# Lower case:
print(y.lower())

# Capitalize:
print(y.capitalize())

# Swap case:
print(y.swapcase())

# Remove leading and trailing whitespaces:

z = " Hello, World! "


print(z.strip())

# Remove leading whitespaces:

print(z.lstrip())
# Remove trailing whitespaces:

print(z.rstrip())

Goodbye, World!
HELLO, WORLD!
hello, world!
Hello, world!
hELLO, wORLD!
Hello, World!
Hello, World!
Hello, World!

Concatenate strings

You can concatenate strings using the + operator.

x = "Pakistani"

y = "World"

print(x + " " + y)

Pakistani World
Format strings
age = 35

name = f"My real age is {age}."

print(name)

# Place holder and modifiers:

name = "John"

age = 35

print(f"My name is {name}, and I am {age} years old.")

# Decimal representation

pi = 3.14159

print(f"Pi is approximately {pi:.2f}.")

# Exponential representation

e = 2.71828

print(f"e is approximately {e:.2e}.")

# Binary representation

b = 10

print(f"Binary representation of {b} is {bin(b)}.")

# Octal representation
octal = 10

print(f"Octal representation of {octal} is {oct(octal)}.")

# Hexadecimal representation
hexa = 10
print(f"Hexadecimal representation of {hexa} is {hex(hexa)}.")

# String formatting with custom separators

name = "John"

age = 35

print(f"{name:10s} {age:5d}")
My real age is 35.
My name is John, and I am 35 years old.
Pi is approximately 3.14.
e is approximately 2.72e+00.
Binary representation of 10 is 0b1010.
Octal representation of 10 is 0o12.
Hexadecimal representation of 10 is 0xa.
John 35

Escape characters
# Python escape characters

print("Hello, World!\nThis is a new line.")

print("Hello, World!\tThis is a tab.")

print("Hello, World!\\This is an escape character.")

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

print(txt)

Hello, World!
This is a new line.
Hello, World! This is a tab.
Hello, World!\This is an escape character.
We are the so-called "Vikings" from the north.

String Methods

String methods are used to manipulate strings. They are used to perform operations such as
concatenation, finding substring, replacing, and more.

# String methods

x = "Hello, World!"
print(x.upper()) # Output: HELLO, WORLD!
print(x.lower()) # Output: hello, world!

print(x.capitalize()) # Output: Hello, world!


print(x.title()) # Output: Hello, World!

print(x.replace("World", "Pakistan")) # Output: Hello, Pakistan!

print(x.split(",")) # Output: ['Hello', ' World!']

print(x.find("World")) # Output: 7
print(x.rfind("World")) # Output: 7

print(x.count("l")) # Output: 3
print(x.startswith("Hello")) # Output: True
print(x.endswith("World!")) # Output: True

print(x.isalnum()) # Output: False

print(x.isalpha()) # Output: False


print(x.isnumeric()) # Output: False

print(x.isspace()) # Output: False

print(x.islower()) # Output: False


print(x.isupper()) # Output: False

print(x.istitle()) # Output: False

HELLO, WORLD!
hello, world!
Hello, world!
Hello, World!
Hello, Pakistan!
['Hello', ' World!']
7
7
3
True
True
False
False
False
False
False
False
True

Python Boolean
Python has a built-in boolean data type that can be used to represent true or false values.

• True: Represents the truth value of a condition that is met.


• False: Represents the truth value of a condition that is not met.
# Python Boolean

print(type(True)) # Output: bool

print(type(False)) # Output: bool

# Examples:

print(10 > 9)
print(10 == 9)

print(10 < 9)

print(10!= 9)

print(True and True)

print(True and False)

print(False and True)

print(False and False)

<class 'bool'>
<class 'bool'>
True
False
False
True
True
False
False
False

def myFunction() :
return True

if myFunction():
print("YES!")
else:
print("NO!")

YES!

Python Operators
Python has a wide range of operators that can be used to perform various operations on data.
Here are some examples

• Arithmetic operators: +, -, *, /, %, //

• Assignment operators: =, +=, -=, *=, /=, %=, //=

• Comparison operators: ==,!=, >, <, >=, <=

• Logical operators: and, or, not

• Bitwise operators: &, |, ^, ~, <<, >>

• Membership operators: in, not in


• Identity operators: is, is not

• Ternary operators: condition? value1 : value2

• Operator precedence: Parentheses, Exponentiation, Multiplication and Division


(from left to right), Addition and Subtraction (from left to right), Bitwise Shift,
Comparison, Logical AND, Logical OR, Logical NOT, Assignment, Ternary

• Operator associativity: Left to right, Right to left

• Operator precedence and associativity can be changed using parentheses.

# Arithmetic operators

print(10 + 3) # Output: 13

print(10 - 3) # Output: 7

print(10 * 3) # Output: 30

print(10 / 3) # Output: 3.3333333333333335

print(10 % 3) # Output: 1

print(10 // 3) # Output: 3

# Assignment operators

x = 10

x += 3 # Output: 13

x -= 3 # Output: 10

x *= 3 # Output: 30

x /= 3 # Output: 10.0

x %= 3 # Output: 1

x //= 3 # Output: 3

# Comparison operators

print(10 > 9) # Output: True

print(10 == 9) # Output: False

print(10 < 9) # Output: False

print(10!= 9) # Output: True


# Logical operators
print(5 > 3 and 3 > 1) # Output: True

print(5 > 3 and 3 < 1) # Output: False

print(5 > 3 or 3 < 1) # Output: True

print(5 > 3 or 3 == 1) # Output: True

print(not (5 > 3 and 3 > 1)) # Output: False

# Bitwise operators
print(5 & 3) # Output: 1

print(5 | 3) # Output: 7

print(5 ^ 3) # Output: 6

print(~5) # Output: -6

print(5 << 1) # Output: 10

print(5 >> 1) # Output: 2

# Membership operators
print(5 in [1, 2, 3, 4, 5])

print(5 not in [1, 2, 3, 4, 5])

# Identity operators

x = 10
y = 10

print(x is y) # Output: True

print(x is not y) # Output: False

# Ternary operator
print("Hello" if 5 > 3 else "World") # Output: Hello

print("World" if 3 > 5 else "Hello") # Output: World

# Operator precedence and associativity

print((5 + 3) * 2) # Output: 16

print(5 + 3 * 2) # Output: 13

print((5 + 3) * (2 + 1)) # Output: 20


print(5 + (3 * 2)) # Output: 11

print(5 + 3 * (2 + 1) / 2) # Output: 7.5

print(5 + (3 * (2 + 1)) // 2) # Output: 6

print(5 + 3 * (2 + 1) % 2) # Output: 1

print(5 + 3 * (2 + 1) ** 2) # Output: 45

print((5 + 3) * 2 + 1) # Output: 17

print(5 + (3 * 2) + 1) # Output: 12

print(5 + 3 * (2 + 1) / 2 + 1) # Output: 8.0

print(5 + (3 * (2 + 1)) // 2 + 1) # Output: 7

print(5 + 3 * (2 + 1) % 2 + 1) # Output: 2

print(5 + 3 * (2 + 1) ** 2 + 1) # Output: 51

# Operator associativity

print(5 + 3 * 2) # Output: 13

print(5 + (3 * 2)) # Output: 13

print((5 + 3) * 2) # Output: 16

print(5 + (3 * 2)) # Output: 13

print(5 + 3 * (2 + 1)) # Output: 18

13
7
30
3.3333333333333335
1
3
True
False
False
True
True
False
True
True
False
1
7
6
-6
10
2
True
False
True
False
Hello
Hello
16
11
24
11
9.5
9
6
32
17
12
10.5
10
7
33
11
11
16
11
14

Python Lists
Python lists are ordered collections of items that can be of any data type, including strings,
integers,

floats, booleans, and even other lists. Lists are created using square brackets ([]).

• Indexing: Lists are zero-indexed, meaning the first item has an index of 0, the second
item has an index of 1, and so on.

• Slicing: Lists can be sliced to extract a subset of items. Slicing is done using the colon
(:) operator. For example, my_list[start:stop:step] returns a new list containing the
items from index start up to but not including index stop, stepping down by step
each time.

• Concatenation: Lists can be concatenated using the + operator. For example, my_list
+ another_list creates a new list containing all the items from both my_list and
another_list.
• Repetition: Lists can be repeated using the * operator. For example, my_list * 3
creates a new list containing all the items from my_list repeated three times.

• Membership: The in operator can be used to check if an item is present in a list. For
example, item in my_list checks if item is in my_list.

• Length: The len() function can be used to get the length of a list. For example,
len(my_list) returns the number of items in my_list.

• Sorting: Lists can be sorted using the sort() method. The sort() method modifies the
original list, and does not return a new list. For example, my_list.sort() sorts the
items in my_list in ascending order.

# Example codes of python lists:

# Creating a list of integers


my_list = [1, 2, 3, 4, 5]
print(my_list) # Output: [1, 2, 3, 4,

# Accessing an item using indexing

print(my_list[0]) # Output: 1

# Slicing a list
print(my_list[1:3]) # Output: [2, 3]

# Concatenating two lists


my_list2 = [6, 7, 8]
print(my_list + my_list2) # Output: [1, 2, 3

# Repeating a list
print(my_list * 2) # Output: [1, 2, 3,

# Checking if an item is in a list


print(5 in my_list) # Output: True
# Checking if an item is not in a list
print(6 not in my_list) # Output: True

# Getting the length of a list

print(len(my_list)) # Output: 5

# Sorting a list in ascending order


print(sorted(my_list)) # Output: [1, 2, 3, 4
# Sorting a list in descending order
print(sorted(my_list, reverse=True)) # Output: [5, 4, 3

# Sorting a list using a custom function


print(sorted(my_list, key=lambda item: len(str(item)))) # Output: [1,
# Removing an item from a list
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]

[1, 2, 3, 4, 5]
1
[2, 3]
[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 1, 2, 3, 4, 5]
True
True
5
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
[1, 2, 4, 5]

Python dictionary
Python dictionaries are unordered collections of key-value pairs. Dictionaries are created using
curly braces ({}) and items are separated by commas.

• Accessing items: Dictionaries can be accessed using keys. For example,


my_dict['key'] retrieves the value associated with the key 'key'.

• Updating items: Dictionaries can be updated by assigning a new value to an existing


key or by adding a new key-value pair. For example, my_dict['key'] = 'value' updates
the value associated with the key 'key' to 'value', and my_dict['new_key'] =
'new_value' adds a new key-value pair with the key 'new_key' and value 'new_value'.

• Deleting items: Dictionaries can be deleted by using the del keyword or by removing
the key-value pair using the pop() method. For example, del my_dict['key'] deletes
the key-value pair associated with the key 'key', and my_dict.pop('key') removes the
key-value pair associated with the key 'key' and returns the value.

• Checking if a key exists: The in operator can be used to check if a key exists in a
dictionary. For example, 'key' in my_dict checks if the key 'key' exists in my_dict.

# Example codes of Python dictionary:

# Creating a dictionary
dict1 = {'name': 'John', 'age': 30, 'city': 'New York', 'country':
'USA'}
print("Dictionary 1: ", dict1)

# Accessing an item
print("Accessing an item: ", dict1['name'])

# Updating an item
dict1['age'] = 31
print("Updating an item: ", dict1)

# Deleting an item
del dict1['city']

print("Deleting an item: ", dict1)

# Checking if a key exists


print("Checking if a key exists: ", 'name' in dict1)

# Adding a new key-value pair

dict1['email'] = '[email protected]'
print("Adding a new key-value pair: ", dict1)

# Removing a key-value pair

dict1.pop('email')
print("Removing a key-value pair: ", dict1)

# Merging two dictionaries

dict2 = {'email': '[email protected]', 'city': 'Los Angeles'}


dict1.update(dict2)
print("Merging two dictionaries: ", dict1)

# Removing all items

dict1.clear()
print("Removing all items: ", dict1)

# Checking if a dictionary is empty


print("Checking if a dictionary is empty: ", dict1 == {})

# Getting the keys and values


print("Getting the keys: ", dict1.keys())

print("Getting the values: ", dict1.values())

# Getting the key-value pairs


print("Getting the key-value pairs: ", dict1.items())

# Checking if a key exists in a dictionary using get() method

print("Checking if a key exists in a dictionary using get(): ",


dict1.get('name'))

print("Checking if a key exists in a dictionary using get(): ",


dict1.get('occupation', 'Not found'))
Dictionary 1: {'name': 'John', 'age': 30, 'city': 'New York',
'country': 'USA'}
Accessing an item: John
Updating an item: {'name': 'John', 'age': 31, 'city': 'New York',
'country': 'USA'}
Deleting an item: {'name': 'John', 'age': 31, 'country': 'USA'}
Checking if a key exists: True
Adding a new key-value pair: {'name': 'John', 'age': 31, 'country':
'USA', 'email': '[email protected]'}
Removing a key-value pair: {'name': 'John', 'age': 31, 'country':
'USA'}
Merging two dictionaries: {'name': 'John', 'age': 31, 'country':
'USA', 'email': '[email protected]', 'city': 'Los Angeles'}
Removing all items: {}
Checking if a dictionary is empty: True
Getting the keys: dict_keys([])
Getting the values: dict_values([])
Getting the key-value pairs: dict_items([])
Checking if a key exists in a dictionary using get(): None
Checking if a key exists in a dictionary using get(): Not found

Python Tuples
Python tuples are ordered collections of items that can be of any data type, including strings,
integers,

floats, booleans, and even other tuples. Tuples are created using parentheses (()) and items are
separated by commas.

• Indexing: Tuples are zero-indexed, meaning the first item has an index of 0, the
second item has an index of 1, and so on.

• Slicing: Tuples can be sliced to extract a subset of items. Slicing is done using the
colon operator (:).

• Concatenation: Tuples can be concatenated using the + operator. For example,


my_tuple + another_tuple creates a new tuple containing all the items from both
my_tuple and another_tuple.

• Repetition: Tuples can be repeated using the * operator. For example, my_tuple * 3
creates a new tuple containing all the items from my_tuple repeated three times.

• Membership: The in operator can be used to check if an item is present in a tuple.


For example, item in my_tuple checks if item is in my_tuple.

• Length: The len() function can be used to get the length of a tuple. For example,
len(my_tuple) returns the number of items in my_tuple.
• Unpacking: Tuples can be unpacked into multiple variables using the asterisk (*)
operator. For example, a, b, c = my_tuple unpacks the items from my_tuple into
variables a, b, and c.

• Immutable: Tuples are immutable, meaning they cannot be changed after they are
created. This means that once a tuple is created, its items cannot be modified.

• Swapping values: Tuples can be used to swap values between two variables without
using a temporary variable. For example, a, b = b, a swaps the values of a and b.

# Example codes of Python in Tupes:


# 1. Tuple creation
tuple1 = (1, 2, 3, 4, 5)
print(tuple1)
# 2. Tuple creation with mixed data types
tuple2 = (1, "Hello", 3.14, True)
print(tuple2)
# 3. Tuple creation with nested tuples
tuple3 = ((1, 2), (3, 4), (5, 6 ))
print(tuple3)
# 4. Tuple creation with dictionary
tuple4 = ({"name": "John", "age": 30}, {"name": "Alice", "age": 25})
print(tuple4)
# 5. Tuple creation with list
tuple5 = ([1, 2, 3], [4, 5, 6 ])
print(tuple5)
# 6. Tuple creation with set
tuple6 = ({1, 2, 3}, {4, 5, 6 })
print(tuple6)
# 7. Tuple creation with string
tuple7 = ("Hello", "World")
print(tuple7)
# 8. Tuple creation with integer
tuple8 = (1, 2, 3, 4, 5)
print(tuple8)
# 9. Tuple creation with float
tuple9 = (1.0, 2.0, 3.0, 4.0, 5.0)
print(tuple9)
# 10. Tuple creation with boolean
tuple10 = (True, False, True, False, True)
print(tuple10)
# 11. Tuple creation with None
tuple11 = (None, None, None, None, None)
print(tuple11)
# 12. Tuple creation with a mix of data types
tuple12 = (1, "Hello", 3.14, True, None)
print(tuple12)
# 13. Tuple creation with a mix of data types and nested tuples
tuple13 = ((1, 2), ("Hello", "World"), (3.14, True, None))
print(tuple13)
# 14. Tuple creation with a mix of data types and nested lists
tuple14 = ([1, 2], ["Hello", "World"], [3.14, True, None])
print(tuple14)
# 15. Tuple creation with a mix of data types and nested sets
tuple15 = ({1, 2}, {"Hello", "World"}, {3.14, True, None})
print(tuple15)
# 16. Tuple creation with a mix of data types and nested dictionaries
tuple16 = ({"name": "John", "age": 30}, {"name": " Alice", "age": 25},
{"name": "Bob", "age": 40})
print(tuple16)
# 17. Tuple creation with a mix of data types and nested tuples with
dictionaries
tuple17 = (({"name": "John", "age": 30}, {"name": " Alice", "age":
25}), ({"name": "Bob", "age": 40 }, {"name": "Charlie", "age": 35}))
print(tuple17)
# 18. Tuple creation with a mix of data types and nested tuples with
lists
tuple18 = (([1, 2], [3, 4]), ([5, 6], [7, 8]))
print(tuple18)

(1, 2, 3, 4, 5)
(1, 'Hello', 3.14, True)
((1, 2), (3, 4), (5, 6))
({'name': 'John', 'age': 30}, {'name': 'Alice', 'age': 25})
([1, 2, 3], [4, 5, 6])
({1, 2, 3}, {4, 5, 6})
('Hello', 'World')
(1, 2, 3, 4, 5)
(1.0, 2.0, 3.0, 4.0, 5.0)
(True, False, True, False, True)
(None, None, None, None, None)
(1, 'Hello', 3.14, True, None)
((1, 2), ('Hello', 'World'), (3.14, True, None))
([1, 2], ['Hello', 'World'], [3.14, True, None])
({1, 2}, {'World', 'Hello'}, {True, 3.14, None})
({'name': 'John', 'age': 30}, {'name': ' Alice', 'age': 25}, {'name':
'Bob', 'age': 40})
(({'name': 'John', 'age': 30}, {'name': ' Alice', 'age': 25}),
({'name': 'Bob', 'age': 40}, {'name': 'Charlie', 'age': 35}))
(([1, 2], [3, 4]), ([5, 6], [7, 8]))

Python Sets
Python sets are unordered collections of unique items. Sets are created using curly braces ({})
and items are separated by commas.

• Indexing: Sets do not support indexing.

• Slicing: Sets do not support slicing.


• Concatenation: Sets can be concatenated using the + operator. For example, my_set
+ another_set creates a new set containing all the items from both my_set and
another_set.

• Repetition: Sets can be repeated using the * operator. For example, my_set * 3
creates a new set containing all the items from my_set repeated three times.

• Membership: The in operator can be used to check if an item is present in a set. For
example, item in my_set checks if item is in my_set.

• Length: The len() function can be used to get the length of a set. For example,
len(my_set) returns the number of items in my_set.

• Unpacking: Sets cannot be unpacked into multiple variables.

• Immutable: Sets are immutable, meaning they cannot be changed after they are
created. This means that once a set is created, its items cannot be modified.

• Union: The union() method returns a new set containing all the items from both
sets. For example, my_set.union(another_set) creates a new set containing all the
items from both my_set and another_set.

# Python sets Examples:

# 1. Creating an empty set


my_set = set()
print(my_set) # Output: set()

# 2. Creating a set with elements


my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: set
# 3. Checking if an item is present in a set
my_set = {1, 2, 3, 4, 5}

print(1 in my_set) # Output: True

print(6 in my_set) # Output: False

# 4. Adding an item to a set

my_set = {1, 2, 3, 4, 5}

my_set.add(6)

print(my_set) # Output: set({1, 2, 3, 4, 5, 6})

# 5. Removing an item from a set


my_set = {1, 2, 3, 4, 5}
my_set.remove(3)
print(my_set) # Output: set({1, 2, 4, 5})

# 6. Removing an item from a set using the discard() method


my_set = {1, 2, 3, 4, 5}

my_set.discard(3)

print(my_set) # Output: set({1, 2, 4, 5})


# 7. Removing all items from a set using the clear() method
my_set = {1, 2, 3, 4, 5}

my_set.clear()
print(my_set) # Output: set()

# 8. Union of two sets


my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}

union_set = my_set1.union(my_set2)
print(union_set) # Output: set({1, 2, 3,

# 10. Intersection of two sets


my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}

intersection_set = my_set1.intersection(my_set2)

print(intersection_set) # Output: set({4, 5})

# 11. Difference between two sets

my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}

difference_set = my_set1.difference(my_set2)

print(difference_set) # Output: set({1, 2, 3})

# 12. Symmetric difference between two sets


my_set1 = {1, 2, 3, 4, 5}

my_set2 = {4, 5, 6, 7, 8}

symmetric_difference_set = my_set1.symmetric_difference(my_set2)

print(symmetric_difference_set) # Output: set({1, 2, 3, 6, 7, 8})

# 13. Checking if two sets are disjoint


my_set1 = {1, 2, 3, 4, 5}
my_set2 = {6, 7, 8, 9, 10}
is_disjoint = my_set1.isdisjoint(my_set2)

print(is_disjoint) # Output: True

set()
{1, 2, 3, 4, 5}
True
False
{1, 2, 3, 4, 5, 6}
{1, 2, 4, 5}
{1, 2, 4, 5}
set()
{1, 2, 3, 4, 5, 6, 7, 8}
{4, 5}
{1, 2, 3}
{1, 2, 3, 6, 7, 8}
True

Python If-Else Conditions


Python if-else statements are used to control the flow of a program based on a condition. If the
condition is true, the code inside the if block is executed. If the condition is false, the code inside
the else block is executed.

• Syntax:

if condition:

code block 1

else:

code block 2

# Python if-else statements

# 1. Simple if-else statement


if 5 > 3:
print("Condition is true")
else:
print("Condition is false")

Condition is true

# 2. Nested if-else statement


num = 5
if num > 10:
print("Number is greater than 10")
elif num == 5:
print("Number is equal to 5")

Number is equal to 5

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

Number is odd

# If-else or Condition

# 1. Using if-else statement


def if_else_example():
x = 5
if x > 3:
print("x is greater than 3")
return True
else:
print("x is less than or equal to 3")
return False

Python While-Loop Conditions


Python while loops are used to repeat a block of code as long as a condition is true.

• Syntax:

while condition:

code block

increment/decrement statement

# Python While-loop condition example:

# The while loop will continue to execute as long as the condition is


true.
i = 0
while i < 5:
print(i)
i += 1

0
1
2
3
4
# Else statements in while loops with python code:

# The while loop will continue to execute as long as the condition is


true.
i = 0

while i < 5:
print(i)
i += 1
# Break the loop if the user enters 0
if i == 3:
break
# Continue the loop if the user enters 5
elif i == 5:
continue
# Print a message if the user enters a negative number
elif i < 0:
print("Invalid input. Please enter a positive number.")
else:
print("Number is valid.")

0
Number is valid.
1
Number is valid.
2

Python For-Loop
Python for loops are used to iterate over a sequence (such as a list, tuple, or string) or other
iterable objects.

• Syntax:

for variable in sequence:

code block

increment/decrement statement

break statement

continue statement

else:

code block when loop completes without a break statement

finally:

code block that will always be executed regardless of the loop's termination
# Python For-Loop Statements

# 1. Printing numbers from 0 to 9 using a for loop


for i in range(10):
print(i)
# Break the loop if the user enters 5
if i == 5:
break
# Continue the loop if the user enters 7
elif i == 7:
continue
# Print a message if the user enters a negative number
elif i < 0:
print("Invalid input. Please enter a positive number.")
else:
print("Number is valid.")

0
Number is valid.
1
Number is valid.
2
Number is valid.
3
Number is valid.
4
Number is valid.
5

Python Functions
Python functions are reusable blocks of code that perform a specific task. They are defined using
the def keyword.

• Syntax:

def function_name(parameter1, parameter2,...):

function_body

return value

# Python functions with Code Examples:

# 1. Defining a function that takes two parameters and returns their


sum
def add_numbers(a, b):
return a + b
# Example usage: add_numbers(5, 7) returns 12
# 2. Defining a function that takes a list of numbers and returns
their average

def calculate_average(numbers):
return sum(numbers) / len(numbers)
# Example usage: calculate_average([1, 2, 3, 4, 5
# 3. Defining a function that takes a string and returns its length
def string_length(s):
return len(s)

# Example usage: string_length("Hello, World!") returns 12


# 4. Defining a function that takes a list of strings and returns the
longest string
def longest_string(strings):
return max(strings, key=len)
# Example usage: longest_string(["apple", "banana", "cherry"]) returns
"banana"
# 5. Defining a function that takes a list of numbers and returns the
maximum number
def max_number(numbers):
return max(numbers)
# Example usage: max_number([1, 2, 3, 4, 5 * 10])
# 6. Defining a function that takes a list of numbers and returns the
minimum number
def min_number(numbers):
return min(numbers)

# Example usage: min_number([1, 2, 3, 4, 5 * 10]) returns 1


# 7. Defining a function that takes a list of numbers and returns the
sum of all
# numbers greater than 5
def sum_greater_than_five(numbers):
return sum(num for num in numbers if num > 5)

# Example usage: sum_greater_than_five([1, 2, 3, 4, 5, 6, 7, 8, 9,


10]) returns 45

# 8. Defining a function that takes a list of numbers and returns the


average of all
# numbers greater than 5
def average_greater_than_five(numbers):
return sum_greater_than_five(numbers) / len(numbers)
# Example usage: average_greater_than_five([1, 2, 3, 4,
# 9. Defining a function that takes a list of numbers and returns the
sum of all
# numbers less than or equal to 5
def sum_less_than_or_equal_to_five(numbers):
return sum(num for num in numbers if num <= 5)
# Example usage: sum_less_than_or_equal_to_five([1, 2, 3, 4])

You might also like