Python_S2AIDS_1st_Class
Python_S2AIDS_1st_Class
Comments are essential for defining the code and help us and other to understand the code
hello world
hello world
hai
10
print() : function to display the message on the screen. the message can be string integer, float
Example to Create Python Variables This example creates different types (an integer, a float, and
a string) of variables.
# Integer
x = 10
# Float
y = 3.14
# String
message = "Hello, World!"
# Boolean
is_active = True
# List
numbers = [1, 2, 3, 4, 5]
In the above example, 1st line if we take =10 it takes the value 10 and assign the value to the
variable name x
Age=25
age=30
print("Age :",Age,"age : ",age)
HAPPY="HH"
happy="jj"
print("hello :",HAPPY,"happy: ",happy)
Age : 25 age : 30
hello : HH happy: jj
----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[17], line 1
----> 1 print(h) # Attempting to print an undefined variable 'x'
Python has the following data types built-in by default, in these categories:
1.Numbers
1. Sequence Type
2. Boolean
3. Set
4. Dictionary
#str
x = "Hello World"
#int
x = 20
#float
x = 20.5
#complex
x = 1j
#list
x = ["apple", "banana", "cherry"]
#tuple
x = ("apple", "banana", "cherry")
#range
x = range(6)
#dict
x = {"name" : "John", "age" : 36}
#set
x = {"apple", "banana", "cherry"}
#frozenset
x = frozenset({"apple", "banana", "cherry"})
#bool
x = True
#bytes
x = b"Hello"
#bytearray
x = bytearray(5)
#Nonetype
x = None
x = bytearray(5)
print(x)
bytearray(b'\x00\x00\x00\x00\x00')
'mnb'
a=input("enter...")
print(a)
enter... a
f-Strings
New since Python 3.6. Use the variables directly inside the braces.
name = "Eric"
age = 25
a = f"Hello, {name}. You are {age}."
print(a)
pi = 3.14159
a = f"Pi is {pi:.3f}"
print(a)
# f-Strings are evaluated at runtime, which allows expressions
a = f"The value is {2*60}"
print(a)
Hello, Eric. You are 25.
Pi is 3.142
The value is 120
a=12.0
type(a) # type() specifiy what type of datatype the variable is using
float
ch="z"
type(ch)
str
str="python program"
print(str)
python program
type(str)
str
w=True
type(w)
bool
Python Keywords
In Python, keywords are reserved words that have special meaning and cannot be used as
identifiers (such as variable names, function names, etc.).
print(keyword.kwlist)
Python Strings
In python strings are a sequence of characters.
For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.
welcome to string
welcome to string
1. Indexing
2. Negative Indexing
3. Slicing
str = "HELLOWORLD"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
print(str[5])
print(str[6])
print(str[7])
print(str[8])
print(str[9])
H
E
L
L
O
W
O
R
L
D
----------------------------------------------------------------------
-----
IndexError Traceback (most recent call
last)
Cell In[23], line 14
11 print(str[9])
13 # It returns the IndexError because 6th index doesn't exist
---> 14 print(str[10])
print(str[5])
print(str[1])
If you use a negative index, Python returns the character starting from the end of the string. For
example:
print(str[-1])
D
print(str[-5:-3])
WO
print(str[::-1])
DLROWOLLEH
sli="happy people"
print(sli)
happy people
print(sli[::-2])
epe pa
The slice notation str[::-2] is used to reverse a string while skipping every second character.
Slicing strings
String slicing in Python allows you to extract a portion of a string using a specified range of
indices.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Extracting a substring:
Use slicing to get specific parts of the string.
text = "hello world"
# Extract "hello"
hello = text[:5] # Takes characters from the start up to, but not
including, index 5
print(hello) # Output: "hello"
# Extract "world"
world = text[6:] # Takes characters from index 6 to the end
print(world) # Output: "world"
hello
world
dlrow olleh
Skipping characters:
You can skip characters using the step parameter in slicing.
hlowrd
Combining slices:
You can combine different slices to get specific parts of the string.
he w
print(str[4:9])
OWORL
print(str[:3])
HEL
print(str[3:])
LOWORLD
print(len(str))
10
Methods of Python String
Methods Description
upper() Converts the string to uppercase
sw="india"
# The capitalize() method returns a string where the first character
is upper case, and the rest is lower case
x=sw.capitalize()
print(x)
India
print(sw.upper())
INDIA
python is fun
Useful methods
my_string = " Hello World "
Hello World
11
HELLO WORLD
hello world
True
True
4
1
Hello Universe
['how', 'are', 'you', 'doing']
['one', 'two', 'three']
How are you doing
Python Operators
1.Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc.
Comparison operator
Comparison operators mainly use for comparison purposes.
Comparison operators compare the values of the two operands and return a true or false
Boolean values
# Comparison Operators
print("Comparison Operators:")
# Equal to (==)
print(f"{a} == {b}:", a == b) # False
# Equal to (==)
print(f"{b} == {c}:", b == c) # True
Comparison Operators:
15 == 10: False
15 != 10: True
15 > 10: True
15 < 10: False
a<b : False
15 >= 10: True
15 <= 10: False
Using the assignment operators, the right expression's value is assigned to the left operand.
a=b: False
a+=b: 38
a-=b: 26
a*=b: 192
a%=b: 2
a**=b: 1073741824
a//=b: 5
Logical Operators
Logical operators are used to check whether an expression is True or False.
Bitwise operators
Python work directly with the binary representations of integers
Consider the following example code in which we will perform a bitwise AND operation between
two numbers 2 and 6.
A = 2
B = 6
result = A & B
print("Result of (2 & 6): ", result)
a = 12 # Binary: 1100
b = 7 # Binary: 0111
#Bitwise AND (&)
result = a & b # Binary: 0100 (Decimal: 4)
print(result) # Output: 4
# Bitwise OR (|)
result = a | b # Binary: 1111 (Decimal: 15)
print(result) # Output: 15
4
15
11
-13
1536
0
Explanation:
In this example,
Bitwise AND operator will take each bit of both binary numbers and perform AND operation as
follows in the below figure.
Membership Operators
Membership operators in Python are used to test if a sequence contains a certain value. There
are two membership operators in Python:
2. not in: Returns True if a specified value is not present in the sequence.
Using in Operator
# List example
numbers = [1, 2, 3, 4, 5,6,7,8]
print(3 in numbers) # Output: True
# String example
text = "Hello, world!"
print("Hello" in text) # Output: True
# Tuple example
tuple_example = ('a', 'b', 'c', 'd')
print('a' in tuple_example) # Output: True
False
True
False
True
False
True
Identity Operator
# Python program to illustrate the use
# of 'is' identity operator
num1 = 5
num2 = 5
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
True
False
False
False
lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1
False
True
True
True