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

Python_S2AIDS_1st_Class

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Python_S2AIDS_1st_Class

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

COMMENTS IN PYTHON :

Comments are essential for defining the code and help us and other to understand the code

# this is my first comment

name="hari" # assigning string value to the name variable

'''This is also a comment in


Python Programming Language,
with multiple lines of statements'''

'This is also a comment in\nPython Programming Language,\nwith


multiple lines of statements'

FIRST PROGRAM OF PYTHON


print("hello world")
print('hello world')
print('hai')
a=10
print(a)

hello world
hello world
hai
10

print() : function to display the message on the screen. the message can be string integer, float

Variables and Basic Types


Python has no command for declaring a variable. A variable is created the moment you first
assign a value to it. Variables are defined with the assignment operator, =".

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

same for the other examples

Case-Sensitivity of Python Variables


Python variables are case sensitive which means Age and age are two different variables:

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

If a variable is not defined, trying to use it will result in a NameError.

print(h) # Attempting to print an undefined variable 'h'

----------------------------------------------------------------------
-----
NameError Traceback (most recent call
last)
Cell In[17], line 1
----> 1 print(h) # Attempting to print an undefined variable 'x'

NameError: name 'h' is not defined

Python Data Types


Variables can store data of different types.

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')

Direct value inputting


a=5
b=10
c=a+b
print("print the result..",c)

print the result.. 15


USER INPUT :
The input() function reads a line from the input (usually from the user), converts it
into a string, and returns it
input("enter the name..")

enter the name.. mnb

'mnb'

a=input("enter...")
print(a)

enter... a

# Prompt the user for a number


age = int(input("Enter your age: "))

# Use the input in a calculation or condition


print(f"You are {age} years old.")

Enter your age: 23

You are 23 years old.

# Prompt the user for a floating-point number


height = float(input("Enter your height in meters: "))

# Use the input


print(f"Your height is {height} meters.")

Enter your height in meters: 12

Your height is 12.0 meters.

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

Getting Type of a Variable


You can get the data type of a Python variable using the python built-in function type() as
follows.

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.).

False await else import pass

None break except in raise

True class finally is return

and continue for lambda try

as def from nonlocal while

assert del global not with

async elif if or yield


import keyword

print(keyword.kwlist)

['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',


'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']

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'.

We use single quotes or double quotes to represent a string in Python

# create a string using double quotes


ss="welcome to string"
print(ss)
# create a string using single quotes
ss1='welcome to string'
print(ss1)

welcome to string
welcome to string

Access String Characters in Python


We can access the characters in a string in three ways

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])

# It returns the IndexError because 6th index doesn't exist


print(str[10])

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])

IndexError: string index out of range

Accessing string elements


Since a string is a sequence of characters, you can access its elements using an index. The first
character in the string has an index of zero.

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.

Let’s break down what each part of the notation means:

1. str refers to the original string.


2. The first colon : denotes that we want to include all characters from the start to the end
of the string.
3. The -2 means we are taking steps of -2, which essentially reverses the string and skips
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.

syntax :string[start : end : step]


includes the character at the start and excludes the string at end ,step is an optional argument
that determines the increment between each index for slicing.

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

Reversing the string:


You can reverse the string using slicing.

reversed_text = text[::-1] # Takes characters in reverse order


print(reversed_text) # Output: "dlrow olleh"

dlrow olleh

Skipping characters:
You can skip characters using the step parameter in slicing.

# Extract every second character


every_second_char = text[::2] # Takes every 2nd character from the
start to the end
print(every_second_char) # Output: "hlo wrd"

hlowrd

Combining slices:
You can combine different slices to get specific parts of the string.

#text = "hello world"


# Extract "he wr"
combined = text[:2] + text[5:7]
print(combined) # Output: "he wr"

he w
print(str[4:9])

OWORL

print(str[:3])

HEL

print(str[3:])

LOWORLD

Getting the length of a string


To get the length of a string, you use the len() function. For example:

print(len(str))

10
Methods of Python String

Methods Description
upper() Converts the string to uppercase

lower() Converts the string to lowercase

partition() Returns a tuple

replace() Replaces substring inside

find() Returns the index of the first occurrence of substring

rstrip() Removes trailing characters

split() Splits string from left

startswith() Checks if string starts with the specified string

isnumeric() Checks numeric characters

index() Returns index of substring

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

message = 'PYTHON IS FUN'

# convert message to lowercase


print(message.lower())

python is fun

Useful methods
my_string = " Hello World "

# remove white space


my_string = my_string.strip()
print(my_string)
# number of characters
print(len(my_string))

# Upper and lower cases


print(my_string.upper())
print(my_string.lower())

# startswith and endswith


print("hello".startswith("he"))
print("hello".endswith("llo"))

# find first index of a given substring, -1 otherwise


print("Hello".find("o"))

# count number of characters/substrings


print("Hello".count("e"))

# replace a substring with another string (only if the substring is


found)
# Note: The original string stays the same
message = "Hello World"
new_message = message.replace("World", "Universe")
print(new_message)

# split the string into a list


my_string = "how are you doing"
a = my_string.split() # default argument is " "
print(a)
my_string = "one,two,three"
a = my_string.split(",")
print(a)

# join elements of a list into a string


my_list = ['How', 'are', 'you', 'doing']
a = ' '.join(my_list) # the given string is the separator, e.g. ' '
between each argument
print(a)

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.

a = 50 # Initialize the value of a


b = 10 # Initialize the value of b
print('Addition of two numbers:',a+b)
print('Subtraction of two numbers:',a-b)
print('Multiplication of two numbers:',a*b)
print('Division of two numbers:',a/b)
print('Reminder of two numbers:',a%b)
print('Exponent of two numbers:',a**b)
print('Floor division of two numbers:',a//b)

Addition of two numbers: 60


Subtraction of two numbers: 40
Multiplication of two numbers: 500
Division of two numbers: 5.0
Reminder of two numbers: 0
Exponent of two numbers: 97656250000000000
Floor division of two numbers: 5

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

# Define two numbers


a = 15
b = 10

# Comparison Operators
print("Comparison Operators:")

# Equal to (==)
print(f"{a} == {b}:", a == b) # False

# Not equal to (!=)


print(f"{a} != {b}:", a != b) # True

# Greater than (>)


print(f"{a} > {b}:", a > b) # True
# Less than (<)
print(f"{a} < {b}:", a < b) # False
print("a<b :",a<b)

# Greater than or equal to (>=)


print(f"{a} >= {b}:", a >= b) # True

# Less than or equal to (<=)


print(f"{a} <= {b}:", a <= b) # False

# Test with equal numbers


c = 10

print("\nTesting with equal numbers:")

# Equal to (==)
print(f"{b} == {c}:", b == c) # True

# Not equal to (!=)


print(f"{b} != {c}:", b != c) # False

# Greater than (>)


print(f"{b} > {c}:", b > c) # False

# Less than (<)


print(f"{b} < {c}:", b < c) # False

# Greater than or equal to (>=)


print(f"{b} >= {c}:", b >= c) # True

# Less than or 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

Testing with equal numbers:


10 == 10: True
10 != 10: False
10 > 10: False
10 < 10: False
10 >= 10: True
10 <= 10: True
Assignment Operators
Assignment operators are used to assign values to the variables.

Using the assignment operators, the right expression's value is assigned to the left operand.

a = 32 # Initialize the value of a


b = 6 # Initialize the value of b
print('a=b:', a==b)
print('a+=b:', a+b) # a = a + b
print('a-=b:', a-b) # a = a - b
print('a*=b:', a*b) # a = a * b
print('a%=b:', a%b)
print('a**=b:', a**b) # Exponentiation and assignment ie: 32^6
print('a//=b:', a//b) # a = a // b. It divides a by b, performs floor
division, and assigns the integer result back to a.

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.

The three primary logical operators in Python are:

Logical AND (and): Returns True if both operands are true.

Logical OR (or): Returns True if at least one of the operands is true.

Logical NOT (not): Returns True if the operand is false.


# Example with conditions
a = 10
b = 20
c = 30

# Using logical operators with comparison operators


and_condition = (a < b) and (b < c)
print("(a < b) and (b < c):", and_condition) # Output: True

or_condition = (a > b) or (b < c)


print("(a > b) or (b < c):", or_condition) # Output: True

not_condition = not (a < c)


print("not (a < c):", not_condition) # Output: False

(a < b) and (b < c): True


(a > b) or (b < c): True
not (a < c): 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)

Result of (2 & 6): 2

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

#Bitwise XOR (^)


result = a ^ b # Binary: 1011 (Decimal: 11)
print(result) # Output: 11

# Bitwise NOT (~)


result = ~a # Binary: 11110011 (Decimal: -13)
print(result) # Output: -13

#Left Shift (<<)


result = a << b # Binary: 00010100 (Decimal: 20)
print(result) # Output: 20

#Right Shift (>>)


result = a >> b # Binary: 00000101 (Decimal: 5)
print(result) # Output: 5

4
15
11
-13
1536
0

Explanation:
In this example,

the binary conversion of 2 is 0010 and that of 6 is 0110.

Bitwise AND operator will take each bit of both binary numbers and perform AND operation as
follows in the below figure.

The decimal conversion of 0010 is 2.

Membership Operators
Membership operators in Python are used to test if a sequence contains a certain value. There
are two membership operators in Python:

1. in: Returns True if a specified value is present in the sequence.

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

# Dictionary example (checks keys)


dictionary = {'key1': 'value1', 'key2': 'value2'}
print('key1' in dictionary) # Output: True
print('value1' in dictionary) # Output: False
True
True
True
True
False

Using not in Operator


list_example = [1, 2, 3, 4, 5]
# Using 'not in'
print(3 not in list_example) # Output: False
print(6 not in list_example) # Output: True

# Using 'not in' with a string


string_example = "Hello, world!"
print('H' not in string_example) # Output: False
print('h' not in string_example) # Output: True

# Using 'not in' with a set


set_example = {1, 2, 3, 4, 5}
print(3 not in set_example) # Output: False
print(6 not in set_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

str1 = "hello world"


str2 = "hello world"

# using 'is' identity operator on different datatypes


print(num1 is num2)
print(lst1 is lst2)
print(str1 is str2)
print(str1 is str2)

True
False
False
False

# Python program to illustrate the use


# of 'is' identity operator
num1 = 5
num2 = 5

lst1 = [1, 2, 3]
lst2 = [1, 2, 3]
lst3 = lst1

str1 = "hello world"


str2 = "hello world"

# using 'is not' identity operator on different datatypes


print(num1 is not num2)
print(lst1 is not lst2)
print(str1 is not str2)
print(str1 is not str2)

False
True
True
True

You might also like