Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Programming Module-1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

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 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.
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
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
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)
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:
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:
 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.
Example:
# Operators
a = 12

# Unary operator
b=~a

# Binary operator
c = a+b

# Driver code
print(b)
print(c)

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:
 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

 In Python, numeric data type represent the data which has numeric value.
 Numeric value can be integer, floating number or even complex numbers.
 These values are defined as int, float and complex class in Python.
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
 Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.
 Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j.
Example:
# Python program to
# demonstrate numeric value

a=5
print("Type of a: ", type(a))

b = 5.0
print("\nType of b: ", type(b))

c = 2 + 4j
print("\nType of c: ", type(c))
Expressions:
 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)
 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
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)
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')

You might also like