0% found this document useful (0 votes)
2 views

u1_python

The document provides an overview of Python programming, covering its basics, features, advantages, and history. It explains Python's applications in various fields, its open-source nature, and the importance of the Python Software Foundation. Additionally, it details the setup process for Python, including installation instructions and examples of using Python in both interactive and script modes.

Uploaded by

balajidev29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

u1_python

The document provides an overview of Python programming, covering its basics, features, advantages, and history. It explains Python's applications in various fields, its open-source nature, and the importance of the Python Software Foundation. Additionally, it details the setup process for Python, including installation instructions and examples of using Python in both interactive and script modes.

Uploaded by

balajidev29
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 45

PYTHON PROGRAMMING

UNIT I PYTHON BASICS


Introduction to Python Programming – Python Interpreter and Interactive Mode– Variables and
Identifiers – Arithmetic Operators – Values and Types – Statements. Operators – Boolean Values
– Operator Precedence – Expression – Conditionals: If-Else Constructs – Loop
Structures/Iterative Statements – While Loop – For Loop – Break Statement-Continue statement –
Function Call and Returning Values – Parameter Passing – Local and Global Scope – Recursive
Functions.
Python
Python is a high-level, interpreted, interactive and object-oriented scripting language.
Python is open source software.
It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

Python Software Foundation(PSF), a non-profit organization, holds the copyright of Python. It is an


open source language, released under a GPL-compatible license. Guido Van Rossum conceived Python
in the late 1980s. Official Web Site is https://www.python.org

Largest companies use Python


 Google makes extensive use of Python in its web search system, and employs Python’s creator.
 Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.
 ESRI (Environmental Systems Research Institute) uses Python. ESRI is an international
supplier of geographic information system (GIS) software, web GIS and geodatabase
management applications.
 The YouTube video sharing service is largely written in Python.

What can Python do?


Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.

Why Use Python / Advantages of Python


 Python is free and distributed as open-source software. A large programming community is
actively involved in the development and support of Python libraries for various applications
such as web frameworks, mathematical computing and data science.
 Python provides enhanced readability. For that purpose, uniform indents are used to delimit
blocks of statements instead of curly brackets, like in many languages such as C, C++ and Java.
 Python is a cross-platform language. It works equally on different OS platforms like Windows,
Linux, Mac OSX etc. Hence Python applications can be easily ported across OS platforms.
 Python supports multiple programming paradigms including imperative, procedural, object-
oriented and functional programming styles.
 Python is an extensible language. Additional functionality (other than what is provided in the
core language) can be made available through modules and packages written in other languages
(C, C++, Java etc)
 A standard DB-API for database connectivity has been defined in Python. It can be enabled
using any data source (Oracle, MySQL, SQLite etc.) as a backend to the Python program for
storage, retrieval and processing of data.
 Python is designed with features to facilitate data analysis and visualization.
 Standard distribution of Python contains the Tkinter GUI toolkit, which is the implementation
of popular GUI library called Tcl/Tk. An attractive GUI can be constructed using Tkinter. Many
other GUI libraries like Qt, GTK, WxWidgets etc. are also ported to Python.
 Python can be integrated with other popular programming technologies like C, C++, Java,
ActiveX and CORBA.
 Python also features a dynamic and strong type system and automatic memory management.
 Python is an interpreted programming language. It allows you to you to run the same code on
multiple platforms without recompilation.
 Robust Standard Library - While writing a web application in Python, you can use specific
modules to implement web services, perform string operations, manage operating system
interface or work with internet protocols.

HISTORY OF PYTHON
The following table lists all the important versions history of Python:
Version Release Date Important Features
Python 0.9.0 February 1991  Classes with inheritance exception handling
 Functions
 Modules
Python 1.0 January 1994  Functional programming tools (lambda, map,
filter and reduce).
 Support for complex numbers.
 Functions with keyword arguments
Python 2.0 October 2000  List comprehension.
Python 2.7.0 - Current July 2010  Cycle-detecting garbage collector.
version  Support for Unicode. Unification of data types
Python 2.7.15 - Current sub- May 2018 and classes
version
Python 3 December 2008  Backward incompatible.
Python 3.6 December 2016  print keyword changed to print() function
Python 3.6.5 March 2018  raw_input() function depreciated
 Unified str/Unicode types.
 Utilities for automatic conversion of Pytthon
2.x code
Python 3.7.0 - Current May 2018  New C API for thread-local storage
Version  Built-in breakpoint()
 Data classes
 Context variables
Python Features:
 Python is an interpreter-based language, which allows execution of one instruction at a time.
 Easy-to-learn- Python has few keywords, simple structure, and a clearly defined syntax. This
allows a student to pick up the language quickly.
 Extensive basic data types are supported e.g. numbers (floating point, complex, and unlimited-
length long integers), strings (both ASCII and Unicode), lists, and dictionaries.
 Variables can be strongly typed as well as dynamic typed.
 Supports object-oriented programming concepts such as class, inheritance, objects, module,
namespace etc.
 Cleaner exception handling support.
 Supports automatic memory management.
 A broad standard library: Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
 Interactive Mode: Python has support for an interactive mode, which allows interactive testing
and debugging of snippets of code.
 Portable: Python can run on a wide variety of hardware platforms and has the same interface on
all platforms.
 Extendable: You can add low-level modules to the Python interpreter. These modules enable
programmers to add to or customize their tools to be more
efficient.
 Databases: Python provides interfaces to all major commercial databases.
 GUI Programming: Python supports GUI applications that can be created and ported to many
system calls, libraries and windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
 Scalable: Python provides a better structure and support for large programs than shell scripting.

Python Environment Setup


Python is free and easy to get from the Python website and is available for use with Windows, Linux,
Mac OS as well as certain other platforms such as IBM AS/400, iOS, Solaris, etc.

Download Python
To install Python on your local machine, get a copy of the standard distribution of Python software
from https://www.python.org/downloads based on your operating system, hardware architecture and
version of your local machine.
Install Python on Windows:

To install Python on a Windows platform, you need to download the installer. A web-based installer,
executable installer and embeddable zip files are available to install Python on Windows.
Visit https://www.python.org/downloads/windows and download the installer based on your local
machine's hardware architecture.

The web-based installer needs an active internet connection. So, you can also download the standalone
executable installer. Visit https://www.python.org/downloads and click on the Download Python
3.7.0 button as shown below. (3.7.0 is the latest version as of this writing.)

Test Python with a Program

Using Windows
A Windows installation creates a new folder in the Start menu that
contains your Python installation. You can access it by choosing Start ➪
All Programs ➪ Python 3.6. The two items of interest in the folder when
creating new applications are IDLE (Python GUI) and Python (command
line).
1. Click IDLE(Python GUI). Now the following screen is displayed.

2. The Python (command line) option opens a command prompt and executes the Python command, as
shown in Figure. Again, the environment automatically displays same above information such as the
Python version and the host platform.

Testing Your Installation

To ensure that you have a usable installation, you need to test it. To see Python work, type print(“This
is my first Python program.”) and press Enter. Python displays the message you just typed, as shown
in Figure.
Interactive Mode:
Working in interactive mode is convenient for beginners and for testing small pieces of code
immediately. Python, in interactive mode, is good enough to learn, experiment or explore, but its
only drawback is that we cannot save the statements and have to retype all the statements once again
to re-run them.
Interactive Mode allows us to interact with OS. After executing, Python statement,
interpreter displays the result(s) immediately.
That means, when we type Python expression / statement / command after the prompt
(>>>), the Python immediately responses with the output of it.
Examples :
>>>print "WELCOME TO PYTHON PROGRAMMING"
WELCOME TO PYTHON PROGRAMMING
>>> print 5+10
15

Script Mode: A Python script can be executed at the command line by invoking the interpreter on
your application. In script mode, we type Python program in a file and then use interpreter to execute
the content of the file. But for coding of more than few lines, we should always save our code so that it
can be modified and reused.

The following script mode is typed and saved with the name of quotient_remainder.py

Example: Input any two numbers and to find Quotient and Remainder.

# Code: (Script mode)


Output:
a = input ("Enter first number: ") Enter first number10
b = input ("Enter second number: ") Enter second number3
print "Quotient", a/b Quotient 3
print "Remainder", a%b Remainder 1
Click “Run” menu option and select Run module or F5 to execute script coding.
Keywords / Reserved words - are used to give some special meaning to the
interpreter and are used by Python interpreter to recognize the structure of program.

>>> import keyword


>>> keyword.kwlist

Python Identifier : Identifier is the name of the variables, functions, classes, modules, packages etc.
• An identifier name is the combination of alphabet letters (a-z or A-Z), digits (0-9) or
underscore. It should start with either an alphabet letter (lower or upper case) or an underscore
(_).No other characters are allowed.
• Identifiers are case sensitive which means variables named age and Age are different.
• An identifier cannot start with a digit. 1emp is invalid, but emp1 is a valid name.
• Can be any (reasonable) length
• Keywords cannot be used as identifiers.

Variable
Variables are nothing but reserved memory locations to store values. This means that when you create a
variable you reserve some space in memory.
• You can store integers, decimals or characters in these variables. Example : "Sara", 120, 25.36
• Variables are created when first assigned.
• Variables must be assigned before being referenced.
• The value stored in a variable can be accessed or updated later.
• No declaration required
• The type (string, int, float etc.) of the variable is determined by Python
• The interpreter allocates memory on the basis of the data type of a variable.

The general format for assigning values to variables is as follows:


variable_name =
expression

>>> myAge=21
Here myAge is an identifier (name) referring to integer value 21.
Rules for Variable Name
 The name of the variable should start with either an alphabet letter or an underscore (_), but it
cannot start with a digit.
 The variable name can consist of alphabet letter(s), number(s) and underscore(s) only.
 For example, myVar, MyVar, _myVar, MyVar123 are valid variable names but m*var,
my-var, 1myVar are invalid variable names.

Assignment of multiple variables


Assignments can be done on more than one variable "simultaneously" on the same line like this
Syntax: <var>, <var>, ..., <var> = <expr>, <expr>, ..., <expr>

a, b = 3, 4
print(a,b) Output: a=3 b=4
print(b) Output; b=4

x, y, z = 1, 2, "abcd“
print(z) Output: z=”abcd”

x, y, z = "Orange", "Banana", "Cherry"


print(x) Outut: x=”Orange”
print(y)
print(z)

c=d=10
print (c) Output: c = 10

Swap variable
Python swap values in a single line and this applies to all objects in python.

x = 10
y = 20
print(x)
print(y)
x,y=y, x
print(x)
print(y)

Reuse of Variable name

You can reuse variable names by simply assigning a new value to them :
>>> x = 100
>>> print(x) Output: x=100
>>> x = "Python
>>> print(x) Now Output: x=”Python”
>>>
Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as global
variables.
Global variables can be used by everyone, both inside of functions and outside.

Example
Create a variable outside of a function, and use it inside the function
x = “good”

def myfunc() :
print("Python is " + x)

myfunc()

Inside & Outside variable usage


var1 = "Python"
def func1():
var1 = "PHP"
print("In side func1() var1 = ",var1)

def func2():
print("In side func2() var1 = ",var1)
func1()
func2()

Output:
In side func1() var1 = PHP
In side func2() var1 = Python

Global & Local variable


If you create a variable with the same name inside a function, this variable will be local, and can only
be used inside the function. The global variable with the same name will remain as it was, global and
with the original value.
Create a variable inside a function, with the same name as the global variable.
x = "awesome"

def myfunc():
x = "fantastic"
print("Python is " + x)

myfunc()

print("Python is " + x)

o/p
Python is fantastic
Python is awesome
Global variable inside function
To create a global variable inside a function, you can use the global keyword.
def myfunc():
global x
x = "fantastic"
myfunc()
print("Python is " + x)

STATEMENTS

By default, the Python interpreter treats a piece of text terminated by hard carriage return (new line
character) as one statement.
A statement is an instruction that the Python interpreter can execute. Python program consists of a
sequence of statements. Statements are everything that can make up a line (or several lines) of Python
code. For example, z = 1 is an assignment statement.

msg="Hello World"
code=123
name="Steve"

You can show the text spread over more than one lines to be a single statement by using the backslash
(\) as a continuation character.

msg="Hello JKJKJ J JKJ JFJJF JKJDL JFJJD NJF JKJD KFJFDJD \


World"

Multiple Statements in Single Line


Use the semicolon ; to write multiple statements in a single line.
msg="Hello World";code=123;name="Steve"

EXPRESSION
Expression is an arrangement of values and operators which are evaluated to make a new value.
Expressions are statements as well. A value is the representation of some entity like a letter or a number
that can be manipulated by a program.
A single value >>> 20 or a single variable >>> z or a combination of variable, operator and value >>>
z + 20 are all examples of expressions.

For example,
>>> 8 + 2
10
TYPES / DATA TYPE:

Type (i.e data type) is a set of values, and the allowable operations on those values. It
can be one of the following:

1. Number: Number data type stores Numerical Values. This data type is immutable (unmodifiable)
i.e. value of its object cannot be changed. Numbers are of three different types:
 Integer & Long (to store whole numbers i.e. decimal digits without fraction part). Integers can
be of any length; it is only limited by the memory available.
 Float/floating point (to store numbers with fraction part). A floating point number is accurate up
to 15 decimal places.
 Complex (to store real and imaginary part). Complex numbers are written in the form, x + yj,
where x is the real part and y is the imaginary part.

Boolean : Condition is really just a yes-or-no question, the answer to that question is a Boolean value,
either True or False. The Boolean values, True and False are treated as reserved words.

2. None : None is a special data type. The None keyword is used to define a null value, or no value at
all or nothing. (Version 3.0)
Syntax
The syntax of None statement is: None

 None is not the same as False.


 None is not 0.
 None is not an empty string.

None is a datatype of its own (NoneType)


3. Sequence: A sequence is an ordered collection of items, indexed by positive integers.
There are three types of sequence data type available in Python, they are Strings, Lists & Tuples.
a) String- is an ordered sequence of letters/characters. They are enclosed in single
quotes (' ') or double quotes ('' "). The quotes are not part of string. They only tell the
computer about where the string constant begins and ends. They can have any character
or sign, including space in them. These are immutable. A string with length 1 represents
a character in Python.
b) Lists: List is also a sequence of values of any type. Values in the list are called elements
or items. These are mutable (modify) and indexed/ordered. List is enclosed in square brackets ([ ]).

c) Tuples: Tuples are a sequence of values of any type and are indexed by integers.
They are immutable.(not modifiable) Tuples are enclosed in ( ).

4. Sets:
Python has a data type called a set. Sets work like mathematical sets.
Set is unordered collection of values of any type with no duplicate entry. It is immutable.
Sets are denoted by curly braces, like below:

S = {1,2,3,4,5}
Recall that curly braces are also used to denote dictionaries, and {} is the empty dictionary. To get
the empty set, use the set function with no arguments, like this:
S = set()

Working with sets There are a few operators that work with sets.

The symmetric difference of two sets gives the elements that are in one or the other set, but not
both. Here are some useful methods:

5. Mapping: This data type is unordered and mutable. Dictionaries fall under Mappings.
Dictionaries: It can store any number of python objects. What they store is a key -value pairs, which
are accessed using key. Dictionary is enclosed in curly brackets { }.

type : You can get the data type of a variable with the type() function.
Example :
x=5
y = "John"
print(type(x)) Output <class 'int'>
print(type(y)) Output <class 'str'>

>>> type(True) Output <class 'bool'>


Type Coversions
You can explicitly cast, or convert, a variable from one type to another.

Casting
If you want to specify the data type of a variable, this can be done with casting.
x = str(3) #Output x will be '3'
y = int(3) # Output y will be 3
z = float(3) # Output z will be 3.0

int() function
To explicitly convert a float to a number or a string to an integer, cast the number using int() function.

Program to Demonstrate int() Casting Function


float_to_int = int(3.5)
string_to_int = int("1")
print(f"After Float to Integer Casting the result is {float_to_int}")
print(f"After String to Integer Casting the result is {string_to_int}")

Output
After Float to Integer Casting the result is 3
After String to Integer Casting the result is 1

float() function
float() function returns a floating point number constructed from a number or string.
Program to Demonstrate float() Casting Function
int_to_float = float(4)

string_to_float = float("1") #number treated as string


print(f"After Integer to Float Casting the result is {int_to_float}")
print(f"After String to Float Casting the result is {string_to_float}")

Output
After Integer to Float Casting the result is 4.0
After String to Float Casting the result is 1.0

str() function
The str() function returns a string which is fairly human readable.
Program to Demonstrate str() Casting Function
int_to_string = str(8)
float_to_string = str(3.5)
print(f"After Integer to String Casting the result is {int_to_string}")
print(f"After Float to String Casting the result is {float_to_string}")

chr() function
The chr() method returns a string representing a character whose >>> print (chr(65))
Unicode code point is an integer. The chr() method takes only one A
integer as argument. >>>
Syntax: chr(num)
num : integer value

PYTHON OPERATORS
Operators in general are used to perform operations on values and variables in Python. These are
standard symbols used for the purpose of logical and arithmetic operations.
1. Arithmetic operators: Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication and division.

Example - 1
>>> 10+35
45

# Example-2
a=9
b=4 Output
# Addition of numbers 13
add = a + b 5
# Subtraction of numbers 36
sub = a - b 2.25
2
# Multiplication of number 1
mul = a * b 6561

# Division(float) of number
div1 = a / b

# Division(floor) of number
div2 = a // b

# Modulo of both number


mod = a % b

# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)

2. Relational / Comparison Operators : Relational operators compares the values. It either


returns True or False according to the condition.
Operator Description

> Greater than: True if left operand is greater than the right

< Less than: True if left operand is less than the right

== Equal to: True if both operands are equal

!= Not equal to - True if operands are not equal

>= Greater than or equal to: True if left operand is greater than or equal to the right

<= Less than or equal to: True if left operand is less than or equal to the right

# Examples of Relational Operators


a = 13 Output:
b = 33 False
True
# a > b is False False
print(a > b) True
False
# a < b is True True
print(a < b)

# a == b is False
print(a == b)

# a != b is True
print(a != b)

# a >= b is False
print(a >= b)

# a <= b is True
print(a <= b)
.3. Logical operators:
The logical operators are used for comparing or negating the logical values of their operands and to
return the resulting logical value. The result of the logical operator is always a Boolean value, True or
False.

Logical operators perform Logical AND, Logical OR and Logical NOT operations.

Operator Description Syntax


and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if operand is false not x


Example
a = 10
b = 10
Output
c = -10
The numbers are greater than 0
Atleast one number is not greater than 0
if a > 0 and b > 0:
print("The numbers are greater than 0")

if a > 0 and b > 0 and c > 0:


print("The numbers are greater than 0")
else:
print("Atleast one number is not greater than 0")

4. Assignment operators : Assignment operators are used to assign values to the variables.
Syntax: <variable> = <expr>

Operator Description Syntax


= Assign value of right side of expression to left side operand x=y+z

Add AND: Add right side operand with left side operand and a+=b
+= then assign to left operand a=a+b

Subtract AND: Subtract right operand from left operand and a-=b
-= then assign to left operand a=a-b

Multiply AND: Multiply right operand with left operand and a*=b
*= then assign to left operand a=a*b

Divide AND: Divide left operand with right operand and a/=b
/= then assign to left operand a=a/b

Modulus AND: Takes modulus using left and right operands a%=b a=a
%= and assign result to left operand %b

Divide(floor) AND: Divide left operand with right operand a//=b


//= and then assign the value(floor) to left operand a=a//b
Exponent AND: Calculate exponent(raise power) value using a**=b
**= operands and assign value to left operand a=a**b
Example:
>>> p = 10
>>> q = 12
>>> q += p
>>> q
22

5. Special operators: There are some special type of operators like-


 Identity operators-
is and is not are the identity operators both are used to check if two values are located on the same
part of the memory. Two variables that are equal does not imply that they are identical.
 is True if the operands are identical
is not True if the operands are not identical

# Examples of Identity operators


a1 = 3 Output:
b1 = 3 False
a2 = 'GeeksforGeeks' True
b2 = 'GeeksforGeeks' False
a3 = [1,2,3]
a4=[1,2,3]
b3 = (1,2,3)
print(a1 is not b1)
print(a2 is b2)

# Output is False, since lists are mutable.


print(a3 is b3)

6. Membership operators-
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
in True if value is found in the sequence
Output:
not in True if value is not found in the sequence
True
True
# Examples of Membership operator
False
x = 'Geeks for Geeks'
True
y = {3:'a',4:'b'}
False
print('G' in x)
print('geeks' not in x)
print('Geeks' not in x)
print(3 in y)
print('b' in y)

7. Bitwise Operator :
Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and perform bit by bit
operation. For example, the decimal number ten has a binary representation of 1010. Bitwise operators
perform their operations on such binary representations, but they return standard Python numerical
values.
Precedence and Associativity of Operators: Operator precedence and associativity as these
determine the priorities of the operator.
Operator Precedence: This is used in an expression with more than one operator to determine which
operation to perform first.
Operator Precedence table
# Examples of Operator Precedence

# Precedence of '+' & '*'


expr = 10 + 20 * 30 Output:
print(expr) 610

# Precedence of 'or' & 'and'


name = "Alex"
age = 10

if name == "Alex" or name == "John" and age >= 2 : Output:


print("Hello! Welcome.") Hello! Welcome.
else :
print("Good Bye!!")

Operator Associativity: If an expression contains two or more operators with the same precedence
then Operator Associativity is used to determine. It can either be Left to Right or from Right to Left.

Input and Output


Program need to interact with end user to accomplish the desired task, this is done using Input-Output
facility. Input means the data entered by user (end user) of the program. In python, input () and
raw_input() functions are available for input.

The raw_input function was built in Python 2. It is deprecated (removed) in version 3.


The raw_input worked the same way as input() function in Python 3 works. Alternatively, you can say
the raw_input is renamed to input function Python version 3.
v
input( )

Syntax

val2 = input("Enter the number: ")


print(type(val2))
val2 = int(val2)
print(type(val2))
print(val2)

val1 = input("Enter the name: ")


Enter the name: SAIRAM

Print statement

In Python, single, double and triple quotes are used to denote a string. Most use single quotes when
declaring a single character. Double quotes when declaring a line and triple quotes when declaring a
paragraph/multiple lines.

Single Quotes Use:


print('Hello')
Output: Hello

Double Quotes Use:


print("Python is very simple language")
Output: Python is very simple language
Triple Quotes Use:
print("""Python is very popular language.
It is also friendly language.""")
Python is very Popular Language.
It is also friendly language.

The print statement can be used in the following ways :


 print("Good Morning")
 print("Good", <Variable Containing the String>)
 print("Good" + <Variable Containing the String>)
 print("Good %s" % <variable containing the string>)
sep – The argument sep is separator function. Python will insert a space between each of the arguments
of the print function.

f-strings
Formatted strings or f-strings were introduced in Python 3.6. A f-string is a string literal that is prefixed
with “f”.
These strings may contain replacement fields, which are expressions enclosed within curly braces {}.
The expressions are replaced with their values. In the real world, it means that you need to specify the
name of the variable inside the curly braces to display its value.
COMMENT : Comments are remark statements. A comment is a message to someone reading your
program. Comments are often used to describe what a section of code does or how it works.

. Anything written after # in a line is ignored by interpreter.


Single-line comments For a single-line comment, use the # character.

For more than one line comments, we use the following;


Use triple quoted string. ( """ """)

Multi-line comments
For comments that span several lines, you can use triple quotes.
""" Program name: Hello world
Author: Brian Heinold
Date: 1/9/11 """
print('Hello world')
Interview Questions of this unit

Why Numeric data type is immutable? i.e. value of its object cannot be changed.

None

In real situation, we have no value. That situation is handled by “None”..


.

DECISION MAKING STATEMENTS / CONTROL FLOW STATEMENTS

Python supports a set of control flow statements that you can integrate into
your program. The statements inside your Python program are generally
executed sequentially from top to bottom, in the order that they appear.
Apart from sequential control flow statements you can employ decision
making and looping control flow statements to break up the flow of
execution thus enabling your program to conditionally execute particular
blocks of code.

1. Sequential Control Flow Statements: This refers to the line by line


execution, in which the statements are executed sequentially, in the same order in which they appear in
the program.

2. Decision Control Flow Statements: Depending on whether a condition is True or False, the decision
structure may skip the execution of an entire block of statements or even execute one block of
statements instead of other (if, if…else and if…elif…else).

3. Loop Control Flow Statements: This is a control structure that allows the execution of a block of
statements multiple times until a loop termination condition is met (for loop and while loop). Loop
Control Flow Statements are also called Repetition statements or Iteration statements.
Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You
need to determine which action to take and which statements to execute if outcome is TRUE or
FALSE otherwise.
Following is the general form of a typical decision making structure found in most of the
programming languages –

Conditional operators
The comparison operators are ==, >, <, >=, <=, and !=. That last one is for not equals. Here are a few
examples:
Example :
if grade>=80 and grade<90:
print('Your grade is a B.')

if Condition
An if statement consists of a boolean expression followed by one or
more statements.

if test expression:
statement(s)
Here, the program evaluates the test expression and will execute
statement(s) only if the text expression is True. If the text expression
is False, the statement(s) is not executed.
(ex)
num = 3
if num > 0:
print(num, "is a positive number.")

if...else statements

An if statement can be followed


by an optional else statement,
which executes when the boolean
expression is FALSE.

if test expression :
Body of if
else :
Body of else

The if..else statement evaluates test expression and will execute body of if only when test condition is
True.
If the condition is False, body of else is executed. Indentation is used to separate the blocks.

(ex)
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
Nested if statements
You can use one if or else if statement inside another if or else if statement(s).
Syntax
If test expression :
Body of if
elif test expression :
Body of elif
else :
Body of else

The elif is short for else if. It allows us to check for multiple expressions. If the condition for if is False,
it checks the condition of the next elif block and so on.

If all the conditions are False, body of else is executed. Only one block among the several if...elif...else
blocks is executed according to the condition.

if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")

Another example
grade = eval(input('Enter your score: '))
if grade>=90:
print('A')
elif grade>=80:
print('B')
elif grade>=70:
print('C')

elif grade>=60:
print('D')
else:
print('F')

Nested if statements
A if...elif...else statement inside another if...elif...else statement. This is called n esting in computer
programming.
Any number of these statements can be nested inside one another.
num = float(input("Enter a number: "))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")

Output 1
Enter a number: 5
Positive number

Output 2
Enter a number: -1
Negative number

Looping
Looping Statements
A loop is a used for iterating over a set of statements repeatedly. In
Python we have three types of loops for, while and do-while.

Syntax of For loop in Python

for <variable> in <sequence>:


# body_of_loop that has set of statements
# which requires repeated execution

Here <variable> is a variable that is used for iterating over a <sequence>. On every iteration it takes
the next value from <sequence> until the end of sequence is reached.
Python – For loop example
The following example shows the use of for loop to iterate over a list of numbers.
In the body of for loop we are calculating the square of each number present in list and Output
displaying the same.
1
# Program to print squares of all numbers present in a list 4
numbers = [1, 2, 4, 6, 11, 20] 16
sq = 0 36
for val in numbers:
121
sq = val * val 400
print(sq)

Function range()
In the above example, we have iterated over a list using for loop. However we can also use a range()
function in for loop to iterate over numbers defined by range().

range(n): generates a set of whole numbers starting from 0 to (n-1).


For example:
range(8) is equivalent to [0, 1, 2, 3, 4, 5, 6, 7]

range(start, stop): generates a set of whole numbers starting from start to stop-1.

For example:
range(5, 9) is equivalent to [5, 6, 7, 8]

range(start, stop, step_size): The default step_size is 1 which is why when we didn’t specify the
step_size, the numbers generated are having difference of 1. However by specifying step_size we can
generate numbers having the difference of step_size.
For example:
range(1, 10, 2) is equivalent to [1, 3, 5, 7, 9]

Lets use the range() function in for loop:

Python for loop example using range() function

Here we are using range() function to calculate and display the sum of first 5 natural numbers.

# Program to print the sum of first 5 natural numbers


sum = 0
for val in range(1, 6):
sum = sum + val
print(sum)
Output
15

The range function


The value we put in the range function determines how many times we will loop.

for variable name in range( number of times to repeat ):


statements to be repeated

Example
for i in range(3):
num = eval(input('Enter a number: '))
print ('The square of your number is', num*num)
print('The loop is now done.')
For loop with else block

Unlike Java, In Python we can have an optional ‘else’ block associated with the loop. The ‘else’ block
executes only when the loop has completed all the iterations. Lets take an example:

for val in range(5): Output


print(val) 0
else: 1
print("The loop has completed execution") 2
3
4
The loop has completed
Nested For loop in Python execution

When a for loop is present inside another for loop then it is called a nested for loop. Lets take an
example of nested for loop.
Output:
0 , 10
for num1 in range(3):
0 , 11
for num2 in range(10, 14):
0 , 12
print(num1, ",", num2)
0 , 13
1 , 10
1 , 11
1 , 12
1 , 13
2 , 10
2 , 11
2 , 12
2 , 13
Print a 10 × 10 multiplication table.

for i in range(1,11):
for j in range(1,11):
print('{:3d}'.format(i*j), end=' ')
print()

Note : end function is worked only python 3 and abover version only. Not works in 2.7

A multiplication table is a two-dimensional object. To work with it, we use two for loops, one for
the horizontal direction and one for the vertical direction.
While Loop
While loop is used to iterate over a block of code repeatedly until a given condition returns false.
Syntax

while condition:
#body_of_while

Flow of while loop

1. First the given condition is checked, if the condition returns false, the loop is terminated and the
control jumps to the next statement in the program after the loop.

2. If the condition returns true, the set of statements inside loop are executed and then the control jumps
to the beginning of the loop for next iteration.

Example Output:
num = 1 1
while num < 10: 4
print(num) 7
#incrementing the value of num
num = num + 3

Nested while loop in Python


When a while loop is present inside another while loop then it is called nested while loop.
i=1
j=5
while i < 4:
while j < 8:
print(i, ",", j)
j=j+1
i=i+1
Output
1,5
2,6
3,7

Python – while loop with else block


The ‘else’ block is optional. It executes only after the loop finished execution.

num = 10
Output:
while num > 6:
10
print(num)
9
num = num-1
8
else:
7
print("loop is finished")
loop is finished
Infinite loops
When working with while loops, sooner or later you will accidentally send Python into a never-
ending loop. Here is an example:

i=0
while i<10:
print(i)

In this program, the value of i never changes and so the condition i<10 is always true. Python will
continuously print zeroes. To stop a program caught in a never-ending loop, use Restart Shell
under the Shell menu. You can use this to stop a Python program before it is finished executing.
Sometimes a never-ending loop is what you want. A simple way to create one is shown below:

while True:
# statements to be repeated go here
The value True is called a boolean value

a = ['foo', 'bar', 'baz']


while True:
if not a:
break
print(a.pop(-1))

Output
baz
bar
foo

iter()

Instead of using the for loop as shown above, we can use the iterator function iter(). An iterator is an
object which represents a data stream. It returns one element at a time. Python's built-in
method iter() receives an iterable and returns an iterator object. The iterator object uses
the __next__() method. Every time it is called, the next element in the iterator stream is returned. When
there are no more elements available, StopIteration error is encountered.

>>> L1=[1, 2, 3]
>>>it=iter(L1)
>>>it.__next__()
1
>>>it.__next__()
2
>>>it.__next__()
3
>>>it.__next__()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
it.__next__()
StopIteration

next()

Calling the it.__next__() method every time is tedious. The built-in function next()accepts an iterator
object as a parameter and calls the __next__() method internally. Hence, it.__next__() is the same
as next(it). The following example uses the next() method to iterate the list.

>>> L1=[1,2,3]
>>>it=iter(L1)
>>>next(it)
>>>1
>>>next(it)
>>>2
>>>next(it)
>>>3
>>>next(it)

Traceback (most recent call last):


File "<pyshell#13>", line 1, in <module>
it.__next__()
StopIteration

Python - Generator
Python provides a generator to create your own iterator function. A generator is a special type of
function which does not return a single value, instead it returns an iterator object with a sequence of
values. In a generator function, a yield statement is used rather than a return statement. The following is
a simple generator function.

def myGenerator():
print('First item') Example
yield 10
Type this coding and save in a
print('Second item') python file. mygenerator.py
yield 20

print('Last item')
yield 30
In the above example, myGenerator() is a generator function. It uses yield instead of return
keyword. So, this will return the value against the yield keyword each time it is called.

>>> gen = myGenerator()


>>> next(gen)
First item
10
>>> next(gen)
Second item
20
>>> next(gen)
Last item
30
>>> next(gen)

Traceback (most recent call last):


File "<pyshell#6>", line 1, in <module>
next(gen)
StopIteration
>>>

enumerate
The built-in enumerate function takes an iterable and returns a new iterable
consisting of pairs
(i,x) where i is an index and x is the corresponding element from the iterable. For
example:
s = 'abcde'
for (i,x) in enumerate(s):
print(i+1, x)

zip
The zip function takes two iterables and “zips” them up into a single iterable that contains
pairs (x,y), where x is from the first iterable, and y is from the second. Here is an example:

s = 'abc'
L = [10, 20, 30]
z = zip(s,L)
print(list(z))

o/p

Flag variable num = eval(input('Enter number: '))


Flag variable is used as a signal in programming to let flag = 0
the program know that a certain condition has met. for i in range(2,num):
It usually acts as a boolean variable indicating a condition if num%i==0:
to be either true or false. flag = 1
if flag==1:
print('Not prime')
else:
print('Prime')
Break Statement
The break statement is generally used inside a loop along with a if statement so that when a particular
condition (defined in if statement) returns true, the break statement is encountered and the loop
terminates.
For example, lets say we are searching an element in a list, so for that we are running a loop starting
from the first element of the list to the last element of the list. Using break statement, we can terminate
the loop as soon as the element is found because why run the loop unnecessary till the end of list when
our element is found.
Syntax: break
Example of break statement

In this example, we are searching a number ’88’ in the given list of numbers.

program to display all the elements before number 88


for num in [11, 9, 88, 10, 90, 3, 19]: Output:
print(num) 11
if(num==88): 9
print("The number 88 is found") 88
print("Terminating the loop") The number 88 is found
break Terminating the loop

Continue Statement
The continue statement is used inside a loop to skip the rest of the statements in the body of loop for
the current iteration and jump to the beginning of the loop for next iteration.
Syntax

Continue

Program to display only odd numbers


Output
for num in [20, 11, 9, 66, 4, 89, 44]:
11
# Skipping the iteration when number is even
9
if num%2 == 0:
89
continue
# This statement will be skipped for all even numbers
print(num)

Python Pass Statement


The pass statement acts as a placeholder and usually used when there is no need of code but a
statement is still required to make a code syntactically correct. For example we want to declare a
function in our code but we want to implement that function in future, which means we are not yet
ready to write the body of the function. In this case we cannot leave the body of function empty as this
would raise error because it is syntactically incorrect, in such cases we can use pass statement
which does nothing but makes the code syntactically correct.

Python pass statement example


If the number is even we are doing nothing and if it is odd then we are displaying the number.

for num in [20, 11, 9, 66, 4, 89, 44]: Output


if num%2 == 0: 11
pass 9
else: 89
print(num)
Pass statement vs comment

You may be wondering that a python comment works similar to the pass statement as it does nothing so
we can use comment in place of pass statement. Well, it is not the case, a comment is not a placeholder
and it is completely ignored by the Python interpreter while on the other hand pass is not ignored by
interpreter, it says the interpreter to do nothing.

FUNCTIONS
A function is a block of reusable code that is used to perform a specific action. The advantages of using
functions are:

 Reducing duplication of code


 Decomposing complex problems into simpler pieces
 Improving clarity of the code
 Reuse of code
 Information hiding

Functions can be defined inside a module, a class, or another function. Function defined inside a class
is called a method.

Python includes many built-in functions. These functions perform a predefined task and can be called
upon in any program, as per requirement.

A function definition has several syntax elements. First, we need to provide the "def" keyword to
identify that the object is a function. Second , we need to provide the name of the function . Third, we
can provide zero or more arguments. Fourth, we need to indent the body of the function as the body of
the function forms a Python block. Last, a function can also return a value.
Why use function
1. Code re-usability:: To perform a specific task in several places of our code
repeatedly. Tracing and error correction task is easy in function using.
2. Improves Readability: It would be easier for anyone to look at the code and be able to understand the
flow and purpose of the code.
3.The Error finding, Debugging and Correction is easy.

User Defined Functions:

In Python, it is also possible for programmer to write their own function(s). These functions can then
be combined to form module which can be used in other programs by importing them. To define a
function, keyword 'def' is used. After the keyword comes an identifier i.e. name of the function,
followed by parenthesized list of parameters and the colon which ends up the line, followed by the
block of statement(s) that are the part of function.

Syntax:
def NAME ([PARAMETER1, PARAMETER2, …..]):
#Square brackets include optional part of statement statement(s)
Defining a Function

You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
 Function blocks begin with the keyword def followed by the function name and parentheses
( ( ) ).
 Any input parameters (or) arguments should be placed within these parentheses. You can also
define parameters inside these parentheses.
 The code block within every function starts with a colon (:) and is indented.
 The first statement is called a docstring and it is optional. It is similar to a Comment / Remark
statement.
 The statement return [expression] exits a function, optionally passing back an expression to the
caller. A return statement with no arguments is not return None.

Syntax def function_name(parameters):


"function docstring"
statement1
statement2
...
...
return [expr]

Calling a Function

Defining a function only gives it a name, specifies the parameters that are to be included in the
function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another
function (or) directly from the Python prompt. Following is the example to call printme() function −

# Function definition is here


def printme( str ):
"Printing the string"
print str
return;

# Now you can call printme function


printme("I'm first call to user defined function!")
printme("Again second call to the same function")
Output
I'm first call to user defined function!
Again second call to the same function

Function Arguments
You can call a function by using the following types of formal arguments −
 Required arguments
 Keyword arguments
 Default arguments
 Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.
>>> def sum(a,b):
return a+b

>>> sum(2,3) #calling function

Output : 5
Suppose if we pass only one argument, the interpreter complains.

>>> def sum(a,b):


return a+b
>>> sum(2)
TypeError: sum() missing 1 required positional argument: ‘b’
Keyword arguments

Keyword arguments are related to the function calls. When you use keyword arguments in a function
call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to
use the keywords provided to match the values with parameters. You can also make keyword calls to
the printme() function in the following ways −

The following example gives more clear picture. Note that the order of parameters does not matter.

# Function definition is here When the above code is executed, it


def printinfo( name, age ): produces the following result −
"This prints a passed info into this function"
print "Name: ", name Name: miki
print "Age ", age Age 50
return;

# Now you can call printinfo function


printinfo( age=50, name="miki" )
Default arguments

A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it prints
default age if it is not passed –

# Function definition is here


def printinfo( name, age = 35 ):
"This prints a passed info into this function" When the above code is executed, it
print "Name: ", name produces the following result −
print "Age ", age
return; Name: miki
Age 50
# Now you can call printinfo function
printinfo( age=50, name="miki" ) Name: miki
Age 35
# 2nd print function
printinfo( name="miki" )

Variable-length / Arbitary arguments


You may not always know how many arguments you’ll get. In that case, you use an asterisk(*) before
an argument name.

def functionname([formal_args,] *var_args_tuple ):


"function_docstring"
function_suite
return [expression]

An asterisk (*) is placed before the variable name that holds the values of tuple. This tuple remains
empty if no additional arguments are specified during the function call. Following is a simple example
When the above code is executed, it
# Function definition is here produces the following result −
>>> def sayhello(*names): Output is:
for name in names: >>> sayhello('Ayushi','Leo','Megha')
print("Hello, {name}") Hello, Ayushi
Hello, Leo
Hello, Megha

And then when you call the function with a number of arguments, they get wrapped into a Python
tuple. We iterate over them using the for loop in python.

The return Statement

The statement return [expression] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as return None.
All the above examples are not returning any value. You can return a value from a function as follows

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them." Inside the function : 30 -
Normal
Outside the function : 30 Return
function
total = arg1 + arg2
print "Inside the function : ", total
return total;

# Now you can call sum function


total = sum( 10, 20 );
print "Outside the function : ", total
When the above code is executed, it produces the following result −

2. BUILT IN FUNCTION:
Built in functions are the function(s) that are built into Python and can be accessed by
Programmer. These are always available and for using them, we don't have to import any
module (file). Python has a small set of built-in functions as most of the functions have
been partitioned to modules. This was done to keep core language precise.
3. THE ANONYMOUS / LAMBDA FUNCTION:

These functions are called anonymous because they are not declared in the standard manner by using
the def keyword. You can use the lambda keyword to create small anonymous functions.
 Lambda forms can take any number of arguments but return just one value in the form of an
expression. They cannot contain commands or multiple expressions.
 An anonymous function cannot be a direct call to print because lambda requires an expression

Syntax
The syntax of lambda functions contains only a single statement, which is as
follows −

lambda [arg1 [,arg2,.....argn]] : expression

# Function definition is here


sum = lambda arg1, arg2 : arg1 + arg2;

# Now you can call sum as a function


print "Value of total : ", sum( 10, 20 )
print "Value of total : ", sum( 20, 20 )
When the above code is executed, it produces the following result −

Value of total : 30
Value of total : 40

Example
Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))

o/p : 15

Example
Lambda functions can take any number of arguments:
Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))

o/p: 30

#Define a lambda function.

def giveMeAFunction(varName):
if (varName == "even"):
return lambda x: x % 2 == 0
elif (varName == "odd"):
return lambda x: x % 2 != 0

#Invoke the returned functions.


print(giveMeAFunction("even")(80)) # Prints True.
print(giveMeAFunction("even")(237)) # Prints False.
print(giveMeAFunction("odd")(237)) # Prints True.
print(giveMeAFunction("odd")(80)) # Prints False.

Recursive Functions
Functions can even call themselves! Such functions are known as recursive functions.
def getFactorial(num):
factorial = 1

print("Computing factorial for " + str(num))


if (num = = 1):
return factorial

factorial = num * getFactorial(num-1);


return factorial

retValue = getFactorial(4)

print("The factorial of 4 is " + str(retValue))

The output shows how the function calls itself for all the integers starting from 4 to 1.
[user@codingtree]$ python3 function_recursive.py
Computing factorial for 4
Computing factorial for 3
Computing factorial for 2
Computing factorial for 1
The factorial of 4 is 24
Scope of Variables

All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier.
There are two basic scopes of variables in Python −
 Global variables
 Local variables
Global vs. Local variables (Program to be added)

Variables that are defined inside a function body have a local scope, and those defined outside have a
global scope.
This means that local variables can be accessed only inside the function in which they are declared,
whereas global variables can be accessed throughout the program body by all functions. When you
call a function, the variables declared inside it are brought into scope. Following is a simple example –

total = 0; # This is global variable.

# Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print "Inside the function local total : ", total
return total;

# Now you can call sum function


sum( 10, 20 );
print "Outside the function global total : ", total
When the above code is executed, it produces the following result −

Inside the function local total : 30


Outside the function global total : 0
Additional Exercises
Python Function example

Here we have a function add() that adds two numbers passed to it as parameters. Later after function
declaration we are calling the function twice in our program to perform the addition.

def add(num1, num2): Output


return num1 + num2 300
sum1 = add(100, 200) 17
sum2 = add(8, 9)
print(sum1)
print(sum2)

def SI(P,R,T):
return(P*R*T)
Output:
>>> SI(1000,2,10)
20000
Default arguments in Function

By using default arguments we can avoid the errors that may arise while calling a function without
passing all the parameters.
In this example we have provided the default argument for the second parameter, this default argument
would be used when we do not provide the second parameter while calling this function.

# default argument for second parameter


def add(num1, num2=1): Output:
return num1 + num2 300
9
sum1 = add(100, 200)
sum2 = add(8) # used default argument for second param
print(sum1)
print(sum2)

FunctionTest.py
def result(m1,m2,m3):
ttl=m1+m2+m3
percent=ttl/3
if percent>=50:
print ("Result: Pass")
else:
print ("Result: Fail")
return

p=int(input("Enter your marks in physics: "))


c=int(input("Enter your marks in chemistry: "))
m=int(input("Enter your marks in maths: "))
result(p,c,m)

Run the above script in IDLE with two different sets of inputs is shown below:

Enter your marks in physics: 50


Enter your marks in chemistry: 60
Enter your marks in maths: 70
Result: Pass

Enter your marks in physics: 30


Enter your marks in chemistry: 40
Enter your marks in maths: 50
Result: Fail

Indentation :
In Python, Programs get structured through Usually,
we expect indentation from any program code, but in
Python it is a requirement and not a matter of style. This principle makes the code look cleaner and
easier to understand and read.
Any statements written under another statement with the same indentation is interpreted to belong to
the same code block.
If there is a next statement with less indentation to the left, then it just means the end of the previous
code block.

In other words, if a code block has to be deeply nested, then the nested statements need to be indented
further to the right.

1. Write a program to input any number and to print all natural numbers up to given number.

Code:
n = input("enter any number")
for i in range(1,n+1):
print i, Output:
enter any number10
1 2 3 4 5 6 7 8 9 10

2. Write a program to input any number and to find sum of all natural numbers up to given number.

Code:
n = input("Enter any number")
sum= 0
for i in range(1,n+1):
sum = sum+i print "sum=",sum
Output:
Enter any number5 sum = 15
3. Write a program to input any number and to find reverse of that number.

Code:
n = input("Enter any number")
r = 0 while(n>0):
r = r*10+n%10 n = n/10

print "reverse number is", r

Output:
>>>
Enter any number345 reverse number is 543
>>>

Example: Write the output from the following code:

1. sum = 0
for i in range(1,11,2):
sum+ = i
print "sum = ", sum output:
sum = 25

2. sum = 0 i = 4
while (i<=20): sum+=i i+= 4
print "Sum = ",sum output:
Sum = 60

Example: Interchange for loop into while loop

1. for i in range(10,26,2):
print i
Ans: i=10 while(i<26):
print i
i+=2

2. s=0
for i in range(10,50,10):
s + =i
print " Sum= ", s

Ans:
s=0
i = 10 while(i<50):
s+ = i i+ = 10
print "Sum=",s

Example: Interchange while loop in to for loop. i = 5


s=0
while (i<25):
s+ = i
i+=5
print " Sum =", s
Ans:
s=0
for i in range(5,25,5):
s+=i
print "Sum = ", s

Example: How many times following loop will execute.

1. for i in range(10,50,5):
print i
Ans:
i values are 10,15,20,25,30,35,40,45
8 times

2. i=4 while(i<25):
print i i+=4
Ans:
i values are 4,8,12,16,20,24
6 times
Program to Find If a Given Number Is Odd or Even
number = int(input("Enter a number"))
if number % 2 == 0:
print(f"{number} is Even number")
else:
print(f"{number} is Odd number")
Output
Enter a number: 45
45 is Odd number
Program to Check If a Given Year Is a Leap Year
year = int(input('Enter a year'))
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')
else:
print(f'{year} is a Leap Year')
else:
print(f'{year} is not a Leap Year')

Output
Enter a year 2014
2014 is not a Leap Year

Program to Find the Average of n Natural Numbers, Where n Is the Input from the User
number = int(input("Enter a number up to which you want to find the average"))
i=0
sum = 0
count = 0
while i < number:
i=i+1
sum = sum + i
count = count + 1
average = sum/count
print(f"The average of {number} natural numbers is {average}")

Output
Enter a number up to which you want to find the average 5
The average of 5 natural numbers is 3.0

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy