Python_Programming_Module-1[1]
Python_Programming_Module-1[1]
MODULE-1
1. Finding an Interpreter:
Windows: There are many interpreters available freely to run Python scripts like
IDLE (Integrated Development Environment) that comes bundled with the Python
software downloaded from http://python.org/.
Linux: Python comes preinstalled with popular Linux distros such as Ubuntu and
Fedora. To check which version of Python you’re running, type “python” in the
terminal emulator. The interpreter should start and print the version number.
macOS: Generally, Python 2.7 comes bundled with macOS. You’ll have to manually
install Python 3 from http://python.org/
2. Writing our first program:
Just type in the following code after you start the interpreter.
# Script Begins
print(“My First Python
Program") # Scripts Ends
Let’s analyze the script line by line.
Language Features:
1. Interpreted:
There are no separate compilation and execution steps like C and C++.
Directly run the program from the source code.
Internally, Python converts the source code into an intermediate form called
bytecodes which is then translated into native language of specific computer to
run it.
No need to worry about linking and loading with libraries, etc.
2. Platform Independent:
Python programs can be developed and executed on multiple operating system
platforms.
Python can be used on Linux, Windows, Macintosh, Solaris and many more.
3. Free and Open Source
4. Redistributable
5. High-level Language
In Python, no need to take care about low-level details such as managing the
memory used by the program.
6. Simple
Closer to English language; Easy to Learn
More emphasis on the solution to the problem rather than the syntax
7. Embeddable
Python can be used within C/C++ program to give scripting capabilities for the
program’s users.
8. Robust:
Exceptional handling features
Memory management techniques in built
9. Rich Library Support
The Python Standard Library is very vast.
Known as the “batteries included” philosophy of Python ;It can help do various
things involving regular expressions, documentation generation, unit testing,
threading, databases, web browsers, CGI, email, XML, HTML, WAV files,
cryptography, GUI and many more.
Besides the standard library, there are various other high-quality libraries such as
the Python Imaging Library which is an amazingly simple image manipulation
library.
Python Programming by BR
Tokens:
This assignment creates an integer object with the value 300 and assigns the variable n
to point to that object.
Literals or Values:
Literals are the fixed values or data items used in a source code.
Python supports different types of literals such as:
String Literals
Character Literals
Numeric Literals
Boolean Literals
Special Literals
Python Programming by BR
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.
Example:
# String Literals
a = 'Hello'
b = "Geeks"
c = '''Geeks for Geeks is a
learning platform'''
# Driver code
print(a)
print(b)
print(c)
Character Literals:
Character literal is also a string literal type in which the character is enclosed in single
or double-quotes.
Ex:
# Character Literals
a = 'G'
b = "W"
# Driver code
print(a)
print(b)
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.
Example:
# Numeric Literals
a=5
b = 10.3
c = -17
# Driver code
Python Programming by BR
print(a)
print(b)
print(c)
Boolean Literals:
Boolean literals have only two values in Python. These are True and False.
Example:
# Boolean Literals
a=3
b = (a == 3)
c = True + 10
# Driver code
print (a, b, c)
Special Literals:
Python has a special literal ‘None’. It is used to denote nothing, no values, or the
absence of value.
Example:
# Special Literals
var = None
print(var)
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
‘{}’. Example:
# 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)
Python Programming by BR
print(my_dict)
print(my_set)
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.
Example:
# Here GFG and b are the identifier
GFG = 'Hello'
b = "Geeks"
# Driver
code
print(GFG)
print(b)
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.
Example:
# for loop
for x in range(1, 9):
# Print the value of x
print(x)
# Check if the value of x is less than
6 # Here if the value of x is less than
6 # then the loop will continue
# Here, if, continue, else, break,
# for loop are keywords
if x < 6:
Python Programming by BR
continue
# If i greater then 6 then break loop
else:
break
Character set:
A character set is a set of valid characters acceptable by a programming language in
scripting.
Python supports all ASCII / Unicode characters that include:
Alphabets: All capital (A-Z) and small (a-z) alphabets.
Digits: All digits 0-9.
Special Symbols: Python supports all kind of special symbols like, ” ‘ l ; : ! ~ @
#$%^`&*()_+–={}[]\.
White Spaces: White spaces like tab space, blank space, newline, and carriage
return.
Other: All ASCII and UNICODE characters are supported by Python that
constitutes the Python character set.
Operators:
Operators are used to perform operations on variables and values These are
standard symbols used for the purpose of logical and arithmetic operations.
1. Arithmetic Operators
Python Arithmetic operators are used to perform basic mathematical operations like addition,
subtraction, multiplication, and division.
Example:
x = 10
y=3
print(x + y) # Addition: 13
print(x - y) # Subtraction: 7
print(x * y) # Multiplication: 30
Python Programming by BR
Example:
x = 10
y = 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x < y) # True
print(x >= y) # False
print(x <= y) # True
4. Logical Operators
In Python, Logical operators are used on conditional statements (either True or False). They perform
Logical AND, Logical OR and Logical NOT operations.
Python Programming by BR
Example:
x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False
5. Bitwise Operators
In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first
converted into binary and then operations are performed on each bit or corresponding pair of bits, hence
the name bitwise operators. The result is then returned in decimal format.
Example:
x = 10 # 1010 in binary
y = 4 # 0100 in binary
print(x & y) # 0000 (0 in decimal)
print(x | y) # 1110 (14 in decimal)
print(x ^ y) # 1110 (14 in decimal)
print(~x) # -11 (inverted bits)
print(x << 2) # 101000 (40 in decimal)
print(x >> 2) # 0010 (2 in decimal)
6. Identity Operators
Identity operators in Python are used to compare the memory locations of two objects. The two identity
operators are is and is not. The is operator returns True if both objects are the same object in memory,
while the is not operator returns True if both objects are not the same object in memory
Python Programming by BR
Example:
x = [1, 2, 3]
y = [1, 2, 3]
z=x
print(x is z) # True, because z is the same object as x
print(x is y) # False, because y is a different object
print(x == y) # True, because x and y have the same values
print(x is not y) # True, because x and y are not the same object
7. Membership Operators
Python offers two membership operators to check or validate the membership of a value. It tests for
membership in a sequence, such as strings, lists, or tuples. in operator: The ‘in’ operator is used to check
if a character/ substring/ element exists in a sequence or not. Evaluate to True if it finds the specified
element in a sequence otherwise False.
Example:
x = "Hello World"
y = [1, 2, 3, 4]
print("H" in x) # True
print("hello" in x) # False
print(1 in y) # True
print(5 not in y) # True
Numeric
Sequence Type
Boolean
Set
Dictionary
Numeric data types represent numbers in Python. They are categorized into three classes:
int
- Represents whole numbers, either positive or negative, without fractions or decimals.
- In Python, there is no limit to how large an integer can be, as long as there is enough memory.
- Example: 5, -10, 0
- Example code:
a=5
print("Type of a:", type(a))
float
- Represents real numbers with floating-point representation (numbers with a decimal point).
- Example: 5.0, -3.14, 0.001
- Example code:
b = 5.0
print("Type of b:", type(b))
complex
- Represents complex numbers, which consist of a real part and an imaginary part.
- Format: (real part) + (imaginary part)j
- Example: 2+3j, -1+4.5j
- Example code:
c = 2 + 3j
print("Type of c:", type(c))
str
- Represents a sequence of characters (text data).
- Strings are immutable, meaning that once created, they cannot be changed.
- Example: "Hello", "Python123"
- Example code:
Python Programming by BR
s = "Hello"
print("Type of s:", type(s))
list
-Represents an ordered collection of items, which can be of different data types.
- Lists are mutable, meaning you can change their content after creation.
- Example: [1, 2, 3], ["apple", "banana", "cherry"]
- Example code:
l = [1, 2, 3]
print("Type of l:", type(l))
tuple
- Represents an ordered collection of items, similar to a list, but tuples are immutable.
- Tuples are faster than lists due to their immutability.
- Example: (1, 2, 3), ("apple", "banana", "cherry")
- Example code:
t = (1, 2, 3)
print("Type of t:", type(t))
bool
- Represents one of two values: `True` or `False`.
- Booleans are commonly used for conditional testing.
- Example: True, False
- Example code:
flag = True
print("Type of flag:", type(flag))
set
- Represents an unordered collection of unique items.
- Sets are mutable, but they do not allow duplicate elements.
- Example: {1, 2, 3}, {"apple", "banana", "cherry"}
- Example code:
s = {1, 2, 3}
print("Type of s:", type(s))
dict
- Represents an unordered collection of key-value pairs.
- Keys must be unique and immutable, while values can be of any data type.
- Example: {"name": "John", "age": 30}, {1: "apple", 2: "banana"}
- Example code:
Expressions:
Python Programming by BR
Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Python Programming by BR
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
In Explicit Type Conversion in Python, the data type is manually changed by the user
as per their requirement.
Various forms of explicit type conversion are explained below:
int(a, base): This function converts any data type to integer. ‘Base’ specifies
the base in which string is if the data type is a string.
float(): This function is used to convert any data type to a floating-
point number.
Example:
# Python code to demonstrate Type conversion
# using int(), float()
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)
# Output
print("Hello, " + name)
print(type(name))
How to take Multiple Inputs in Python: we can take multiple inputs of the same data
type at a time in python, using map() method in python.
Example:
a, b, c = map(int, input("Enter the Numbers : ").split())
print("The Numbers are : ",end = " ")
print(a, b, c)
Python Programming by BR