0% found this document useful (0 votes)
11 views17 pages

Python_Programming_Module-1[1]

Uploaded by

yash95632
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
11 views17 pages

Python_Programming_Module-1[1]

Uploaded by

yash95632
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 17

Python Programming by BR

MODULE-1

INTRODUCTION TO PYTHON PROGRAMMING


Introduction to Python:

 Python is a widely used general-purpose, high level programming language.


 It was created by Guido van Rossum in 1991 and further developed by the Python
Software Foundation.
 It was designed with an emphasis on code readability, and its syntax allows
programmers to express their concepts in fewer lines of code.

Beginning with Python programming:

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.

Line 1: [# Script Begins] In Python, comments begin with a #. This statement is


ignored by the interpreter and serves as documentation for our code.

Line 2: [print(“This is my python program”)] To print something on the console,


print() function is used. This function also adds a newline after our message is
printed(unlike in C). Note that in Python 2, “print” is not a function but a keyword
and therefore can be used without parentheses. However, in Python 3, it is a function
and must be invoked with parentheses.

Line 3: [# Script Ends] This is just another comment like in Line 1.

Reason for increasing popularity:

 Emphasis on code readability, shorter codes, ease of writing


 Programmers can express logical concepts in fewer lines of code in comparison to
languages such as C++ or Java.
Python Programming by BR

 Python supports multiple programming paradigms, like object-oriented, imperative


and functional programming or procedural.
 There exist inbuilt functions for almost all of the frequently used concepts.
 Philosophy is “Simplicity is the best”.

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:

 A token is the smallest individual unit in a python program.


 All statements and instructions in a program are built with tokens.
 A Python variable is a symbolic name that is a reference or pointer to an object.
 Once an object is assigned to a variable, you can refer to the object by that name.

 But the data itself is still contained within the object.


 For example:
 >>> n = 300

 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

print(x / y) # Division: 3.333...


print(x % y) # Modulus: 1
print(x ** y) # Exponentiation: 1000
print(x // y) # Floor Division: 3
2. Assignment Operators
 Assignment Operators are used to assign values to variables and update their values in a
shorthand manner.
 (=) assigns the value on the right to the variable on the left.

3. Comparision (Relational) Operators


Relational operators are used to compare the value of operands (expressions) to produce a logical value.
A logical value is either True or False.

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

Python Data Types:


 Data types are the classification or categorization of data items.
 It represents the kind of value that tells what operations can be performed on a
particular data.
 Since everything is an object in Python programming, data types are actually classes
and variables are instance (object) of these classes.
 Following are the standard or built-in data type of Python:
Python Programming by BR

 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

1. Numeric Data Types

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

2. Sequence Data Types


Sequence data types represent ordered collections of items. These include strings, lists, and tuples.

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

3. Boolean Data Type

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

4. Set Data Types

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

5. Dictionary Data Type

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:

d = {"name": "John", "age": 30}


print("Type of d:", type(d))

Expressions:
Python Programming by BR

 An expression is a combination of operators and operands that is interpreted to produce


some other value.
 Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)

 Arithmetic Expressions: An arithmetic expression is a combination of numeric


values, operators, and sometimes parenthesis.
 The result of this type of expression is also a numeric value.
 The operators used in these expressions are arithmetic operators like addition,
subtraction, etc.
 Here are some arithmetic operators in Python:

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

 Relational Expressions: In these types of expressions, arithmetic expressions are


written on both sides of relational operator (> , < , >= , <=).
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
 Logical Expressions: These are kinds of expressions that result in
either True or False.
 It basically specifies one or more
conditions. Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
 Bitwise Expressions: These are the kind of expressions in which computations are
performed at bit level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Type Conversion in Python:
 Python defines type conversion functions to directly convert one data type to another
which is useful in day-to-day and competitive programming.
 There are two types of Type Conversion in Python:
 Implicit Type Conversion
 Explicit Type Conversion
Implicit Type Conversion
 In Implicit type conversion of data types in Python, the Python interpreter
automatically converts one data type to another without any user involvement.
Example:
x = 10
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)

Input and Output in Python:


How to Take Input from User in Python
 Sometimes a developer might want to take user input at some point in the program. To
do this Python provides an input() function.
 Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the time of
taking input.
Example:
# Taking input from the user
name = input("Enter your name: ")

# 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

How to Display Output in Python:


 Python provides the print() function to display output to the standard output devices.
 Syntax: print(value(s), sep= ‘ ‘, end = ‘\n’, file=file,
flush=flush) Example:
# Python program to demonstrate
# print() method
print("GFG")

# code for disabling the softspace feature


print('G', 'F', 'G')
Python Programming by BR

You might also like