Unit - 1
Unit - 1
YouTube: World’s largest video-sharing platform uses Python for features like video streaming and backend
services.
Instagram: This popular social media app relies on Python’s simplicity for scaling and handling millions of
users.
Spotify: Python is used for backend services and machine learning to personalize music recommendations.
Dropbox: The file hosting service uses Python for both its desktop client and server-side operations.
Netflix: Python powers key components of Netflix’s recommendation engine and content delivery systems
(CDN).
Google: Python is one of the key languages used in Google for web crawling, testing, and data analysis.
Uber: Python helps Uber handle dynamic pricing and route optimization using machine learning.
Pinterest: Python is used to process and store huge amounts of image data efficiently.
2. Tokens
A token is the smallest individual unit in a python program. All statements and instructions in a program are
built with tokens. The various tokens in python are :
1. Keywords: Keywords are words that have some special meaning or significance in a programming
language. They can’t be used as variable names, function names, or any other random purpose. They are used
for their special features. In Python we have 33 keywords some of them are: try, False, True, class, break,
continue, and, as, assert, while, for, in, raise, except, or, not, if, elif, print, import, etc.
# for loop
for x in range(1, 9):
# Print the value of x
print(x)
Output:
1
2
3
4
5
6
2. Identifiers: Identifiers are the names given to any variable, function, class, list, methods, etc. for their
identification. Python is a case-sensitive language and it has some rules and regulations to name an identifier.
Here are some rules to name an identifier:-
As stated above, Python is case-sensitive. So case matters in naming identifiers. And
hence geeks and Geeks are two different identifiers.
Identifier starts with a capital letter (A-Z) , a small letter (a-z) or an underscore( _ ). It can’t start with
any other character.
Except for letters and underscore, digits can also be a part of identifier but can’t be the first character of
it.
Any other special characters or whitespaces are strictly prohibited in an identifier.
An identifier can’t be a keyword.
# Here GFG and b are the identifier
GFG = 'Hello'
b = "Geeks"
# Driver code
print(GFG)
print(b)
Output:
Hello
Geeks
3. Literals or Values: Literals are the fixed values or data items used in a source code. Python supports
different types of literals such as:
(i) String Literals: The text written in single, double, or triple quotes represents the string literals in
Python. For example: “Computer Science”, ‘sam’, etc. We can also use triple quotes to write multi-line strings.
# String Literals
a = 'Hello'
b = "Geeks"
c = '''Geeks for Geeks is a
learning platform'''
# Driver code
print(a)
print(b)
print(c)
Output
Hello
Geeks
Geeks for Geeks is a
learning platform
(ii) Character Literals: Character literal is also a string literal type in which the character is enclosed in
single or double-quotes.
# Character Literals
a = 'G'
b = "W"
# Driver code
print(a)
print(b)
Output:
G
W
(iii) Numeric Literals: These are the literals written in form of numbers. Python supports the following
numerical literals:
Integer Literal: It includes both positive and negative numbers along with 0. It doesn’t include
fractional parts. It can also include binary, decimal, octal, hexadecimal literal.
Float Literal: It includes both positive and negative real numbers. It also includes fractional parts.
Complex Literal: It includes a+bi numeral, here a represents the real part and b represents the
complex part.
# Numeric Literals
a=5
b = 10.3
c = -17
# Driver code
print(a)
print(b)
print(c)
Output
5
10.3
-17
(iv) Boolean Literals: Boolean literals have only two values in Python. These are True and False.
# Boolean Literals
a=3
b = (a == 3)
c = True + 10
# Driver code
print(a, b, c)
Output
3 True 11
(v) Special Literals: Python has a special literal ‘None’. It is used to denote nothing, no values, or the
absence of value.
# Special Literals
var = None
print(var)
Output
None
(vi) Literals Collections: Literals collections in python includes list, tuple, dictionary, and sets.
List: It is a list of elements represented in square brackets with commas in between. These variables
can be of any data type and can be changed as well.
Tuple: It is also a list of comma-separated elements or values in round brackets. The values can be of
any data type but can’t be changed.
Dictionary: It is the unordered set of key-value pairs.
Set: It is the unordered collection of elements in curly braces ‘{}’.
# Literals collections
# List
my_list = [23, "geek", 1.2, 'data']
# Tuple
my_tuple = (1, 2, 3, 'hello')
# Dictionary
my_dict = {1:'one', 2:'two', 3:'three'}
# Set
my_set = {1, 2, 3, 4}
# Driver code
print(my_list)
print(my_tuple)
print(my_dict)
print(my_set)
Output
[23, 'geek', 1.2, 'data']
(1, 2, 3, 'hello')
{1: 'one', 2: 'two', 3: 'three'}
{1, 2, 3, 4}
4. Operators: These are the tokens responsible to perform an operation in an expression. The variables on which
operation is applied are called operands. Operators can be unary or binary. Unary operators are the ones acting on a
single operand like complement operator, etc. While binary operators need two operands to operate.
# Operators
a = 12
# Unary operator
b=~a
# Binary operator
c = a+b
# Driver code
print(b)
print(c)
Output
-13
-1
5. Punctuators: These are the symbols that used in Python to organize the structures, statements, and
expressions. Some of the Punctuators are: [ ] { } ( ) @ -= += *= //= **== = , etc.
3. Variables
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 many other programming languages, Python
variables do not require explicit declaration of type. The type of the variable is inferred based on the value assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
# Variable 'x' stores the integer value 10
x=5
print(x)
print(name)
Output
5
Samantha
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
Variable names can only contain letters, digits and underscores (_).
A variable name cannot start with a digit.
Variable names are case-sensitive (myVar and myvar are different).
Avoid using Python keywords (e.g., if, else, for) as variable names.
Valid Example:
age = 21
_colour = "lilac"
total_score = 90
Invalid Example:
1name = "Error" # Starts with a digit
class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen
1. Basic Assignment
Variables in Python are assigned values using the =operator.
x=5
y = 3.14
z = "Hi"
2. 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
Python allows multiple variables to be assigned values in a single line.
Casting a Variable
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.
Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output
10
5.0
25
Scope of a Variable
There are two methods how we define scope of a variable in python which are local and global.
1. Local Variables:
Variables defined inside a function are local to that function.
def f():
a = "I am local"
print(a)
f()
# print(a) # This would raise an error since 'local_var' is not accessible outside the function
Output
I am local
2. Global Variables:
Variables defined outside any function are global and can be accessed inside functions using
the global keyword.
a = "I am global"
def f():
global a
a = "Modified globally"
print(a)
f()
print(a)
Output
Modified globally
Modified globally