R19 Python UNIT - 1 (Ref-2)
R19 Python UNIT - 1 (Ref-2)
K
Assoc., Prof., CSE
UNIT-1 Introduction: Introduction to Python, Program Development Cycle, Input, Processing, and Output,
Displaying Output with the Print Function, Comments, Variables, Reading Input from the Keyboard, Performing
Calculations, Operators. Type conversions, Expressions, More about Data Output. Data Types, and Expression: Strings
Assignment, and Comment, Numeric Data Types and Character Sets, Using functions and Modules. Decision Structures
and Boolean Logic: if, if-else, if-elif-else Statements, Nested Decision Structures, Comparing Strings, Logical Operators,
Boolean Variables. Repetition Structures: Introduction, while loop, for loop, Calculating a Running Total, Input
Validation Loops, Nested Loops.
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.
Python is a programming language that lets you work quickly and integrate systems more efficiently.
There are two major Python versions: Python 2 and Python 3. Both are quite different.
1) Finding an Interpreter:
Before we start Python programming, we need to have an interpreter to interpret and run our
programs. http://ideone.com/ or http://codepad.org/ that can be used to run Python programs
without installing 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/.
Just type in the following code after you start the interpreter.
2020-2021
www.Jntufastupdates.com 1
Unit-1 Python Programming
# Script Begins
# Scripts Ends
Line 2: [print("welcome to Technical World") ]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.
Applications:
1. Web development – Web framework like Django and Flask are based on Python. They help
you write server side code which helps you manage database, write backend programming
logic, mapping urls etc.
2. Machine learning – There are many machine learning applications written in Python. Machine
learning is a way to write a logic so that a machine can learn and solve a particular problem on
its own. For example, products recommendation in websites like Amazon, Flipkart, eBay etc. is
a machine learning algorithm that recognises user’s interest. Face recognition and Voice
recognition in your phone is another example of machine learning.
3. Data Analysis – Data analysis and data visualisation in form of charts can also be developed
using Python.
4. Scripting – Scripting is writing small programs to automate simple tasks such as sending
automated response emails etc. Such type of applications can also be written in Python
programming language.
7. Desktop applications – You can develop desktop application in Python using library like
TKinter or QT.
2020-2021
www.Jntufastupdates.com 2
Unit-1 Python Programming
Features of Python:
1. Simple and easy to learn.
2. Free ware and Open source.
3. High level programming language.
4. Python id platform independent.
5. Portability.
6. Dynamically typed.
7. Both procedure oriented and object oriented.
8. Interpreted programming language.
9. Extensible.
10. Embedded.
11. Extensive library.
2020-2021
www.Jntufastupdates.com 3
Unit-1 Python Programming
2. Easy to Learn: Learning python is easy as this is a expressive and high level programming
language, which means it is easy to understand the language and thus easy to learn.
3. Cross platform: Python is available and can run on various operating systems such as Mac,
Windows, Linux, Unix etc. This makes it a cross platform and portable language.
5. Large standard library: Python comes with a large standard library that has some handy codes and
functions which we can use while writing code in Python.
6. Free: Python is free to download and use. This means you can download it for free and use it in
your application. Python is an example of a FLOSS (Free/Libre Open Source Software), which means
you can freely distribute copies of this software, read its source code and modify it.
7. Supports exception handling: If you are new, you may wonder what is an exception? An
exception is an event that can occur during program exception and can disrupt the normal flow of
program. Python supports exception handling which means we can write less error prone code and can
test various scenarios that can cause an exception later on.
9. Automatic memory management: Python supports automatic memory management which means
the memory is cleared and freed automatically. You do not have to bother clearing the memory.
Limitations of Python:
1. Performance is not up to the mark.
2. For mobile applications it is not up to the mark.
Flavours of python:
1. Cpython
2. Jython (or) Jpython.
3. Ironpython.
4. Pypy.
5. Rubypython.
6. Anaconda python.
7. Stackless
2020-2021
www.Jntufastupdates.com 4
Unit-1 Python Programming
Local Environment Setup: Open a terminal window and type "python" to find out if it
is already installed and which version is installed.
Getting Python for Windows platform: Binaries of latest version of Python 3 (Python
3.6.5) are available in https://www.python.org/
Download the software and save to hard drive. Double click on the install file and install software as
per instructions. By default, IDLE will install in to the system as default IDE (Integrated development
Environment). After installing software it is very important to set the path if path is not set by default.
Above 3 versions are not necessary to set the path. It will set automatically by default.
2020-2021
www.Jntufastupdates.com 5
Unit-1 Python Programming
A shell window contains an opening message followed by the special symbol>>>, called a shell
prompt. The cursor at the shell prompt waits for you to enter a Python command. Note that you can
get immediate help by entering help at the shell prompt or selecting Help from the window’s drop-
down menu. When you enter an expression or statement, Python evaluates it and displays its result, if
there is one, followed by a new prompt.
To quit the Python shell, you can either select the window’s close box or press the Control + D key
combination.
Most of the professionals are use default IDE i.e IDLE to work with python environment. There are
Some of the key features of IDLE it offers are:
• Python shell with syntax highlighting.
• Multi-window text editor.
• Code auto completion.
• Intelligent indenting.
• Program animation and stepping which allows one line of code to run at a time helpful for
debugging.
• Persistent breakpoints.
• Finally, Call stack visibility.
• Program Development Life Cycle (PDLC) is a systematic way of developing quality software.
It provides an organized plan for breaking down the task of program development into
manageable chunks, each of which must be successfully completed before moving on to the
next phase.
• Python's development cycle is dramatically shorter than that of traditional tools as shown in
figure
2020-2021
www.Jntufastupdates.com 6
Unit-1 Python Programming
• In Python, there are no compile or link steps -- Python programs simply import modules at
runtime and use the objects they contain. Because of this, Python programs run immediately
after changes are made and in cases where dynamic module reloading can be used, it's even
possible to change and reload parts of a running program without stopping it at all.
Variables
• Variables are nothing but reserved memory locations to store values. It means that when you
create a variable, you reserve some space in the memory. Based on the data type of a
variable, the interpreter allocates memory and decides what can be stored in the reserved
memory
• Python variables do not need explicit declaration to reserve memory space. The declaration
happens automatically when you assign a value to a variable. The equal sign (=) is used to
assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable.
For example :
counter =100 # An integer assignment
miles =1000.0 # A floating point
name ="John" # A string
print(counter)
print(miles)
print(name)
Here, 100, 1000.0 and "John" are the values assigned to counter, miles, and name variables,
respectively. This produces the following result −
Output:
100
1000.0
‘John’
Multiple Assignments: Python allows you to assign a single value to several variables simultaneously.
Python Comments
Comments are descriptions that help programmers better understand the intent and functionality of the
program. It is completely ignored by the Python interpreter.
Single-Line Comments in Python: In Python, we use the hash symbol # to write a single-line comment.
• Some of the functions like input() and print() are widely used for standard input and output operations
respectively.
Let us see the output section first. : Python Output Using print () function
• We use the print() function to output data to the standard output device (screen). We can also output
data to a file
print() function:The print() function prints the given object to the standard output device (screen) or to the text
stream file.
Example 1:
print('This sentence is output to the screen')
Example 2:
a=5
print('The value of a is', a)
Example 3:
print("Python is fun.")
a=5
# Two objects are passed
print("a =", a)
b=a
# Three objects are passed
print('a =', a, '= b')
2020-2021
www.Jntufastupdates.com 9
Unit-1 Python Programming
Output:
Python is fun.
a= 5
a=5=b
Output:
Tirumala Engineering College
Computer Science Engineering
world
print(5*'cse\n')
Output:
cse
cse
cse
cse
2020-2021
www.Jntufastupdates.com 10
Unit-1 Python Programming
cse
print(5*'cse\t') Output: cse cse cse cse cse
(b) a,b,c=10,20,30
print(‘values are:’,a,b,c)
>>>print('values are:',10,20,30,sep="--")
• The end key of print function will set the string that needs to be appended when printing is
done.
• By default, the end key is set by newline character (By default, attribute end =’\n’ in print
function). So after finishing printing all the variables, a newline character is appended. Hence,
we get the output of each print statement in different line. But we will now overwrite the
newline character by any character at the end of the print statement.
Example-1:
2020-2021
www.Jntufastupdates.com 11
Unit-1 Python Programming
Output:
Tirumala
rajani
devansh
Note: when you observe output 1st print statement prints output Tirumala and immediately takes
new line character and execute 2nd print statement and followed.
Example-2:
• print('devansh')
Output:
Tirumala$rajani*devansh
• print(19,20,30,sep=':',end='$$$')
• print(40,50,sep=':')
• print(70,80,sep=':',end='&&&')
• print(90,100)
Output: 19:20:30$$$40:50
70:80&&&90 100
Python | Output Formatting
• There are several ways to present the output of a program, data can be printed in a human-
readable form, or written to a file for future use. Sometimes user often wants more control
the formatting of output than simply printing space-separated values. There are several ways
to format output.
1. Formatting output using String modulo operator (%):
Syntax: print (‘formatted string’ %( variable list)
2020-2021
www.Jntufastupdates.com 12
Unit-1 Python Programming
The % operator can also be used for string formatting. string modulo operator ( % ) is still
available in Python(3.x) and user is using it widely.
Example 1
# Python program showing how to use string modulo operator (%) to print fancier output
Example 2
(a) a=6
print(‘a value is =%i’ %a)
Output: a value is =6
(b) a=6;b=7;c=8
print('a value is =%i and b=%f and c=%i' %(a,b,c))
Output: a value is =6 and b=7.000000 and c=8
2. print function with replacement operator {}or format function
str.format() is one of the string formatting methods in Python3, which allows multiple
substitutions and value formatting. This method lets us concatenate elements within a string
through positional formatting.
2020-2021
www.Jntufastupdates.com 13
Unit-1 Python Programming
Example:1
Name= ‘John’
Salary=’1000’
print(‘hello my name is {} and my salary is {}’.format(Name,Salary))
Example: 3
name='John'
salary=1000
print('hello my name is "{0}" and my salary is "{1}"'.format(name,salary))
Output: hello my name is "John" and my salary is "1000"
Example: 4
print('hello my name is "{0}" and my salary is "{1}"'.format(salary,name))
Output: hello my name is "1000" and my salary is "john"
Reading Input from the Keyboard: In python input() is used to read the input from the keyboard
dynamically. By default, the value of the input function will be stored as a string
Syntax: Variable name =input(‘prompt’)
Example:
name =input("Enter Employee Name ")
salary =input("Enter salary ")
company =input("Enter Company name ")
print("\n")
print("Printing Employee Details")
print("Name","Salary","Company")
print(name, salary, company)
Output:
Enter Employee Name Jon
Enter salary 12000
Enter Company name Google
Accept an numeric input from User: To accept an integer value from a user in Python. We need to
convert an input string value into an integer using a int() function.
We need to convert an input string value into an integer using a float() function.
Output:
Enter first number 20
Enter second number 40
First Number: 20
Second Number: 40
Addition of two number is: 60
Get multiple input values from a user in one line: In Python, we can accept two or three values from
the user in one input() call.
Example: In a single execution of the input() function, we can ask the user hi/her name, age, and
phone number and store it in three different variables.
name, age, phone =input("Enter your name, Age, Percentage separated by space ").split()
print("\n")
print("User Details: ", name, age, phone)
Output:
Enter your name, Age, Percentage separated by space John 26 75.50
User Details: John 26 75.50
Performing Calculations
Computers are great at math problems! How can we tell Python to solve a math problem for us? In
this we use numbers in Python and the special symbols we use to tell it what kind of calculation to
do.Example-1:
1. print(2+2)
2. print("2"+"2")
Output:
4
22
Example-2:
Subtraction:
print(2 - 2)
Multiplication:
print(2 * 2)
2020-2021
www.Jntufastupdates.com 16
Unit-1 Python Programming
Division:
print(2 / 2)
Question: Why did the last statement output 1.0?
Answer: When Python does division, it uses a different kind of number called a float. Floats always
have a decimal point. Integers are always whole numbers and do not have decimal points.
Run:
print(7/2)
Calculations in Python follow the Order of Operations, which is sometimes called PEMDAS.
Run:
print((6 - 2) * 5)
print(6 - 2 * 5)
Subtraction:
print(2 - 2)
Multiplication:
print(2 * 2)
Division:
print(2 / 2)
Example-3:
Example-4:
The modulo operator (%) finds the remainder of the first number divided by the second number.
Run:
print(12 % 10)
12 / 10 = 1 with a remainder of 2.
Integer division (//) is like normal division, but it rounds down if there is a decimal point.
2020-2021
www.Jntufastupdates.com 17
Unit-1 Python Programming
Run:
print(5 // 2)
5 / 2 = 2.5, which is rounded down to 2
Exponentiation (**) raises the first number to the power of the second number.
Run:
print(3 ** 2)
This is the same as 32
Example-5:
Remember, input() returns a string, and we can’t do math with strings. Fortunately, we can change
strings into ints like so:
two = "2"
two = int(two)
print(two + two)
If you need to work with a decimal point, you can change it to a float instead:
two = float(two)
Example-6:
Activity 1:
Do you know anyone who tends to one-up you in conversation? In this activity, we’ll make a simple
chatbot that asks a series of questions, explaining to you why it’s superior after each one. The robot
will have a variable level of one-upmanship.
We’ll use print, input, and math operators and variables to accomplish this.
Example-7:one_up_level = 1
a1 = input("How many seconds does it take you to run the 100 meter dash?")
a1 = int(a1)
print("That's cool. I can do it in", a1 - one_up_level, "seconds though. And I don't even have legs,
sooooo…")
a2 = input("But what about your GPA? I'm sure that's pretty good, eh? (Enter your GPA)")
a2 = float(a2)
print("Alright. Mine was", a2 + one_up_level)
print("Not that it matters, lol")
Explanation: No matter what number you tell the chatbot, in his calculations it’ll always inform you
that he’s somehow better. It does this by adding or subtracting, depending on which operation
flatters it. Many students delete this program after the exercise.
2020-2021
www.Jntufastupdates.com 18
Unit-1 Python Programming
Example-8:
Activity 2: Make a simple program that tells you if a given number is a multiple of another given
number.
A Correct Answer:
print("Is _ a multiple of _?")
num1 = input("Write the first number: ")
num2 = input("Write the second number: ")
print(int(num1) % int(num2))
print("If the number above is zero, then", num1, "is a multiple of", num2)
Explanation:
Remember, the modulo finds the remainder of the first number divided by the second number. If it
gives us zero, then we know that the second number divides evenly into the first number.
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
1. Python Arithmetic Operators.
2. Python Comparison/relational Operators
3. Python Logical Operators
4. Python Assignment Operators
5. Python Identity Operators
6. Python Membership Operators
7. Python Bitwise Operators
• Arithmetic operators
2020-2021
www.Jntufastupdates.com 19
Unit-1 Python Programming
Example:
x ,y= 15,4
# Output: x + y = 19
print('x + y =',x+y)
# Output: x - y = 11
print('x - y =',x-y)
# Output: x * y = 60
print('x * y =',x*y)
# Output: x / y = 3.75
print('x / y =',x/y)
The calculation which done both integer and floating-point number is called mixed-mode arithmetic.
When each operand is of a different type.
Example:
9/2.0 ---> 4.5
• Relational operators
2020-2021
www.Jntufastupdates.com 20
Unit-1 Python Programming
Example:
x=5
y=2
# Output: x == y is False
print('x == y is',x==y)
# Output: x != y is True
print('x != y is',x!=y)
• Logical operator :
Example :
x = True y = False
# Output: x or y is True
print('x or y is',x or y)
2020-2021
www.Jntufastupdates.com 21
Unit-1 Python Programming
• Assignment operator :
2020-2021
www.Jntufastupdates.com 22
Unit-1 Python Programming
• Identity operators
x1 , y1 = 5 ,5
x2 , y2 = "cse",”cse”
x3 , y3= [1,2,3],[1,2,3]
print(id(x1)) #20935504
print(id(y1)) #20935504
print(x1 is y1)
print(x1 is not y1)
print(id(x2)) #21527296
print(id(y2)) #21527296
print(x2 is y2)
print(x2 is not y2)
print(id(x3)) #45082264
print(id(y3)) #45061624
print(x3 is y3)
a=10
b=15
x=a
y=b
z=a
print(x is y)
print(x is a)
print(y is b)
print(x is not y)
print(x is not a)
print(x is z)
2020-21
www.Jntufastupdates.com 23
Unit-1 Python Programming
• Membership operators:
in: "in" operator return true if a character or the entire substring is present in the
specified string, otherwise false.
not in: "not in" operator return true if a character or entire substring does not exist in the
specified string, otherwise false.
Example:
str1="ramuit"
str2="tirumalacse"
str3="ramu"
str4="tirumala"
print(str3 in str1) # True
print(str4 in str2) # True
print(str3 in str2) # False
print("ratan" in "ratanit") #true
print("ratan" in "durgasoft") #False
print(str3 not in str1) # False
print(str4 not in str2) # False
print(str3 not in str2) # True
print("ratan" not in "ratanit") # false
print("ratan" not in "anu") # true
• Bitwise operator: -
2020-21
www.Jntufastupdates.com 24
Unit-1 Python Programming
Numbers
Boolean
• bool : type
• represent True/False values.
• 0 =False & 1 =True
• Logical operators and or not return value is Boolean
Strings
• str : type
• Represent group of characters
• Declared with in single or double or triple quotes
• It is immutable modifications are not allowed.
2020-21
www.Jntufastupdates.com 25
Unit-1 Python Programming
Lists
• list : type
• group of heterogeneous objects in sequence.
• This is mutable modifications are allowed
• Declared with in the square brackets [ ]
Tuples
• tuple : type
• group of heterogeneous objects in sequence
• this is immutable modifications are not allowed.
• Declared within the parenthesis ( )
Sets
• set : type
• group of heterogeneous objects in unordered
• this is mutable modifications are allowed
• declared within brasses { }
Dictionaries
• dict : type
• it stores the data in key value pairs format.
• Keys must be unique & value
• It is mutable modifications are allowed.
• Declared within the curly brasses {key:value}
2020-21
www.Jntufastupdates.com 26
Unit-1 Python Programming
• true& false are result values of comparison operation or logical operation in python.
• true & false in python is same as 1 & 0 1=true 0=false
• except zero it is always True.
• while writing true & false first letter should be capital otherwise error message will be
generated.
• Comparison operations are return Boolean values.
Example:
print (1 == 1) #true
2020-21
www.Jntufastupdates.com 27
Unit-1 Python Programming
• String index starts from 0, trying to access character out of index range will generate
IndexError.
• In python it is not possible to add any two different data types, possible to add only same data
type data.
Slice Notation
• <string_name>[startIndex:endIndex],
• <string_name>[:endIndex],
• <string_name>[startIndex:]
• s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4 s[1:] is
'ello' -- omitting either index defaults to the start or end of the string
• s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing
• s[1:100] is 'ello' -- an index that is too big is truncated down to the string length s[-1] is 'o' --
last char (1st from the end)
Practice Examples:
• List is used to store the group of values & we can manipulate them, in list the values are
stores in index format starts with 0;
• List is mutable object so we can do the manipulations.
• A python list is enclosed between square([]) brackets.
• In list insertion order is preserved it means in which order we inserted element same
order output is printed.
• A list can be composed by storing a sequence of different type of values separated by
commas.
<list_name>=[value1,value2,value3,...,valuen];
• The list contians forward indexing & backword indexing.
Practice Examples:
2020-21
www.Jntufastupdates.com 29
Unit-1 Python Programming
• tuple : type
• group of heterogeneous objects in sequence
• this is immutable modifications are not allowed.
• Declared within the parenthesis ( )
• Insertion order is preserved it means in which order we inserted the objects same order
output is printed.
• The tuple contains forward indexing & backward indexing.
Example:
2020-21
www.Jntufastupdates.com 30
Unit-1 Python Programming
set:
Python also includes a data type for sets. A set is an unordered collection with no duplicate elements.
Basic uses include membership testing and eliminating duplicate entries. Set objects also support
mathematical operations like union, intersection, difference, and symmetric difference.
Curly braces or the set() function can be used to create sets.
Note: to create an empty set you have to use set(), not {}
Example:
# set of integers
my_set = {1, 2, 3}
print(my_set)
print(type(my_set))
#creates empty set
s=set()
print(s)
# set of mixed datatypes
my_set = {1.0, "Hello", (1, 2, 3)}
print(my_set)
# set do not have duplicates
# Output: {1, 2, 3, 4}
my_set = {1,2,3,4,3,2}
print(my_set)
Frozenset:
• It is a new class that has the characteristics of a set, but its elements cannot be changed
once assigned. While tuples are immutable lists, frozensets are immutable sets.
• Frozensets can be created using the function frozenset().
• This datatype supports methods like copy(), difference(), intersection(), isdisjoint(),
issubset(),issuperset(), symmetric_difference() and union(). Being immutable it does not
have method that add or remove elements.
Dictionary data type:
• List,tupple ,set data types are used to represent individual objects as a single entity.
• To store the group of objects as a key-value pairs use dictionary.
• A dictionary is a data type similar to arrays, but works with keys and values instead of indexes.
• Each value stored in a dictionary can be accessed using a key, which is any type of object (a
string, a number, a list, etc.) instead of using its index to address it.
• The keys must be unique keys but values can be duplicated.
2020-21
www.Jntufastupdates.com 31
Unit-1 Python Programming
Example:
phonebook = {}
phonebook["ramu"] = 935577566
phonebook["anu"] = 936677884
phonebook["devi"] = 9476655551
print(phonebook)
Example:
Alternatively, a dictionary can be initialized with the same values in the following notation:
phonebook = { "ramu" : 935577566, "anu" : 936677884, "devi" : 9476655551}
print(phonebook)
• Dictionaries can be created using pair of curly braces ( {} ). Each item in the dictionary
consist of key, followed by a colon, which is followed by value. And each item is separated
using commas (,) .
• An item has a key and the corresponding value expressed as a pair, key: value.
• in dictionary values can be of any data type and can repeat,.
• keys must be of immutable type (string, number or tuple with immutable elements) and
must be unique.
Example:
# empty dictionary
my_dict = {}
print(my_dict)
# dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
print(my_dict)
# dictionary with mixed keys
my_dict = {'name': 'John', 1: [2, 4, 3]}
print(my_dict)
2020-21
www.Jntufastupdates.com 32
Unit-1 Python Programming
If-else statement:
• if the condition true if block executed.
• if the condition false else block executed.
Example-1: Example-2:
a=10 In python 0=false 1=true
if(a>10): if(1):
print("if body") print("hi ramu")
else: else:
print("else body") print("hi anu")
Example-3:
In python Boolean constants start with uppercase character.
if(False):
print ("true body")
else:
print ("false body")
Example-4:
year = 2000
if year % 4 == 0:
print("Year is Leap")
else:
print("Year is not Leap")
2020-21
www.Jntufastupdates.com 33
Unit-1 Python Programming
elif statement :
Example-1
number = 23
guess = int(input("Enter an integer : "))
if guess == number:
print("Congratulations, you guessed it.")
elif guess < number:
print("No, it is a little higher number")
else:
print("No, it is a little lower number")
print("rest of the app")
Example:
x = int(input("Please enter an integer: "))
if x > 0:
print ("Positive")
elif x == 0:
print ("Zero")
2020-21
www.Jntufastupdates.com 34
Unit-1 Python Programming
for loop :
• Used to print the data n number of times based on condition.
• If you do need to iterate over a sequence of numbers, use the built-in function
range().
range() function :
range(10) 1-10
range(5, 10) 5 through 9
range(0, 10, 3) 0, 3, 6, 9
range(-10, -100, -30) -10, -40, -70
Syntax:
for iterator_name in range(10):
…statements…
for iterator_name in range(start,end):
…statements…
for iterator_name in range(start,stop,increment):
…statements…
Example:
for x in range(10):
print("Tirumala World",x)
for x in range(8,10):
print("CSE World",x)
for x in range(3,10,3):
print("Technical world",x)
for x in range(-20,-10):
print("Python",x)
for x in range(-20,-10,3):
print("Running Trendy",x)
for i in range(-10,-100,-15):
print(i)
for i in range(10, 0, -2):
print (i)
2020-21
www.Jntufastupdates.com 35
Unit-1 Python Programming
Example: else is always executed after the while loop is over unless a break statement is
encountered.
a=0
while(a<10):
print ("Python New Tech ",a)
a=a+1
else:
print("else block after while");
print("process done")
Example: in below example else not executed.
a=0
while(a<10):
print ("hi Students”, a)
a=a+1
if(a==2):
break
else:
print("else block after while");
print("process done")
• The Python interpreter has a number of built-in functions. They are loaded automatically as
the interpreter starts and are always available.
• For example, print() and input() for I/O.
• Number conversion functions int(), float(), complex(), data type conversions
list(), tuple(), set(), etc.
• In addition to built-in functions, a large number of pre-defined functions are also available as a
part of libraries bundled with Python distributions. These functions are defined as modules.
• A module is a file containing definitions of functions, classes, variables, constants or any other
Python objects. Contents of this file can be made available to any other program.
• Built-in modules are written in C and integrated with the Python interpreter.
• Each built-in module contains resources for certain system-specific functionalities such as OS
management, disk IO, etc. The standard library also contains many Python scripts (with the .py
extension) containing useful utilities.
• To display a list of all available modules, use the following command in the Python console:
>>> help('modules')
Which displays all modules that are supported in the python 3
2020-21
www.Jntufastupdates.com 38
Unit-1 Python Programming
✓ The math module contains functions for calculating various trigonometric ratios for a given
angle.
✓ The functions (sin, cos, tan, etc.) need the angle in radians as an argument. We, on the other
hand, are used to express the angle in degrees.
✓ The math module presents two angle conversion functions: degrees() and radians(), to convert
the angle from degrees to radians and vice versa.
✓ For example, the following statements convert the angle of 30 degrees to radians and back
(Note: π radians is equivalent to 180 degrees).
>>>math.radians(30)
0.5235987755982988
>>>math.degrees(math.pi/6)
29.999999999999996
✓ The following statements show sin, cos and tan ratios for the angle of 30 degrees
(0.5235987755982988 radians):
>>math.sin(0.5235987755982988)
0.49999999999999994
>>>math.cos(0.5235987755982988)
0.8660254037844387
>>>math.tan(0.5235987755982988)
0.5773502691896257
✓ You may recall that sin(30)=0.5, cos(30)=32 (which is 0.8660254037844387) and tan(30)= 13
(which is 0.5773502691896257).
math.log():
✓ The math.log() method returns the natural logarithm of a given number. The natural logarithm
is calculated to the base e.
>>>math.log(10)
2.302585092994046
2020-21
www.Jntufastupdates.com 39
Unit-1 Python Programming
math.log10():
✓ The math.log10() method returns the base-10 logarithm of the given number. It is called the
standard logarithm.
>>>math.log10(10)
1.0
math.exp():
✓ The math.exp() method returns a float number after raising e (math.e) to given number. In
other words, exp(x) gives e**x.
>>>math.exp(10)
1.0
This can be verified by the exponent operator.
>>>math.e**10
22026.465794806703
math.pow():
✓ The math.pow() method receives two float arguments, raises the first to the second and
returns the result. In other words, pow(4,4) is equivalent to 4**4.
>>>math.pow(2,4)
16.0
>>>2**4
16
math.sqrt():
✓ The math.sqrt() method returns the square root of a given number.
>>>math.sqrt(100)
10.0
>>>math.sqrt(3)
1.7320508075688772
Representation functions:
✓ The ceil() function approximates the given number to the smallest integer, greater than or
equal to the given floating point number. The floor() function returns the largest integer less
than or equal to the given number.
>>>math.ceil(4.5867)
5
>>>math.floor(4.5687)
4
2020-21
www.Jntufastupdates.com 40
Unit-1 Python Programming
2020-21
www.Jntufastupdates.com 41
Unit-1 Python Programming
✓ random.randrange(): Returns a randomly selected element from the range created by the
start, stop and step arguments. The value of start is 0 by default. Similarly, the value of step is
1 by default.
>>>random.randrange(1,10)
2
>>>random.randrange(1,10,2)
5
>>>random.randrange(0,101,10)
80
✓ random.choice(): Returns a randomly selected element from a non-empty sequence. An
empty sequence as argument raises an IndexError.
>>>import random
>>>random.choice('computer')
't'
>>>random.choice([12,23,45,67,65,43])
45
>>>random.choice((12,23,45,67,65,43))
67
✓ random.shuffle(): This functions randomly reorders the elements in a list.
>>>numbers=[12,23,45,67,65,43]
>>>random.shuffle(numbers)
>>>numbers
[23, 12, 43, 65, 67, 45]
>>>random.shuffle(numbers)
>>>numbers
[23, 43, 65, 45, 12, 67]
Step 1: Declare the function with the keyword def followed by the function name.
Step 2: Write the arguments inside the opening and closing parentheses of the function, and end
the declaration with a colon.
Step 3: Add the program statements to be executed
Step 4: End the function with/without return statement.
2020-21
www.Jntufastupdates.com 42
Unit-1 Python Programming
Syntax :
def function_name(parameters):
"""doc string"""
statement(s)
Example:
def userDefFunction (arg1, arg2, arg3 ...):
program statement1
program statement3
program statement3
....
return
Advantages of functions :
• User-defined functions are reusable code blocks; they only need to be written once, then
they can be used multiple times.
• These functions are very useful, from writing common utilities to specific business logic.
• The code is usually well organized, easy to maintain, and developer-friendly.
• A function can have dif types of arguments & return value.
Example : 1
def disp():
print("hi srividya")
print("hi students")
disp() # function calling
Example : 2
To specify no body of the function use pass statement.
def disp():
pass
disp()
2020-21
www.Jntufastupdates.com 43
Unit-1 Python Programming
Example : 3
one function is able to call more than one function.
>>>def happyBirthday(person):
print("Happy Birthday dear ",person)
>>>def mohan():
happyBirthday('CSE')
happyBirthday('IT')
>>>mohan()
Inner functions: A function can be created as an inner function in order to protect it from
everything that is happening outside of the function. In that case, the function will be hidden from
the global scope.
Example: 1
def function1(): # outer function
print ("Hello from outer function")
def function2(): # inner function
print ("Hello from inner function")
function2()
>>>function1()
Output:
Hello from outer function
Hello from inner function
Explanation:
In the above example, function2() has been defined inside function1(), making it an inner function. To
call function2(), we must first call function1(). The function1() will then go ahead and call function2()
as it has been defined inside it.
It is important to mention that the outer function has to be called in order for the inner function to
execute. If the outer function is not called, the inner function will never execute.
2020-21
www.Jntufastupdates.com 44
Unit-1 Python Programming
Example:
• Inside the inner function to represent outer function variable use nonlocal keyword.
def outer():
var_outer = 'TEC'
print (var_outer)
def inner():
nonlocal var_outer
var_outer="CSE&IT"
inner() #calling of inner function
print (var_outer)
>>>outer()
Output:
TEC
CSE&IT
Example:
• Inside the function to represent the global value use global keyword.
name='Tirumala'
def outer():
var_outer = 'Eamcet Code'
def inner():
nonlocal var_outer
var_outer="Eamcet Code:TMLN"
global name
print(name)
name="TEC"
print(name)
print (var_outer)
inner() #calling of inner function
print (var_outer)
2020-21
www.Jntufastupdates.com 45
Unit-1 Python Programming
>>>outer()
Output:
Tirumala
TEC
Eamcet Code
Eamcet Code:TMLN
Function vs arguments:-
1. default arg
2. required arg
3. keyword argument
4. variable argument
1 .Default arguments:
When we call the function if we are not passing any argument the default value is assigned.
Example:-1
def empdetails(eid=1,ename="anu",esal=10000):
print ("Emp id =", eid)
print ("Emp name = ", ename)
print ("Empsal=", esal)
print("*********")
empdetails()
empdetails(222)
empdetails(333,"bhavani")
empdetails(111,"srividya",10.5)
Output:
Emp id = 1
Emp name = anu
Empsal= 10000
*********
Emp id = 222
Emp name = anu
Empsal= 10000
*********
Emp id = 333
Emp name = bhavani
Empsal= 10000
2020-21
www.Jntufastupdates.com 46
Unit-1 Python Programming
*********
Emp id = 111
Emp name = srividya
Empsal= 10.5
*********
2. Required arguments: Required arguments are the mandatory arguments of a function. These
argument values must be passed in correct number and order during function call.
Example:-1
def add(a,b):
print(a+b)
add("BALL",10)
Output: Traceback (most recent call last):
File "<pyshell#65>", line 1, in <module>
add("BALL",10)
File "<pyshell#58>", line 2, in add
print(a+b)
TypeError: must be str, not int
Example-1:
2020-21
www.Jntufastupdates.com 47
Unit-1 Python Programming
def msg(id,name):
print(id)
print(name)
msg(id=111,name='CSE')
msg(name='Students',id=222)
Output:
111
CSE
222
Students
Example:
def disp(*var):
for i in var:
print("var arg=",i)
disp()
disp(10,20,30)
disp(10,20.3,"ratan")
Output:
var arg= 10
var arg= 20
var arg= 30
var arg= 10
var arg= 20.3
var arg= ratan
2020-21
www.Jntufastupdates.com 48