0% found this document useful (0 votes)
2 views34 pages

Notes Python

Uploaded by

Drdeepti Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Notes Python

Uploaded by

Drdeepti Gupta
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python Variables

Last Updated : 14 Jan, 2026



In Python, variables are used to store data that can be referenced


and manipulated during program execution. A variable is
essentially a name that is assigned to a value.
 Unlike Java and many other languages, Python variables do not
require explicit declaration of type.
 The type of the variable is inferred based on the value assigned.

x = 5
name = "Samantha"
print(x)
print(name)

Output
5
Samantha
Ex:
a=4
A = "Sally"

print(a)
print(A)
output:
4
Sally
Ex:
x = "John"
print(x)
#double quotes are the same as single quotes:
x = 'John'
print(x)
output:
John
John

x, y, z = "Orange", "Banana", "Cherry"

print(x)
print(y)
print(z)
output:
Orange
Banana
Cherry

x = y = z = "Orange"

print(x)
print(y)
print(z)
output:
Orange
Orange
Orange

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


x, y, z = fruits
print(x)
print(y)
print(z)
output:
apple
banana
cherry

x = "Python "
y = "is "
z = "awesome"
print(x + y + z)
output:
Python is awesome

x = "Python"
y = "is"
z = "awesome"
print(x, y, z)
output:
Python is awesome

x=5
y = "John"
print(x + y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

x=5
y = "John"
print(x, y)
output:
5 John
x = "awesome"

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

myfunc()
output:
Python is awesome

x = "awesome"

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

myfunc()

print("Python is " + x)

output:
Python is fantastic
Python is awesome

Rules for Naming Variables


To use variables effectively, we must follow Python’s naming rules:
1. Variable names can only contain letters, digits and underscores
(_).
2. A variable name cannot start with a digit.
3. Variable names are case-sensitive like myVar and myvar are
different.
4. Avoid using Python keywords like if, else, for as variable names.
Below listed variable names are valid:
age = 21
_colour = "lilac"
total_score = 90
Below listed variables names are invalid:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
Assigning Values to Variables
Basic Assignment: Variables in Python are assigned values using
the = operator.
x = 5
y = 3.14
z = "Hi"
Dynamic Typing: Python variables are dynamically typed,
meaning the same variable can hold different types of values
during execution.
x = 10
x = "Now a string"
Multiple Assignments
Assigning Same Value: Python allows assigning the same value
to multiple variables in a single line, which can be useful for
initializing variables with the same value.

a = b = c = 100
print(a, b, c)

Output
100 100 100
Assigning Different Values: We can assign different values to
multiple variables simultaneously, making the code concise and
easier to read.

x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one
data type into another. Python provides several built-in functions to
facilitate casting, including int(), float() and str() among others.
Basic casting functions are:
 int(): Converts compatible values to an integer.
 float(): Transforms values into floating-point numbers.
 str(): Converts any data type into a string.

s = "10"
n = int(s)

cnt = 5
f = float(cnt)

age = 25
s2 = str(age)

print(n)
print(f)
print(s2)
Output
10
5.0
25
Type of Variable
In Python, we can determine the type of a variable using
the type() function. This built-in function returns the type of the
object passed to it.

n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True

print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))

Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>

Example:
x=5
y = "John"
print(type(x))
print(type(y))

output :
<class 'int'>
<class 'str'>

Concept of Object Reference


Let us assign a variable x to value 5.
x=5
When x = 5 is executed, Python creates an object to represent the
value 5 and makes x reference this object.

object reference
Now, let's assign another variable y to the variable x.
y=x
This statement creates y and references the same object as x, not
x itself. This is called a Shared Reference, where multiple variables
reference the same object.
shared reference
Now, if we write
x = 'Geeks'
Python creates a new object for the value "Geeks" and makes x
reference this new object.

shared reference
example
The variable y remains unchanged, still referencing the original
object 5. Now, If we assign a new value to y:
y = "Computer"

shared
reference example
 Python creates yet another object for "Computer" and updates y
to reference it.
 The original object 5 no longer has any references and becomes
eligible for garbage collection.
 Python variables hold references to objects, not the actual
objects themselves.
 Reassigning a variable does not affect other variables
referencing the same object unless explicitly updated.
Deleting a Variable
We can remove a variable from the namespace using
the del keyword. This deletes the variable and frees up the memory
it was using.
x = 10
del x
print(x)
Output
ERROR!
Traceback (most recent call last):
File "<[Link]>", line 3, in <module>
NameError: name 'x' is not defined
Explanation:
 del x removes the variable x from memory.
 After deletion, trying to access the variable x results in a
NameError indicating that the variable no longer exists.
Practical Examples
1. Swapping Two Variables: Using multiple assignments, we can
swap the values of two variables without needing a temporary
variable.

a, b = 5, 10
a, b = b, a
print(a, b)

Output
10 5
2. Counting Characters in a String: Assign the results of
multiple operations on a string to variables in one line.

word = "Python"
length = len(word)
print("Length of the word:", length)

Output
Length of the word: 6

Built-in Data Types


In programming, data type is an important concept.

Variables can store data of different types, and different types can do
different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric int, float, complex


Types:

Sequence list, tuple, range


Types:

Mapping dict
Type:

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

x = "Hello World" str Try it »

x = 20 int Try it »

x = 20.5 float Try it »

x = 1j complex Try it »

x = ["apple", "banana", "cherry"] list Try it »

x = ("apple", "banana", "cherry") tuple Try it »

x = range(6) range Try it »

x = {"name" : "John", "age" : 36} dict Try it »


x = {"apple", "banana", "cherry"} set Try it »

x = frozenset({"apple", "banana", "cherry"}) frozenset Try it »

x = True bool Try it »

x = b"Hello" bytes Try it »

x = bytearray(5) bytearray Try it »

x = memoryview(bytes(5)) memoryview Try it »

x = None NoneType Try it »

REMOVE ADS

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor
functions:

Example Data Type Try it

x = str("Hello World") str Try it »


x = int(20) int Try it »

x = float(20.5) float Try it »

x = complex(1j) complex Try it »

x = list(("apple", "banana", "cherry")) list Try it »

x = tuple(("apple", "banana", "cherry")) tuple Try it »

x = range(6) range Try it »

x = dict(name="John", age=36) dict Try it »

x = set(("apple", "banana", "cherry")) set Try it »

x = frozenset(("apple", "banana", frozenset Try it »


"cherry"))

x = bool(5) bool Try it »


x = bytes(5) bytes Try it »

x = bytearray(5) bytearray Try it »

x = memoryview(bytes(5)) memoryview Try it »

x=1

y = 2.8

z = 1j

print(type(x))

print(type(y))

print(type(z))
<class 'int'>
<class 'float'>
<class 'complex'>

x=1

y = 35656222554887711

z = -3255522

print(type(x))

print(type(y))
print(type(z))
<class 'int'>
<class 'int'>
<class 'int'>

x = 1.10

y = 1.0

z = -35.59

print(type(x))

print(type(y))

print(type(z))
<class 'float'>
<class 'float'>
<class 'float'>

x = 35e3

y = 12E4

z = -87.7e100

print(type(x))

print(type(y))

print(type(z))
<class 'float'>
<class 'float'>
<class 'float'>

x = 3+5j
y = 5j

z = -5j

print(type(x))

print(type(y))

print(type(z))
<class 'complex'>
<class 'complex'>
<class 'complex'>

#convert from int to float:

x = float(1)

#convert from float to int:

y = int(2.8)

#convert from int to complex:

z = complex(1)

print(x)

print(y)

print(z)

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

print(type(z))

#convert from int to float:


x = float(1)

#convert from float to int:


y = int(2.8)

#convert from int to complex:


z = complex(1)

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

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

1.0
2
(1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>

x = int(1)

y = int(2.8)

z = int("3")

print(x)
print(y)

print(z)
1
2
3

x = float(1)

y = float(2.8)

z = float("3")

w = float("4.2")

print(x)

print(y)

print(z)

print(w)
1.0
2.8
3.0
4.2

x = int(1)

y = int(2.8)

z = int("3")

print(x)

print(y)
print(z)
1
2
3

print("It's alright")

print("He is called 'Johnny'")

print('He is called "Johnny"')


It's alright
He is called 'Johnny'
He is called "Johnny"

for x in "banana":

print(x)
b
a
n
a
n
a

a = "Hello, World!"

print(len(a))
13

txt = "The best things in life are free!"

print("free" in txt)
True

txt = "The best things in life are free!"


if "free" in txt:

print("Yes, 'free' is present.")


Yes, 'free' is present.

txt = "The best things in life are free!"

print("expensive" not in txt)


True

txt = "The best things in life are free!"

if "expensive" not in txt:

print("No, 'expensive' is NOT present.")


No, 'expensive' is NOT present.

b = "Hello, World!"

print(b[2:5])
llo

b = "Hello, World!"

print(b[:5])
Hello

b = "Hello, World!"

print(b[2:])
llo, World!

b = "Hello, World!"

print(b[-5:-2])
orl
a = "Hello, World!"

print([Link]())
HELLO, WORLD!

a = "Hello, World!"

print([Link]())
hello, world!

a = " Hello, World! "

print([Link]())
Hello, World!

a = "Hello, World!"

print([Link]("H", "J"))
Jello, World!

a = "Hello, World!"

b = [Link](",")

print(b)
['Hello', ' World!']

a = "Hello"

b = "World"

c=a+b

print(c)
HelloWorld
a = "Hello"

b = "World"

c=a+""+b

print(c)
Hello World

age = 36

#This will produce an error:

txt = "My name is John, I am " + age

print(txt)
Traceback (most recent call last):
File "demo_string_format_error.py", line 2, in <module>
txt = "My name is John, I am " + age
TypeError: must be str, not int

age = 36

txt = f"My name is John, I am {age}"

print(txt)

My name is John, I am 36

price = 59

txt = f"The price is {price} dollars"

print(txt)

The price is 59 dollars

price = 59
txt = f"The price is {price:.2f} dollars"

print(txt)

The price is 59.00 dollars

txt = f"The price is {20 * 59} dollars"

print(txt)

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

print(txt)
We are the so-called "Vikings" from the north.

Method Description

capitalize() Converts the first character to upper case

casefold() Converts string into lower case

center() Returns a centered string

count() Returns the number of times a specified value occurs in a string

encode() Returns an encoded version of the string

endswith() Returns true if the string ends with the specified value
expandtabs Sets the tab size of the string
()

find() Searches the string for a specified value and returns the position of
where it was found

format() Formats specified values in a string

format_ma Formats specified values in a string


p()

index() Searches the string for a specified value and returns the position of
where it was found

isalnum() Returns True if all characters in the string are alphanumeric

isalpha() Returns True if all characters in the string are in the alphabet

isascii() Returns True if all characters in the string are ascii characters

isdecimal() Returns True if all characters in the string are decimals

isdigit() Returns True if all characters in the string are digits


isidentifier( Returns True if the string is an identifier
)

islower() Returns True if all characters in the string are lower case

isnumeric() Returns True if all characters in the string are numeric

isprintable( Returns True if all characters in the string are printable


)

isspace() Returns True if all characters in the string are whitespaces

istitle() Returns True if the string follows the rules of a title

isupper() Returns True if all characters in the string are upper case

join() Joins the elements of an iterable to the end of the string

ljust() Returns a left justified version of the string

lower() Converts a string into lower case

lstrip() Returns a left trim version of the string


maketrans( Returns a translation table to be used in translations
)

partition() Returns a tuple where the string is parted into three parts

replace() Returns a string where a specified value is replaced with a specified value

rfind() Searches the string for a specified value and returns the last position of
where it was found

rindex() Searches the string for a specified value and returns the last position of
where it was found

rjust() Returns a right justified version of the string

rpartition() Returns a tuple where the string is parted into three parts

rsplit() Splits the string at the specified separator, and returns a list

rstrip() Returns a right trim version of the string

split() Splits the string at the specified separator, and returns a list

splitlines() Splits the string at line breaks and returns a list

startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string

swapcase() Swaps cases, lower case becomes upper case and vice versa

title() Converts the first character of each word to upper case

translate() Returns a translated string

upper() Converts a string into upper case

zfill() Fills the string with a specified number of 0 values at the beginning

a = 200

b = 33

if b > a:

print("b is greater than a")

else:

print("b is not greater than a")


b is not greater than a

print(bool("Hello"))
print(bool(15))
True
True

x = "Hello"

y = 15

print(bool(x))

print(bool(y))
True
True

sum1 = 100 + 50 # 150 (100 + 50)

sum2 = sum1 + 250 # 400 (150 + 250)

sum3 = sum2 + sum2 # 800 (400 + 400)

print(sum1)

print(sum2)

print(sum3)
150
400
800

+ Addition x+y Try it »


- Subtraction x-y Try it »

* Multiplication x*y Try it »

/ Division x/y Try it »

% Modulus x%y Try it »

** Exponentiation x ** y Try it »

// Floor division x // y

Operator Example Same As Try it

= x=5 x=5 Try it »

+= x += 3 x=x+3 Try it »

-= x -= 3 x=x-3 Try it »

*= x *= 3 x=x*3 Try it »

/= x /= 3 x=x/3 Try it »
%= x %= 3 x=x%3 Try it »

//= x //= 3 x = x // 3 Try it »

**= x **= 3 x = x ** 3 Try it »

&= x &= 3 x=x&3 Try it »

|= x |= 3 x=x|3 Try it »

^= x ^= 3 x=x^3 Try it »

>>= x >>= 3 x = x >> 3 Try it »

<<= x <<= 3 x = x << 3 Try it »

:= print(x := 3) x=3
print(x)

numbers = [1, 2, 3, 4, 5]

count = len(numbers)

if count > 3:

print(f"List has {count} elements")


if (count := len(numbers)) > 3:

print(f"List has {count} elements")


List has 5 elements
List has 5 elements

== Equal x == y Try it »

!= Not equal x != y Try it »

> Greater than x>y Try it »

< Less than x<y Try it »

>= Greater than or equal to x >= y Try it »

<= Less than or equal to x <= y

x = 5
y = 3

print(x == y)
print(x != y)
print(x > y)
print(x < y)
print(x >= y)
print(x <= y)

x=5
print(1 < x < 10)

print(1 < x and x < 10)


True
True

Logical Operators
Logical operators are used to combine conditional statements:

Operator Description Example Try it

and Returns True if both statements are x < 5 and x < 10 Try it »
true

or Returns True if one of the x < 5 or x < 4 Try it »


statements is true

not Reverse the result, returns False if not(x < 5 and x < 10)
the result is true

x=5

print(x > 0 and x < 10)


True
x=5

Print(x < 5 or x > 10)


False

x=5

print (not(x > 3 and x < 10))


False

You might also like