_Basic guide of Python Programming Language_
_Basic guide of Python Programming Language_
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.
• 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.
• 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.
Python Codes
• To check the version of Python:
import sys
print(sys.version)
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.
Hello, world!
I love Pakistan.
My name is Muhammad Anas.
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.
print(x)
print(y)
5
Anas
print(x)
print(y)
print(z)
3
4
5.0
print(type(x))
print(type(y))
print(type(z))
<class 'int'>
<class 'str'>
<class 'float'>
c = 'Jhon'
k = "India"
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
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
print(myVariablesName)
John
John
John
print(x)
print(y)
1
2
print(x)
print(y)
Mango
Mango
print(fruit1)
print(fruit2)
print(fruit3)
apple
banana
cherry
x = "Python is awesome"
print(x)
Python is awesome
x = "Python"
y = "is"
z = "awesome"
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
1. Integers
Integers are whole numbers, either positive, negative, or zero. They are used to represent counts
or quantities.
2. Floats
Floats are decimal numbers. They are used to represent real numbers, such as measurements or
financial amounts
3. Strings
Strings are sequences of characters, such as words or phrases. They are used to represent text
data.
4. Booleans
Booleans are true or false values. They are used to represent logical conditions or outcomes.
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
7. Dictionaries
Dictionaries are unordered collections of key-value pairs. They are used to represent data with
key-value relationships.
8. Sets
Sets are unordered collections of unique items. They are used to represent data with no
duplicates.
9. NoneType
NoneType is a special data type in Python that represents the absence of a value.
Example: None
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.
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))
print(type(f))
j = b'\141\142\143\144\145\146'
print(j)
print(type(j))
print(c)
print(type(c))
print(n)
print(type(n))
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
Slicing format
# String in slicing format:
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())
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
x = "Pakistani"
y = "World"
Pakistani World
Format strings
age = 35
print(name)
name = "John"
age = 35
# Decimal representation
pi = 3.14159
# Exponential representation
e = 2.71828
# Binary representation
b = 10
# Octal representation
octal = 10
# Hexadecimal representation
hexa = 10
print(f"Hexadecimal representation of {hexa} is {hex(hexa)}.")
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(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.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
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.
# Examples:
print(10 > 9)
print(10 == 9)
print(10 < 9)
print(10!= 9)
<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: +, -, *, /, %, //
# Arithmetic operators
print(10 + 3) # Output: 13
print(10 - 3) # Output: 7
print(10 * 3) # Output: 30
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
# Bitwise operators
print(5 & 3) # Output: 1
print(5 | 3) # Output: 7
print(5 ^ 3) # Output: 6
print(~5) # Output: -6
# Membership operators
print(5 in [1, 2, 3, 4, 5])
# Identity operators
x = 10
y = 10
# Ternary operator
print("Hello" if 5 > 3 else "World") # Output: Hello
print((5 + 3) * 2) # Output: 16
print(5 + 3 * 2) # Output: 13
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: 2
print(5 + 3 * (2 + 1) ** 2 + 1) # Output: 51
# Operator associativity
print(5 + 3 * 2) # Output: 13
print((5 + 3) * 2) # Output: 16
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.
print(my_list[0]) # Output: 1
# Slicing a list
print(my_list[1:3]) # Output: [2, 3]
# Repeating a list
print(my_list * 2) # Output: [1, 2, 3,
print(len(my_list)) # Output: 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.
• 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.
# 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']
dict1['email'] = '[email protected]'
print("Adding a new key-value pair: ", dict1)
dict1.pop('email')
print("Removing a key-value pair: ", dict1)
dict1.clear()
print("Removing all items: ", dict1)
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 (:).
• 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.
• 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.
(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.
• 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.
• 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.
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
my_set.discard(3)
my_set.clear()
print(my_set) # Output: set()
union_set = my_set1.union(my_set2)
print(union_set) # Output: set({1, 2, 3,
intersection_set = my_set1.intersection(my_set2)
my_set1 = {1, 2, 3, 4, 5}
my_set2 = {4, 5, 6, 7, 8}
difference_set = my_set1.difference(my_set2)
my_set2 = {4, 5, 6, 7, 8}
symmetric_difference_set = my_set1.symmetric_difference(my_set2)
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
• Syntax:
if condition:
code block 1
else:
code block 2
Condition is true
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
• Syntax:
while condition:
code block
increment/decrement statement
0
1
2
3
4
# Else statements in while loops with python code:
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:
code block
increment/decrement statement
break statement
continue statement
else:
finally:
code block that will always be executed regardless of the loop's termination
# Python For-Loop Statements
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:
function_body
return value
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)