




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





























































































CDOE – ODL B.Sc CS – SEMESTER I PYTHON PROGRAMMING
Unit I : Basics of Python Programming: History of Python-Features of Python-Literal
Unit II: Control Statements: Selection/Conditional Branching statements: if, if-else, nested if and if-elif-else statements. Iterative Statements: while loop, for loop, else suite in loop and nested loops. Jump Statements: break, continue and pass statements.
Unit III: Functions: Function Definition – Function Call – Variable Scope and its Lifetime-Return Statement. Function Arguments: Required Arguments, Keyword Arguments, Default Arguments and Variable Length Arguments- Recursion. Python Strings: String operations- Immutable Strings - Built-in String Methods and Functions
Unit IV : Lists: Creating a list - Access values in List-Updating values in Lists-Nested lists - Basic list operations- List Methods. Tuples: Creating, Accessing, Updating and Deleting Elements in a tuple – Nested tuples– Difference between lists and tuples. Dictionaries: Creating, Accessing, Updating and Deleting Elements in a Dictionary – Dictionary Functions and Methods - Difference between Lists and Dictionaries.
Unit V : Python File Handling: Types of files in Python - Opening and Closing files- Reading and Writing files: write() and writelines() methods- append() method – read() and readlines() methods – with keyword – Splitting words – File methods - File Positions- Renaming and deleting files
CDOE – ODL B.Sc CS – SEMESTER I PYTHON PROGRAMMING
In this unit, leaners will have a brief understanding of the history and features of python programming. The basic concepts that are need for any programming languages like constants, literals, keywords and how to declare a variable in python will be discussed. Along with the basic data types that are supported in python programming. The way how to use the input, output statement and how data type conversion of variables in done in python. Finally the unit ends with how to create and process Arrays and the methods used for array in python.
Python was first developed by Guido van Rossum in the late 80‟s and early 90‟s at the National Research Institute for Mathematics and Computer Science in the Netherlands. It has been derived from many languages such as ABC, Modula-3, C, C++, Algol68, SmallTalk, UNIX shell and other scripting languages.Since early 90‟s Python has been improved tremendously. Its version 1.0 was released in 1991, which
1.2.1 Defining and Processing Arrays 37 1.2.2 Array methods 40 Let Us Sum Up Check Your Progress 1.8 Unit- Summary 43 1.9 Glossary 44 1.10 Self- Assessment Questions 44 1.11 Exercises 44 1.12 Quiz - Answers 45 1.13 Suggested Readings 45 1.14 Open Source E-Content Links 46 1.15 References 46
introduced several new functional programming tools. While version 2.0included list comprehension was released in 2000 by the Be Open Python Labs team.
Python 2.7 which is still used today will be supported till 2020. Currently Python 3.6.4 is already available. The newer versions have better features like flexible string representation etc., Although Python is copyrighted, its source code is available under GNU General Public License (GPL) like that Perl. Python is currently maintained by a core development team at the institute which is directed by Guido Van Rossum. These days, from data to web development, Python has emerged as very powerful and popular language. It would be surprising to know that python is actually older than Java, R and JavaScript.
Simple : Reading a program written in Python feels almost like reading english. The main strength of Python which allows programmer to concentrate on the solution to the problem rather than language itself. Easy to Learn: Python program is clearly defined and easily readable. The structure of the program is simple. It uses few keywords and clearly defined syntax. Versatile: Python supports development of wide range of applications such as simple text processing, WWW browsers and games etc.. Free and Open Source: It is a Open Source Software. So, anyone can freely distribute it, read the source code, edit it, and even use the code to write new (free) programs. High-level Language: While writing programs in Python we do not worry about the low-level details like managing memory used by the program. Interactive: Programs in Python work in interactive mode which allows interactive testing and debugging of pieces of code. Programmer can easily interact with the interpreter directly at the python prompt to write their programs. Portable: It is a portable language and hence the programs behave the same on wide variety of hardware platforms with different operating systems.
Python literals or constants are the notation for representing a fixed value in source code. In contrast to variables, literals (123, 4.3, "Hello") are static values or you can say constants which do not change throughout the operation of the program or application.
Example
x= Here 10 is a literal as numeric value representing 10, which is directly stored in memory. However, y=x*
Here, even if the expression evaluates to 20, it is not literally included in source code. You can also declare an int object with built-in int() function. However, this is also an indirect way of instantiation and not with literal. x=(int)
Number The value of a literal constant can be used directly in programs. For example, 7, 3.9, 'A', and "Hello" are literal constants. Numbers refers to a numeric value. You can use four types of numbers in Python program- integers, long integers, floating point and complex numbers. Numbers like 5 or other whole numbers are referred to as integers. Bigger whole numbers are called long integers.
For example, 535633629843L is a long integer. Numbers like are 3.23 and 91.5E-2 are termed as floating point numbers. Numbers of a + bj form (like -3 + 7j) are complex numbers.
>>>50+40- 35
55
A Literals Boolean type can have one of the two values- True or False.
>>>bvar=True >>>print(bvar) True
False
>>>”Python” True
>>>20 != 20 False
>>>”Python” != “Python3.3” True
False >>>90<= True
False
false
>>> 87<87. False
True
True
String
A string is a group of characters. Using Single Quotes ('): For example, a string can be written as 'HELLO'. Using Double Quotes ("): Strings in double quotes are exactly same as those in single quotes. Therefore, 'HELLO' is same as "HELLO". Using Triple Quotes (''' '''): You can specify multi-line strings using triple quotes. You can use as many single quotes and double quotes as you want in a string within triple quotes.
>>>”Hello” ‘Hello’
>>>’Hello’ ‘Hello’
>>>’’’Hello’’’ ‘Hello’
Unicode Strings
Unicode is a standard way of writing international text. That is,if you want to write some text in your native language like hindi,then you need to have a Unicode-enable text editor. Python allows you to specify Unicode text by prefixing the string with a u or U. For Example: u”Sample Unicode string” Note :The „U‟ prefix specifies that the file contains text written in language other than English
Escape Sequences
Some characters (like ", ) cannot be directly included in a string. Such characters must be escaped by placing a backslash before them.
Names of identifiers are case-sensitive; for instance, my name, and MyName isn't something very similar.
Examples of valid identifiers : a123, _n, n_9, etc.
Examples of invalid identifiers : 1a, n%4, n 9, etc.
Declaring Variable and Assigning Values
Python doesn't tie us to pronounce a variable prior to involving it in the application. It permits us to make a variable at the necessary time. In Python, we don't have to explicitly declare variables. The variable is declared automatically whenever a value is added to it. The equal (=) operator is utilized to assign worth to a variable.
Example number = 10 site_name = 'programiz.pro' print(site_name) Output 'programiz.pro'
Example: Assigning multiple values to multiple variables a, b, c = 5, 3.2, 'Hello'
x=y=z=
print (a) # prints 5
print (b) # prints 3.
print (c) # prints Hello
Local Variable
The variables that are declared within the function and have scope within the function are known as local variables. Let's examine the following illustration.
Example - def add(): # Defining local variables. They has scope only within a function
a = 20
b = 30
c = a + b
print("The sum is:", c)
add() # Calling a function
Output: The sum is: 50
Global Variables
Global variables can be utilized all through the program, and its extension is in the whole program. Global variables can be used inside or outside the function. By default, a variable declared outside of the function serves as the global variable. Python gives the worldwide catchphrase to utilize worldwide variable inside the capability. The function treats it as a local variable if we don't use the global keyword.
Example - x = 101 # Declare a variable and initialize it def mainFunction(): # Global variable in function
global x print(x)
x = 'Welcome To Python’ print(x) mainFunction() print(x) Output:
assert else if not while break except import or with class False in pass yield continue finally is raise def for lambda return
The data stored in the memory can be of many types. For example, a person’s name is stored as an alphabetic value and its address is stored as an alphanumeric value. Sometimes, we also need to store answer in terms of only ‘yes’ or ‘no’, i.e., true or false. This type of data is known as Boolean data. Python has six basic data types which are as follows:
>>>num 2.5 # Output Note : In all the earlier versions of Python 3, slash (/) operator worked differently. When both numerator and denominator are integers, then the result will be an integer. The slash operator removes the fraction part.
The result becomes a floating number when either the numerator or the denominator is a floating number. When both the numerator and the denominator are floating numbers, the result is again a floating number. The division operator provides accurate results even when both the numerator and the denominator are integers. Example >>> 5/ 1.5 # Output
String Besides numbers, strings are another important data type. Single quotes or double quotes are used to represent strings. A string in Python can be a series or a sequence of alphabets, numerals and special characters. Similar to C, the first character of a string has an index 0. There are many operations that can be performed on a string. There are several operators such as slice operator ([]) and [:]), concatenation operator (+), repetition operator (*), etc. Slicing is used to take out a subset of the string, concatenation is used to combine two or more than two strings and repetition is used to repeat the same string several times. Example >>>sample_string =”Hello” # store string value >>>sample_string # display string value ‘Hello’ # Output >>>sample_string + “World” # use of + operator ‘HelloWorld’ # Output >>>sample_string * 3 # use of * operator ‘HelloHelloHello’ # Output
[‘five’, 6, ‘five’, 6, ‘five’, 6] # Output >>>first[0:2] # display sublist [1, ‘two’]
Tuple Similar to a list, a tuple is also used to store sequence of items. Like a list, a tuple consists of items separated by commas. However, tuples are enclosed within parentheses rather than within square brackets. Example >>>third=(7, “eight”,9, 10.0) >>>third (7, ‘eight’, 9, 10.0) # Output Lists and tuples have the following differences: In lists, items are enclosed within square brackets [], whereas in tuples, items are enclosed within parentheses (). Lists are mutable whereas Tuples are immutable. Tuples are read only lists. Once the items are stored, the tuple cannot be modified.
Dictionary It is the same as the hash table type. The order of elements in a dictionary is undefined. But, we can iterate over the following:
A Python dictionary is an unordered collection of key-value pairs. When we have the large amount of data, the dictionary data type is used. Keys and values can be of any type in a dictionary. Items in dictionary are enclosed in the curly-braces{} and separated by the comma (,). A colon (:) is used o separate key from value. A key inside the square bracket [] is used for accessing the dictionary items.
Example >>> dict1 = {1:"first line", "second":2} # declare dictionary >>>dict1[3] = "third line" # add new item
>>> dict1 # display dictionary {1: 'first line', 'second': 2, 3: 'third line'} #Output >>>dict1.keys() # display dictionary keys [1, 'second', 3] # Output >>>dict1.values() # display dictionary values ['first line', 2, 'third line'] # Output
Boolean In a programming language, mostly data is stored in the form of alphanumeric but sometimes we need to store the data in the form of ‘Yes’ or ‘No’. In terms of programming language, Yes is similar to True and No is similar to False. This True and False data is known as Boolean Data and the data types which stores this Boolean data are known as Boolean Data Types.
Example >>> a = True >>>type(a)
>>> x = False >>>type(x)
Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it’s various operations. Syntax print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush) Parameters: value(s): Any value, and as many as you like. Will be converted to a string before printed
String literals in Python’s print statement are primarily used to format or design how a specific string appears when printed using the print() function. \n: This string literal is used to add a new blank line while printing a statement. “”: An empty quote (“”) is used to print an empty line. >>>print("Python Programming \n is OOP.") Python Programming is OOP.
The end keyword is used to specify the content that is to be printed at the end of the execution of the print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print() statement.
Example #using print() with end and without end parameters.
print ("Python Programming is OOP ")
print ("Python Programming is OOP ", end= "&&") print("Welcome to Python World") Output: Python Programming is OOP Python Programming is OOP&&Welcome to Python World
Print concatenation
>>>print(‘Python Programming supports ' + OOP.') Python Programming supports OOP Print using formatting
>>>a,b,=10, print('The value of a is {} and b is {}'.format(a,b)) The value of a is 10 and b is 1000
“sep” parameter in print()
The print() function can accept any number of positional arguments. To separate these positional arguments, the keyword argument “sep” is used.
Example a= b= c= print(a,b,c,sep="-") Output: 12-12-
In a programming language, the input from keyboard by user plays the most important role in executing a program. There is hardly any program which executes without some input. The input in many programs is prompted by the user and the user uses the keyboard in order to provide input for the program to execute. Python programming language also provides the facility to user to provide input from keyboard.
Prompting the input from user in Python is through function has an optional parameter, which is the prompt string. When the input() input() function. input() function is called, in order to take input from the user then the execution of program halts and waits for the user to provide an input. The input is given by the user through keyboard and it is ended by the return key. input() function interprets the input provided by the user, i.e. if user provides an integer value as input then the input function will return this integer value. On the other hand, if the user has input a String, then the function will return a string.
Example >>>name = input(“What is your Name?”) >>> print (“Hello “ + name + “!”) What is your Name? ‘John’