0% found this document useful (0 votes)
4 views32 pages

389560663-python

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 32

Python is a high-level, general-purpose, interpreted programming language.

Key features of python

Python is a high level programming language.

 Easy to learn and use: It is much easier to learn than any other programming
languages like C, C++, Java, Ruby and Swift. It has few keywords and thus
very less syntactical constraints. Thus the language is very developer friendly
and easy to pick up.
 Free and Open Source → Python is a open sourced language. Thus it is
publicly available to download and use and even anyone can contribute to its
development.
 Easy to maintain → Python code base is very easy to maintain.
 Object Oriented Language → Python is an Object Oriented language. Thus is
provides all the key features of an Object Oriented Programming language
like Encapsulation, Inheritance, Abstraction and Polymorphism.
Nevertheless, Python also offers a scope to write code as in a Procedural
Programming Language.
 Extensibility → Python is very extensible. We can write and integrate some
Python code into C and C++ and hence compile it using its irrespective
compilers.
 Portability → Python provides high portability. Thus same piece of code can
be run in all platforms of Windows, UNIX and Linux.
 Large Standard Library → Python has a large set of large standard library
which possess some inbuilt rich set of functions such that we need not to
write code for every single thing.
 Dynamically Typed Language → Python is a dynamically typed language.
Here, we need not to declare the type of the variable like int, float and char. It
is also auto-set as we assign a value to the variable.
 Garbage Collection → Python also supports auto garbage collection.
Comments:

Comments are an indespensible part of any programming language.

A good piece of code is the one which a reader can understand. Comments are
mainly used for this purpose.

Comments in python have their own benefits.

In Python, comments are ignored by the interpreter and hence they are used to make
the code more readable. By putting comments in or around any block of code, we
can explain the functionality of that piece of code.

Interestingly, comments are also used to disable Python instructions to prevent


comment from getting executed during testing or debugging phase.

A comment in Python has the syntax:

# This is a Python comment

Python single line comment

A comment in Python always begins with "#" sign. These are mainly single line
comments. In Python, there is no concept of multiline comments, but you can realize
a multiline comment by using docstrings.

'''

This is a multiline comment.

This comment has been made using docstrings

Docstrings will be discussed later in this tutorial.

'''

Variable

Variable is a name that is used to refer to memory location. Python variable is also
known as an identifier and used to hold value.

In Python, we don't need to specify the type of variable because Python is a infer
language and smart enough to get variable type.

Variable names can be a group of both the letters and digits, but they have to begin
with a letter or an underscore.
Rules to define Variables are:

1. The first character of the variable must be an alphabet or underscore ( _ ).


2. All the characters except the first character may be an alphabet of lower-
case(a-z), upper-case (A-Z), underscore, or digit (0-9).
3. Identifier name must not contain any white-space, or special character (!, @, #,
%, ^, &, *).
4. Identifier name must not be similar to any keyword defined in the language.
5. Identifier names are case sensitive; for example, my name, and MyName is
not the same.

Declaring Variable:

Python does not bind us to declare a variable before using it in the application. It
allows us to create a variable at the required time.

The equal (=) operator is used to assign value to a variable.

Example:
1. a = 50

In the above image, the variable a refers to an integer object.

2. a = 50

b=a

The variable b refers to the same object that a points to because Python does not
create another object.

Example 2:
1. name = "Devansh"
2. age = 20
3. marks = 80.50
4. print(name)
5. print(age)
6. print(marks)

Multiple Assignments
Python allows us to assign a value to multiple variables in a single statement, which
is also known as multiple assignments.

We can apply multiple assignments in two ways, either by assigning a single value
to multiple variables or assigning multiple values to multiple variables

1. Assigning single value to multiple variables

Eg:

1. x=y=z=50
2. print(x)
3. print(y)
4. print(z)

2. Assigning multiple values to multiple variables:

Eg:

1. a,b,c=5,10,15
2. print a
3. print b
4. print c

Python Data Types

Variables can hold values, and every value has a data-type. Python is a dynamically
typed language; hence we do not need to define the type of the variable while
declaring it. The interpreter implicitly binds the value with its type.

a=5

The variable a holds integer value five and we did not define its type. Python
interpreter will automatically interpret variables a as an integer type.

Example:

1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))

Output:
<type 'int'>
<type 'str'>
<type 'float'>

A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.

The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

Number stores numeric values. The integer, float, and complex values belong
to a Python Numbers data-type

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc.
Python has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It
is accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x
and y denote the real and imaginary parts, respectively. The complex
numbers like 2.14j, 2.0 + 2.3j, etc.

Sequence Type

String

The string can be defined as the sequence of characters represented in the


quotation marks. In Python, we can use single, double, or triple quotes to
define a string.
Example - 1

1. str = "string using double quotes"


2. print(str)

List
Python Lists are similar to arrays in C. However, the list can contain data of
different types. The items stored in the list are separated with a comma (,)
and enclosed within square brackets [].

list1 = [1, "hi", "Python", 2]


print (list1)

Tuple
A tuple is similar to the list in many ways. Like lists, tuples also contain the
collection of the items of different data types. The items of the tuple are
separated with a comma (,) and enclosed in parentheses ().
A tuple is a read-only data structure as we can't modify the size and value
of the items of a tuple.
Example:
tup = ("hi", "Python", 2)
print (tup)

Dictionaries
Dictionaries are basically unordered collection of key-value pairs.

Dictionaries are defined within braces and contain key:value pairs. Keys and
values can be of any data type.

Example:

myDict = { 1 : "Devjeet", 2 : "Akash" }

Set
Python Set is the unordered collection of the data type. It is iterable, mutable
(can modify after creation), and has unique elements.

Boolean
Boolean type provides two built-in values, True and False. These values are
used to determine the given statement true or false.
Python Operators

The operator is a symbol that performs a certain operation between two operands.
The different operators that Python offers are listed here.

o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators

Arithmetic Operators

Arithmetic operations between two operands are carried out using arithmetic
operators.

Operator Description

+ (Addition) It is used to add two operands. For example, if a = 10, b = 10 => a+b = 20

- (Subtraction) It is used to subtract the second operand from the first operand. If the
first operand is less than the second operand, the value results negative.
For example, if a = 20, b = 5 => a - b = 15

/ (divide) It returns the quotient after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a/b = 2.0

* It is used to multiply one operand with the other. For example, if a = 20, b
(Multiplication) = 4 => a * b = 80

% (reminder) It returns the reminder after dividing the first operand by the second
operand. For example, if a = 20, b = 10 => a%b = 0

** (Exponent) As it calculates the first operand's power to the second operand, it is an


exponent operator.

// (Floor It provides the quotient's floor value, which is obtained by dividing the
division) two operands.
Comparison operator

Comparison operators compare the values of the two operands and return a true or
false Boolean value in accordance.

Operator Description

== If the value of two operands is equal, then the condition becomes true.

!= If the value of two operands is not equal, then the condition becomes
true.

<= The condition is met if the first operand is smaller than or equal to the
second operand.

>= The condition is met if the first operand is greater than or equal to the
second operand.

> If the first operand is greater than the second operand, then the condition
becomes true.

< If the first operand is less than the second operand, then the condition
becomes true.

Assignment Operators

The right expression's value is assigned to the left operand using the assignment
operators. The following table provides a description of the assignment operators.

Operator Description

= It assigns the value of the right expression to the left operand.

+= By multiplying the value of the right operand by the value of the left
operand, the left operand receives a changed value. For example, if a =
10, b = 20 => a+ = b will be equal to a = a+ b and therefore, a = 30.

-= It decreases the value of the left operand by the value of the right
operand and assigns the modified value back to left operand. For
example, if a = 20, b = 10 => a- = b will be equal to a = a- b and therefore,
a = 10.
*= It multiplies the value of the left operand by the value of the right
operand and assigns the modified value back to then the left operand.
For example, if a = 10, b = 20 => a* = b will be equal to a = a* b and
therefore, a = 200.

%= It divides the value of the left operand by the value of the right operand
and assigns the reminder back to the left operand. For example, if a = 20,
b = 10 => a % = b will be equal to a = a % b and therefore, a = 0.

**= a**=b will be equal to a=a**b, for example, if a = 4, b =2, a**=b will assign
4**2 = 16 to a.

//= A//=b will be equal to a = a// b, for example, if a = 4, b = 3, a//=b will


assign 4//3 = 1 to a.

Bitwise Operators

The two operands' values are processed bit by bit by the bitwise operators. Consider
the case below.

For example,

1. if a = 7
2. b=6
3. then, binary (a) = 0111
4. binary (b) = 0110
5.
6. hence, a & b = 0011
7. a | b = 0111
8. a ^ b = 0100
9. ~ a = 1000

Operator Description

& (binary A 1 is copied to the result if both bits in two operands at the same
and) location are 1. If not, 0 is copied.

| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the
resulting bit will be 1.
^ (binary If the two bits are different, the outcome bit will be 1, else it will be 0.
xor)

~ (negation) The operand's bits are calculated as their negations, so if one bit is 0,
the next bit will be 1, and vice versa.

<< (left The number of bits in the right operand is multiplied by the leftward
shift) shift of the value of the left operand.

>> (right The left operand is moved right by the number of bits present in the
shift) right operand.

Logical Operators

The assessment of expressions to make decisions typically makes use of the logical
operators. The following logical operators are supported by Python.

Operator Description

and The condition will also be true if the expression is true. If the two
expressions a and b are the same, then a and b must both be true.

or The condition will be true if one of the phrases is true. If a and b are the
two expressions, then an or b must be true if and is true and b is false.

not If an expression a is true, then not (a) will be false and vice versa.

Membership Operators

The membership of a value inside a Python data structure can be verified using
Python membership operators. The result is true if the value is in the data structure;
otherwise, it returns false.

Operator Description

in If the first operand cannot be found in the second operand, it is


evaluated to be true (list, tuple, or dictionary).

not in If the first operand is not present in the second operand, the evaluation is
true (list, tuple, or dictionary).
Identity Operators
Operator Description

is If the references on both sides point to the same object, it is determined


to be true.

is not If the references on both sides do not point at the same object, it is
determined to be true.

Basic Input / Output statements

Reading Input

In Python, input() function is used to gather data from the user. The syntax for input
function is,
variable_name = input([prompt])

prompt is a string written inside the parenthesis that is printed on the screen. The
prompt statement gives an indication to the user of the value that needs to be entered
through the keyboard. When the user presses Enter key, the program resumes and input
returns what the user typed as a string. Even when the user inputs a number, it is
treated as a string which should be casted or converted to number explicitly using
appropriate type casting function.

Example1:

val =input("Enter your value: ")


print(val)

 When input() function executes program flow will be stopped until the user has
given input.
 The text or message displayed on the output screen to ask a user to enter an input
value is optional i.e. the prompt, which will be printed on the screen is optional.
 Whatever you enter as input, the input function converts it into a string. if you
enter an integer value still input() function converts it into a string. You need to
explicitly convert it into an integer in your code using typecasting.

Ex 2
num =input("Enter number :")
print(num)
There are various function that are used to take as desired input few of them are : –

 int(input())
 float(input())

num =int(input("Enter a number: "))


print(num, " ", type(num)
floatNum =float(input("Enter a decimal number: "))
print(floatNum, " ", type(floatNum))

Output Statement :
The print() function allows a program to display text onto the console. The print
function will print everything as strings and anything that is not already a string is
automatically converted to its string representation. For example,

1. >>> print("Hello World!!")


Hello World!!

prints the string Hello World!! onto the console. Notice that the string Hello World is
enclosed within double quotes inside the print() function.

Python Casting

Type Casting is the method to convert the variable data type into a certain data
type in order to the operation required to be performed by users. In this article, we
will see the various technique for typecasting.

There can be two types of Type Casting in Python –


 Implicit Type Casting
 Explicit Type Casting

Implicit Type Conversion


In this, methods, Python converts data type into another data type automatically.
In this process, users don’t have to involve in this process.
a =7
b =3.0
c =a +b
print(c)
print(type(c))

Explicit Type Casting


In this method, Python need user involvement to convert the variable data type
into certain data type in order to the operation required.

Mainly in type casting can be done with these data type function:

 Int() : Int() function take float or string as an argument and return int
type object.
 float() : float() function take int or string as an argument and return float
type object.
 str() : str() function take float or int as an argument and return string type
object.
 Type Casting int to float:
 Here, we are casting integer object to float object with float() function.

a =5
# typecast to float
n =float(a)
print(n)
print(type(n))

Output:
5.0

<class 'float'>

Type Casting float to int:


Here, we are casting float data type into integer data type with int() function.

# int variable
a =5.9

# typecast to int
n =int(a)

print(n)
print(type(n))

Output:
5

<class 'int'>

Control Flow Statements

There comes situations in real life when we need to make some decisions and
based on these decisions, we decide what should we do next. Similar situations
arise in programming also where we need to make some decisions and based on
these decisions we will execute the next block of code. Decision-making statements
in programming languages decide the direction of the flow of program execution.

In Python, if-else statement is used for decision making.

if statement
if statement is the most simple decision-making statement. It is used to decide
whether a certain statement or block of statements will be executed or not i.e if a
certain condition is true then a block of statement is executed otherwise not.

if condition:
# Statements to execute if
# condition is true

Here, the condition after evaluation will be either true or false. if the statement
accepts boolean values – if the value is true then it will execute the block of
statements below it otherwise not.
As we know, python uses indentation to identify a block. So the block under an if
statement will be identified as shown in the below example:

if condition:

statement1

statement2
Flowchart of Python if statement

Example:

i=10
if(i>15):
print("10 is less than 15")

output:

Program Reads a Number and Prints a Message If It Is Positive

number = int(input("Enter a number"))


if number >= 0:
print(f"The number entered by the user is a positive number")

Output
Enter a number 67
The number entered by the user is a positive number

Program to Read Luggage Weight and Charge the Tax Accordingly


weight = int(input("How many pounds does your suitcase weigh?"))
if weight >50:
print(f"There is a $25 surcharge for heavy luggage")
print(f"Thank you")
Output
How many pounds does your suitcase weigh? 75
There is a $25 surcharge for heavy luggage
Thank you
if-else
The if statement alone tells us that if a condition is true it will execute a block of
statements and if the condition is false it won’t. But what if we want to do
something else if the condition is false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code when the condition is
false.
Syntax:
if (condition):

# Executes this block if

# condition is true

else:

# Executes this block if

# condition is false

FlowChart of Python if-else statement

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
A number is read and stored in the variable named number ➀. The number is checked
using modulus operator ➁to determine whether the number is perfectly divisible by
2 or not. If the number is perfectly divisible by 2, then the expression is evaluated to
True and number is even ➂. However, ➃if the expression evaluates to False, the
number is odd ➄.

Program to Find the Greater of Two Numbers

number_1 = int(input("Enter the first number"))


number_2 = int(input("Enter the second number"))

if number_1 >number_2:
print(f"{number_1} is greater than {number_2}")
else:
print(f"{number_2} is greater than {number_1}")
Output
Enter the first number 8
Enter the second number 10
10 is greater than 8

if-elif-else ladder
Here, a user can decide among multiple options. The if statements are executed
from the top down. As soon as one of the conditions controlling the if is true, the
statement associated with that if is executed, and the rest of the ladder is bypassed.
If none of the conditions is true, then the final else statement will be executed.

Syntax:
if (condition):
statement
elif (condition):
statement
.else:
statement

FlowChart of Python if else elif statements


Write a Program to Prompt for a Score between 0.0 and 1.0. If the
Score Is Out of Range, Print an Error. If the Score Is between 0.0
and 1.0, Print a Grade Using the Following Table
Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
>= 0.6 D
<0.6 F
score = float(input("Enter your score"))
if score <0 or score >1:
print('Wrong Input')
elif score >= 0.9:
print('Your Grade is "A" ')
elif score >= 0.8:
print('Your Grade is "B" ')
elif score >= 0.7:
print('Your Grade is "C" ')
elif score >= 0.6:
print('Your Grade is "D" ')
else:
print('Your Grade is "F" ')
Output
Enter your score0.92
Your Grade is "A"
A number is read and is assigned to the variable score ➀. If the score value is greater
than1 or less than 0 ➁then we display an error message indicating to the user that it
is a wronginput ➂. If not, the score value is checked for different conditions based on
the score tableand the grade statements are printed accordingly ➃– .

Program to Display the Cost of Each Type of Fruit


fruit_type = input("Enter the Fruit Type:")
if fruit_type == "Oranges":
print('Oranges are $0.59 a pound')
eliffruit_type == "Apples":
print('Apples are $0.32 a pound')
eliffruit_type == "Bananas":
print('Bananas are $0.48 a pound')
eliffruit_type == "Cherries":
print('Cherries are $3.00 a pound')
else:
print(f'Sorry, we are out of {fruit_type}')
Output
Enter the Fruit Type: Cherries
Cherries are $3.00 a pound

nested-if
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, Python allows us
to nest if statements within if statements. i.e, we can place an if statement inside
another if statement.

Syntax:
if (condition1):

# Executes when condition1 is true

if (condition2):

# executes when condition2 is true

# if Block is end here

# if Block is end here


Flowchart of Python Nested if Statement

Example: Python Nested if

i=10
if(i==10):
# First if statement
if(i<15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if(i<12):
print("i is smaller than 12 too")
else:
print("i is greater than 15")

Output:

i is smaller than 15

i is smaller than 12 too


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')
Output
Enter a year 2014
2014 is not a Leap Year

The while Loop

The while loop starts with the while keyword and ends with a colon. With a while
statement, the first thing that happens is that the Boolean expression is evaluated
before thestatements in the while loop block is executed. If the Boolean expression
evaluates to False,then the statements in the while loop block are never executed. If
the Boolean expressionevaluates to True, then the while loop block is executed. After
each iteration of the loopblock, the Boolean expression is again checked, and if it is
True, the loop is iterated again.

Syntax:
while expression:
statement(s)

Flowchart of While Loop :


Write Python Program to Display First 10 Numbers Using
while Loop Starting from 0
i=0
while i<10:
print(f"Current value of i is {i}")
i = i+ 1
Output
Current value of i is 0
Current value of i is 1
Current value of i is 2
Current value of i is 3
Current value of i is 4
Current value of i is 5
Current value of i is 6
Current value of i is 7
Current value of i is 8
Current value of i is 9

Variable iis assigned with 0 outside the loop ➀. The expression i<10 is evaluated ➁.
If thevalue of iis less than 10 (i.e., True) then the body of the loop is executed. Value
of iis printed ➂and iis incremented by 1 ➃. This continues until the expression in
while loop becomes False.

Program 3.9: Write a Program to Find the Average of n Natural NumbersWhere nIs
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
Program to Find the GCD of Two Positive Numbers
m = int(input("Enter first positive number"))
n = int(input("Enter second positive number"))
if m == 0 and n == 0:
print("Invalid Input")
if m == 0:
print(f"GCD is {n}")
if n == 0:
print(f"GCD is {m}")
while m != n:
if m >n:
m=m–n
if n >m:
n=n–m
print(f"GCD of two numbers is {m}")
Output
Enter first positive number8
Enter second positive number12
GCD of two numbers is 4
Read the value for m and n ➀–➁. If both m and n are zero then it is invalid input
because
zero cannot be divided by zero which is indeterminate ➂–➃. If either m or n is zero
then
the other one is gcd➄–➇. If the value of m >n then m = m – n or if n >m then n = n –
m.
The logic in line _– is repeated until the value of m is equal to the value of n ➈. Then
gcd
will be either m or n .
Program 3.11: Write Python Program to Find the Sum of Digits in a Number
number = int(input('Enter a number'))
result = 0
remainder = 0
while number != 0:
remainder = number % 10

result = result + remainder


number = int(number / 10)
print(f"The sum of all digits is {result}")
Output
Enter a number1234
The sum of all digits is 10

Write a Program to Display the Fibonacci Sequences up to nthTerm Where n is


Provided by the User
nterms = int(input('How many terms?'))
current = 0
previous = 1
count = 0
next_term = 0
if nterms<= 0:
print('Please enter a positive number')
elifnterms == 1:
print('Fibonacci sequence')
print('0')
else:
print("Fibonacci sequence")
while count <nterms:
print(next_term)
current = next_term
next_term = previous + current
previous = current
count += 1
Output
How many terms? 5
Fibonacci sequence
01123

Program to Repeatedly Check for the Largest Number Until theUser Enters
“done”
largest_number = int(input("Enter the largest number initially"))
check_number = input("Enter a number to check whether it is largest or not")
while check_number != "done":
if largest_number>int(check_number):
print(f"Largest Number is {largest_number}")
else:
largest_number = int(check_number)
print(f"Largest Number is {largest_number}")
check_number = input("Enter a number to check whether it is largest or not")
Output
Enter the largest number initially 5
Enter a number to check whether it is largest or not 1
Largest Number is 5
Enter a number to check whether it is largest or not 10
Largest Number is 10
Enter a number to check whether it is largest or not 8
Largest Number is 10
Enter a number to check whether it is largest or not done

Multiplication Table using While Loop


num = 21
counter = 1
# we will use a while loop for iterating 10 times for the multiplication table

print("The Multiplication Table of: ", num)


while counter <= 10: # specifying the condition
ans = num * counter
print (num, 'x', counter, '=', ans)
counter += 1 # expression to increment the counter

Program to find the sum of 10 natural numbers.


i=1 sum=0
while i<=10:
sum=sum+i
i=i+1
print(sum)

The for Loop


The for loop starts with for keyword and ends with a colon. The first item in the
sequence gets assigned to the iteration variable iteration_variable. Here,
iteration_variablecan be any valid variable name. Then the statement block is
executed. This process of assigning items from the sequence to the
iteration_variableand then executing the statement continues until all the items in the
sequence are completed. We take the liberty of introducing you to range() function
which is a built-in function at this stage as it is useful in demonstrating for loop. The
range() function generates a sequence of numbers which can be iterated through
using for loop. The syntax for range() function is,

A range is a series of values between two numeric intervals.

range([start ,] stop [, step])


Both start and step arguments are optional and the range argument value should
always be an integer.
start → value indicates the beginning of the sequence. If the start argument is not
specified, then the sequence of numbers start from zero by default.
stop → Generates numbers up to this value but not including the number itself.
step → indicates the difference between every two consecutive numbers in
thesequence. The step value can be both negative and positive but not zero.

Loop through the letters in the word "banana":


for x in "banana":
print(x)

Output:
b
a
n
a
n
a
Example 2
languages = ['Swift', 'Python', 'Go', 'JavaScript']

# access items of a list using for loop


for language in languages:
print(language)

output:

Swift
Python
Go
JavaScript
The range () function:
 We can generate a sequence of numbers using range() function. range (10)
will generate numbers from 0 to 9 (10 numbers).
 We can also define the start, stop and step size as range
(start,stop,step_size). step_size defaults to 1, start to 0 and stop is end of
object if not provided.
 This function does not store all the values in memory; it would be
inefficient. So, it remembers the start, stop, step size and generates the next
number on the go.

Write a Program to Find the Sum of All Odd and Even Numbers
up to a Number Specified by the User.
number = int(input("Enter a number"))
even = 0
odd = 0
for i in range(number):
if i% 2 == 0:
even = even + i
else:
odd = odd + i
print(f"Sum of Even numbers are {even} and Odd numbers are {odd}")

Output
Enter a number 10
Sum of Even numbers are 20 and Odd numbers are 25

Write a Program to Find the Factorial of a Number


number = int(input('Enter a number'))
factorial = 1
if number <0:
print("Factorial doesn't exist for negative numbers")
elif number == 0:
print('The factorial of 0 is 1')
else:
for i in range(1, number + 1):
factorial = factorial * i
print(f"The factorial of number {number} is {factorial}")
Output
Enter a number 5
The factorial of number 5 is 120
The factorial of a non-negative integer n is denoted by n! which is the product of all
positive
integers less than or equal to n i.e., n! = n * (n − 1) * (n − 2) * (n − 3)… 3 * 2 * 1. For
example,
5! = 5 × 4 × 3 × 2 × 1 = 120.
The value of 0! is 1

The continue and break Statements

The break and continue statements provide greater control over the execution of
codein a loop. Whenever the break statement is encountered, the execution control
immediately jumps to the first instruction following the loop. To pass control to the
next iteration without exiting the loop, use the continue statement. Both continue and
break statements can be used in while and for loops.

Ex1:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Output:
apple
banana

ex 3
# program to find first 5 multiples of 6

i=1
while (i<=10):
print('6 * ',(i), '=',6 * i)
if i>= 5:
break
i=i+1

Output
6* 1=6
6* 2 = 12
6* 3 = 18
6* 4 = 24
6* 5 = 30

Example

n=0
while True:
print(f"The latest value of n is {n}")
n=n+1
if n >5:
print(f"The value of n is greater than 5")
break
Output
The latest value of n is 0
The latest value of n is 1
The latest value of n is 2
The latest value of n is 3
The latest value of n is 4
The latest value of n is 5
The value of n is greater than 5

Write a Program to Check Whether a Number Is Prime or Not


number = int(input('Enter a number >1: '))
prime = True
for i in range(2, number):
if number % i == 0:
prime = False
break
if prime:
print(f"{number} is a prime number")
else:
print(f"{number} is not a prime number")
Output
Enter a number >1: 7
7 is a prime number
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

Program to Demonstrate continue Statement


n = 10
while n >0:
print(f"The current value of number is {n}")
if n == 5:
continue
n=n–1
Output
The current value of number is 10
The current value of number is 9
The current value of number is 8
The current value of number is 7
The current value of number is 6
The current value of number is 4
The current value of number is 3
The current value of number is 2
The current value of number is 1

1. # Python program to find the largest number among the three input numbers
2. # take three numbers from user
3. num1 =float(input("Enter first number: "))
4. num2 =float(input("Enter second number: "))
5. num3 =float(input("Enter third number: "))
6.
7. if(num1 > num2)and(num1 > num3):
8. largest = num1
9. elif(num2 > num1)and(num2 > num3):
10. largest = num2
11. else:
12. largest = num3
13. print("The largest number is",largest)
Function in python

Functions in python are basically a block of code which gets executed when it is
invoked.

Why do you need functions in Python

1. Sometimes, you need to perform a task multiple times in a program. And


you don’t want to copy the code for that same task all over places. To do so,
you wrap the code in a function and use this function to perform the task
whenever you need it.
2. Functions are used to divide a large program into smaller and more
manageable parts. The functions will make your program easier to develop,
read, test, and maintain.

Syntax:

Def function_name(arguments):
Statements
return (values)

Defining a Python function

Here’s a simple function that shows a greeting:

def greet():

""" Display a greeting to users """

print('Hi')

This example shows the simplest structure of a function. A function has two main
parts: a function definition and body.

1) Function definition

A function definition starts with the def keyword and the name of the function
(greet). If the function needs some information to do its job, you need to specify it
inside the parentheses (). The greet function in this example doesn’t need any
information, so its parentheses are empty.
The function definition always ends in a colon (:).

2) Function body

All the indented lines that follow the function definition make up the function’s
body. The line print('Hi') is the only line of actual code in the function body. The
greet() function does one task: print('Hi').

Calling a function

When you want to use a function, you need to call it. A function call instructs
Python to execute the code inside the function.

To call a function, you write the function’s name, followed by the information that
the function needs in parentheses.

The following example calls the greet() function. Since the greet() function doesn’t
need any information, you need to specify empty parentheses like this:

You might also like