Introduction#
What is Python?#
Python is a high-level, interpreted programming language known for its simplicity and readability. It was created by Guido van Rossum and first released in 1991. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming styles.
Here are some key features and uses of Python:#
Simple and Readable Syntax: Python has a clean and easy-to-understand syntax, which makes it accessible for beginners and experienced programmers alike. It emphasizes readability, reducing the cost of program maintenance and development.
Versatility: Python is a versatile language used in various domains such as web development, data analysis, artificial intelligence, machine learning, scientific computing, automation, and more. Its extensive standard library provides support for many common tasks and protocols.
Large Ecosystem: Python has a rich ecosystem with a wide range of libraries and frameworks that facilitate development across different domains. For example, Django and Flask are popular frameworks for web development, while NumPy and pandas are widely used for data analysis and manipulation.
Interpreted and Interactive: Python is an interpreted language, meaning that code is executed line by line. This makes it suitable for rapid prototyping and testing. Additionally, Python supports interactive mode, allowing users to execute code interactively and get immediate feedback.
Cross-platform: Python is available on multiple platforms, including Windows, macOS, and Linux. This ensures that code written in Python can be run on different operating systems without modification.
Community and Support: Python has a large and active community of developers who contribute to its development, share knowledge, and provide support through forums, mailing lists, and other channels. This vibrant community contributes to the continuous improvement and evolution of the language.
Open Source: Python is open-source software, which means that its source code is freely available and can be modified and distributed by anyone. This fosters collaboration and innovation within the Python community.
Overall, Python’s simplicity, versatility, and strong community support make it a popular choice for a wide range of programming tasks, from simple scripting to complex software development projects.
1. Python Output#
print('Hello World')
Hello World
# Python is a case sensitive language
print('Hello World')
Hello World
print('Pakistan')
Pakistan
print(pakistan)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[4], line 1
----> 1 print(pakistan)
NameError: name 'pakistan' is not defined
print(7)
7
print(34+5)
39
print('34+5')
34+5
print(7.7)
7.7
print(True)
True
print('Hello',1,4.5,True)
Hello 1 4.5 True
print('Hello',1,4.5,True , sep='!')
Hello!1!4.5!True
print('hello')
print('world')
hello
world
print('hello',end='-')
print('world', end='-')
print("Pakistan")
hello-world-Pakistan
2. Data Types#
# Integer
print(8)
# 1*10^308
print(1e309)
8
inf
# Decimal/Float
print(8.55)
print(1.7e309)
8.55
inf
# Boolean
print(True)
print(False)
True
False
# Text/String
print('Hello World')
Hello World
# complex
print(5+6j)
(5+6j)
# List-> C-> Array
print([1,2,3,4,5])
[1, 2, 3, 4, 5]
# Tuple
print((1,2,3,4,5))
(1, 2, 3, 4, 5)
# Sets
print({1,2,3,4,5})
{1, 2, 3, 4, 5}
# Dictionary
print({'name':'Fahad','gender':'Male','weight':70})
{'name': 'Fahad', 'gender': 'Male', 'weight': 70}
# type
type([1,2,3])
list
type("Pakistan")
str
type({'name':'Fahad','gender':'Male','weight':70})
dict
3. Operators#
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Membership Operators
print(5/2)
2.5
print(5//2)
2
# Arithmetric Operators
print(5+6) # Addidtion
print(5-6) # Subtraction
print(5*6) # Multiplication
print(5/2) # Division (After divion give float)
print(5//2) # Floor Division (After division give integer)
print(5%2) # Modulo
print(5**2) # Exponent
11
-1
30
2.5
2
1
25
# Relational Operators
print(4>5) # Greater than
print(4<5) # Less than
print(4>=4) # Greater than or equal
print(4<=4) # Less than or equal
print(4==4) # Equal
print(4!=4) # Not Equal
False
True
True
True
True
False
# Logical Operators
print(1 and 0)
print(1 or 0)
print(not 1)
0
1
False
# Bitwise Operators
# bitwise and
print(2 & 3) # Give the value after solving it in binary
# bitwise or
print(2 | 3)
# # bitwise xor
print(2 ^ 3) # xor me jab same hoga to 0 and jab different hoga to 1
2
3
1
# Assignment Operators
# =
a = 3
# # a = a + 2
a *= 2
print(a)
6
# Membership Operators
# in/not in
print('L' not in 'Lahore')
print(1 in [2,3,4,5,6])
False
False
4. Variables#
# Static Vs Dynamic Typing
# Static Vs Dynamic Binding
# stylish declaration techniques
# C/C++
name = 'Fahad'
print(name)
a = 5
b = 6
a = 7
print(a + b)
Fahad
13
# Dynamic Typing
a = 5
# Static Typing
# int a = 5
# Dynamic Binding
a = 5
print(a)
a = 'Fahad'
print(a)
# Static Binding
# int a = 5
5
Fahad
a = 1
b = 2
c = 3
print(a,b,c)
1 2 3
a,b,c = 1,2,3
print(a,b,c)
1 2 3
a=b=c= 5
print(a,b,c)
5 5 5
Pros of variable#
It reduces the human effort.
Easy to write for long datasets.
Easy to recall.
Examples of variable naming conventions:#
Only those jo python ki apni zuban main nahi hyn
Reserved words in Python:
False class finally is return
None continue for lambda tr
True def from nonlocal while
and del global not with
as elif if or yield
assert else import pass
break except in raiseUse underscores instead of spaces
variable_name = “example”Avoid capitalizing variable names
variable_name = “example”Use short words (maximum 2) for variable names
x = 10, y = “hello”Avoid using special characters in variable names
variable_name = “example”Avoid starting variable names with numbers
variable_name = “example”Avoid using special characters in variable names
variable_name = “example”Meaningful
Global trends (df=dataframe)
Don’t ever repeat the same variable (pehly wala update ho jana he)
Don’t use operators (+.-,,/,**)
x = 2+3+9-912*(2/3)
5. Keywords#
Keywords in Python are reserved words that have special meaning and are used to define the syntax and structure of the language. These keywords cannot be used as identifiers (such as variable names or function names) because they have predefined meanings within the language.
Here are some examples of Python keywords:
if, else, elif: Used for conditional statements.
while, for: Used for loops.
def, return: Used for defining functions and returning values.
class, self: Used for defining classes and referring to instance variables.
import, from, as: Used for importing modules and renaming identifiers.
try, except, finally: Used for exception handling.
and, or, not: Used for logical operations.
True, False, None: Used for boolean values and null objects.
6. String Operations#
Strings are sequence of Characters
In Python specifically, strings are a sequence of Unicode Characters
Creating Strings
Accessing Strings
Adding Chars to Strings
Editing Strings
Deleting Strings
Operations on Strings
String Functions
Creating Stings#
s = 'hello'
s = "hello"
# multiline strings
s = '''hello'''
s = """hello"""
s = str('hello')
print(s)
hello
"it's raining outside"
"it's raining outside"
Accessing Substrings from a String#
# Positive Indexing
s = 'hello world'
print(s[6])
w
# Negative Indexing
s = 'hello world'
print(s[-5])
w
# Slicing (1 se ziada character ko extract karne ke liye)
s = 'hello world'
print(s[2:6])
llo
# Skip last number
s = 'hello world'
print(s[4:])
o world
# Skip first number
s = 'hello world'
print(s[:7])
hello w
# Skip both number
s = 'hello world'
print(s[:])
hello world
# Step Size
s = 'hello world'
print(s[0:8:3])
hlw
# Negative Step Size
s = 'hello world'
print(s[6:0:-2])
wol
# Reverse the string
s = 'hello world'
print(s[::-1])
dlrow olleh
# Reverse Negative Slicing
s = 'hello world'
print(s[-1:-6:-2])
drw
Editing and Deleting in Strings#
s = 'hello world'
s[0] = 'H'
# Python strings are immutable (change ni ho sakta)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[56], line 2
1 s = 'hello world'
----> 2 s[0] = 'H'
4 # Python strings are immutable (change ni ho sakta)
TypeError: 'str' object does not support item assignment
s = 'hello world'
del s
print(s)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[57], line 3
1 s = 'hello world'
2 del s
----> 3 print(s)
NameError: name 's' is not defined
s = 'hello world'
del s[-1:-5:2]
print(s)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[58], line 2
1 s = 'hello world'
----> 2 del s[-1:-5:2]
3 print(s)
TypeError: 'str' object does not support item deletion
Operations on Strings#
Arithmetic Operations
Relational Operations
Logical Operations
Loops on Strings
Membership Operations
print('Lahore' + ' ' + 'Karachi')
Lahore Karachi
print('Lahore'*5)
LahoreLahoreLahoreLahoreLahore
'lahore' == 'Lahore'
False
'Karachi' > 'karachi'
# lexiographically (compare through character ASCII)
False
'hello' and 'world'
'world'
'world' and 'hello'
'hello'
'hello' or 'world'
'hello'
'' and 'world'
''
'' or 'world'
'world'
'hello' or 'world'
'hello'
not 'hello'
False
for i in 'hello':
print(i)
h
e
l
l
o
for i in 'lahore':
print('karachi')
karachi
karachi
karachi
karachi
karachi
karachi
'L' in 'Lahore'
True
Common Functions#
len
max
min
sorted
len('hello world')
11
max('hello world')
'w'
min('hello world')
' '
sorted('hello world',reverse=True)
['w', 'r', 'o', 'o', 'l', 'l', 'l', 'h', 'e', 'd', ' ']
Capitalize#
Title
Upper
Lower
Swapcase
s = 'hello world'
print(s.capitalize())
Hello world
s.title()
'Hello World'
s.upper()
'HELLO WORLD'
'Hello Wolrd'.lower()
'hello wolrd'
'HeLlO WorLD'.swapcase()
'hElLo wORld'
Split/Join#
'hi my name is Fahad'.split()
['hi', 'my', 'name', 'is', 'Fahad']
" / ".join(['hi', 'my', 'name', 'is', 'Fahad'])
'hi / my / name / is / Fahad'
Strip#
# To remove space between the words
'Fahad '.strip()
'Fahad'
'Hello World '.strip()
'Hello World'
Replace#
'hi my name is Fahad'.replace('Fahad','EDU')
'hi my name is EDU'
7. Input#
input('Enter email')
'fahad1078397@gmail.com'
# take input from users and store them in a variable
num1 = int(input('enter first number'))
num2 = int(input('enter second number'))
# add the 2 variables
result = num1 + num2
# print the result
print(result)
print(type(num1))
16
<class 'int'>
46
<class 'int'>
8. Type Casting (Conversion)#
# Implicit Vs Explicit
#Implicit
print(5+5.6)
print(type(5),type(5.6))
print(4 + '4')
10.6
<class 'int'> <class 'float'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[90], line 6
3 print(5+5.6)
4 print(type(5),type(5.6))
----> 6 print(4 + '4')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
# Explicit
# str -> int
#int(4+5j)
# int to str
str(5)
# float
float(4)
4.0
9. Comments#
# this is a comment
# second line
a = 4
b = 6 # like this
# second comment
print(a+b)
10