You are on page 1of 81

PYTHON

CONDITIONAL STATEMENTS

BY AMIT PATEL
CONDITIONAL STATEMENTS

 Conditional Statement in Python perform different computations or actions depending on


whether a specific Boolean constraint evaluates to true or false.

 In order to write useful programs, we almost always need the ability to check conditions and
change the behavior of the program accordingly. Conditional statements give us this ability.

 Conditional statements are handled by IF statements in Python.


 If
 If….else
 If..elif…else
 Nested if..else
CONDITIONAL STATEMENTS : if

 Python if Statement is used for decision-making operations.

 Also known as : Branching Statement

 Branching statement means the ability of program to alter its execution sequences.

 It contains a body of code which runs only when the condition given in the if statement is
true.
If <condition> :
statements
CONDITIONAL STATEMENTS : if

Important points to note about if statement:

 The colon (:) is significant and required. It separates the header of the compound
statement from the body.

 The line after the colon must be indented. It is standard in Python to use four spaces for
indenting.

 All lines indented the same amount after the colon will be executed whenever the condition
is true.
CONDITIONAL STATEMENTS : if

For Example

food = ‘pizza'

if food == ‘pizza':

print('Ummmm, my favorite!')

print('I feel like saying it 100 times...')

print(100 * (food + '! '))


CONDITIONAL STATEMENTS : if … else

 It is frequently the case that you want one thing to happen when a condition true, and
something else to happen when it is false.

 For that we have the if else statement.

If <condition> :
statements
else :
statements
CONDITIONAL STATEMENTS : if … else

For Example

food = ‘pizza'

if food == ‘pizza':

print('Ummmm, my favorite!’)

else:

print(‘I like burger not pizza')


Shorthand if … else conditional expresssion

 Python provides a shorter syntax, which allows writing such


conditions in a single line of code.

 It is known as a conditional expression, sometimes also


referred to as a ternary operator.

 It has the following syntax:

var = true_value if condition else false_value


Shorthand if … else conditional expresssion

 For Example:

a_number=13;

parity = 'even' if a_number % 2 == 0 else 'odd‘

print('The number {} is {}.'.format(a_number, parity))

Output:

The number 13 is odd.


CONDITIONAL STATEMENTS : elif

 The elif statement enables us to check multiple conditions If <condition> :


and execute the specific block of statements depending statements
upon the true condition among them. elif <condition> :

 We can have any number of elif statements in our program statements

depending upon our need. However, using elif is optional. elif <condition> :
statements
 The elif statement works like an if-else-if ladder statement in
<else:>
C. It must be succeeded by an if statement.
statements
CONDITIONAL STATEMENTS : elif

For Example elif number==100:


print("number { } is equal to 100“,.format(number));
number = int(input("Enter the number?"))
else:
if number==10: print("number is not equal to 10, 50 or 100");

print(“number
{ } is equals to 10“,.format(number))
Output:
elif number==50: Enter the number?15

print("number { } is equal to 50“,.format(number)); number is not equal to 10, 50 or 100


“pass” statement

 if statements cannot be empty, there must be at least one statement in every if and elif block.

 You can use the pass statement to do nothing and avoid getting an error.

 For example:

a_number = 9
Output:
if a_number % 2 == 0: elif a_number % 3 == 0: File "<ipython-input-33-77268dd66617>", line 2
print('{} is divisible by 3 but not divisible by 2') elif a_number % 3 == 0:
^ IndentationError: expected an indented block
“pass” statement

a_number=9

if a_number % 2 == 0:

pass

elif a_number % 3 == 0:

print('{} is divisible by 3 but not divisible by 2'.format(a_number))

Output:
9 is divisible by 3 but not divisible by 2
format( )

 The format() method formats the specified value(s) and insert them inside the string's
placeholder.

 The placeholder is defined using curly brackets: {}. Read more about the placeholders in the
Placeholder section below.

 The format() method returns the formatted string.

string.format (value1, value2...)


format( )

 The format() method formats the specified value(s) and insert them inside the string's placeholder.

 The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder
section below.

 The format() method returns the formatted string.

string.format (value1, value2...)

 Where value1,value2 is required. It is the value that should be formatted and inserted in the string.

 It is either a list of values seperated by commas , a key=value list or a combination of both.

 It is any type of data.


format( )

For Example:

 txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)

 txt2 = "My name is {0}, I'm {1}".format("John",36)

 txt3 = "My name is {}, I'm {}".format("John",36)

 txt = “I have only {price:.2f} Rs." Output:


My name is John, I'm 36
print(txt.format(price = 49))
My name is John, I'm 36
My name is John, I'm 36
I have only 49.00 Rs.
Non Boolean Condition

 Note that conditions do not necessarily have to be booleans.

 In fact, a condition can be any value.

 The value is converted into a boolean automatically using the bool operator.

 This means that false values like 0, '', {}, [], None etc. evaluate to False and all other values
evaluate to True.
Non Boolean Condition

if '': if “Hi”:

print('The condition evaluted to True') print('The condition evaluted to True')

else: else:

print('The condition evaluted to False') print('The condition evaluted to False')

Output:
Output:
The condition evaluted to False The condition evaluted to True
LOOPING STATEMENT

 The flow of the programs written in any programming language is sequential by default.
Sometimes we may need to alter the flow of the program.

 The execution of a specific code may need to be repeated several numbers of times.

 For this purpose, The programming languages provide various types of loops which are capable
of repeating some specific code several numbers of times.
LOOPING STATEMENT

Advantages of loops

 There are the following advantages of loops in Python.

 It provides code re-usability.

 Using loops, we do not need to write the same code again and again.

 Using loops, we can traverse over the elements of data structures (array or linked lists).
LOOPING STATEMENT : for

 The for loop in Python is used to iterate the statements or a part of the program several times. It
is frequently used to traverse the data structures like list, tuple, or dictionary.

 Syntax:

for iterating_var in sequence:

statement(s)
LOOPING STATEMENT : for

For Example 1 : For Example 2: For Example 3:


list = [10,30,23,43,65,12] for char in 'MONDAY': person = { 'name': ‘Om', 'age': 32 }
sum = 0 print(char) for key in person:
for i in list: Output: print("Key:", key, ",", "Value:", person[key])

sum = sum+i M
O Output:
print("The sum is:",sum)
N Key: name , Value: Om
D Key: age , Value: 32
Output:
A
The sum is: 183
Y
FOR LOOP USING range( )

 The range function is used to create a sequence of numbers that can be iterated over using
a for loop. It can be used in 3 ways:

1. range(n) - Creates a sequence of numbers from 0 to n-1


2. range(a, b) - Creates a sequence of numbers from a to b-1
3. range(a, b, step) - Creates a sequence of numbers from a to b-1 with increments of step
FOR LOOP USING range( )

Syntax: range ( start, stop, step size )

 If we pass the range(10), it will generate the numbers from 0 to 9.

 The start represents the beginning of the iteration.

 The stop represents that the loop will iterate till stop-1. The range(1,5) will generate numbers 1
to 4 iterations. It is optional.

 The step size is used to skip the specific numbers from the iteration. It is optional to use. By
default, the step size is 1. It is optional.
Note : range( )

To quickly recap the range() function when passing one, two, or three parameters:

 One parameter will create a sequence, one-by-one, from zero to one less than the parameter.

 Two parameters will create a sequence, one-by-one, from the first parameter to one less than
the second parameter.

 Three parameters will create a sequence starting with the first parameter and stopping before
the second parameter, but this time increasing each step by the third parameter.
FOR LOOP USING range( )

For Example
for i in range(10): n = int(input("Enter the number ")) list = [‘om',‘sai',’ram‘]
for i in range(2,n,2): for i in range(len(list)):
print(i,end = ' ')
print(i) print("Hello",list[i])

Output: Output: Output:


0123456789 Enter the number 10 om

2 sai

4 ram

6
8
FOR LOOP WITH ELSE()

 A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts.

 The break keyword can be used to stop a for loop. In such cases, the else part is ignored.

 Hence, a for loop's else part runs if no break occurs.


FOR LOOP USING range( )

For Example
digits = [0, 1, 5]  Here, the for loop prints items of the list until the loop

for i in digits: exhausts. When the for loop exhausts, it executes the block of

print(i) code in the else and prints No items left.

else:  This for...else statement can be used with the break keyword to
run the else block only when the break keyword was not executed.
print("No items left.")

Output:
0 1 5 No items left.
Note

 For Example: We want to print number 5 and if we write following code it gives above error.

for x in 5:

print(x)

TypeError : “int” object is not inerrable.

In the above example, we are trying to iterate through a for loop using an integer value. But the
integers are not inerrable. As the single integer value 5, it cannot be iterated using a for loop or any
other loop.
Note

 For Example: We want to print number 5 in the following way , using list, it cant give error

for x in [5]:

print(x)

Output : 5

 In the above example, we printing the elements of the list using the for loop. since the list is an iterable
object, thus we can use the for loop to iterate through it.

 Thus, the TypeError is not encountered here.

 Dictionaries are also iterable in Python using the loops.


Note

 To check which datatype is inerrable and which is not , Write following code: It show all method of list. Find
_iter_ method : If it is present then datatype is inerrable.

List= [ ]

print(dir(List))

Output : ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__',


'__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
'__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__',
'__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
LOOPING STATEMENT : WHILE

 The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

 We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax
while test_expression:
Body of while
LOOPING STATEMENT : WHILE

 In the while loop, test expression is checked first. The body of the loop is entered only if
the test_expression evaluates to True.

 After one iteration, the test expression is checked again. This process continues until
the test_expression evaluates to False.

 In Python, the body of the while loop is determined through indentation.

 The body starts with indentation and the first unindented line marks the end.

 Python interprets any non-zero value as True. None and 0 are interpreted as False.
LOOPING STATEMENT : WHILE

For Example
n = 10
sum = 0
i=1
while i <= n:
sum = sum + i
Output:
i = i+1
The sum is 55
print("The sum is", sum)
WHILE LOOP WITH ELSE()

 Same as with for loops, while loops can also have an optional else block.

 The else part is executed if the condition in the while loop evaluates to False.

 The while loop can be terminated with a break statement. In such cases, the else part is ignored.
Hence, a while loop's else part runs if no break occurs and the condition is false.
LOOPING STATEMENT : WHILE

For Example
counter = 0
Output:
while counter < 3:
Inside loop
print("Inside loop")
Inside loop
counter = counter + 1
Inside loop
else: Inside else
print("Inside else")
Note: When to use which loop?

 Use while loop when you want to repeat an action until a condition
changes.

 Use for loop when there’s a sequence of element that you want to
iterate.
“break” Statement

 break is used for breaking out of the loop.

 For Example:

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

for day in weekdays:

print('Today is {}'.format(day)) Output:

if (day == 'Wednesday'): Today is Monday


Today is Tuesday
print("I don't work beyond Wednesday!")
Today is Wednesday
break I don't work beyond Wednesday!
“continue” Statement

 continue is used for skipping ahead to the next iteration.

 For Example:

weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']


for day in weekdays:
print('Today is {}'.format(day)) Output:
if (day == 'Wednesday'): Today is Monday

print("I don't work beyond Wednesday!") Today is Tuesday


I don't work beyond Wednesday!
continue
Today is Thursday
print('Today is {}'.format(day))
Today is Friday
Nested Loop

 loops can be nested inside other loops. This is useful for looping lists of lists, dictionaries etc.

Output:
 For Example:
Monday apple
days = ['Monday', 'Tuesday', 'Wednesday']
Monday banana
fruits = ['apple', 'banana', 'guava']
Monday guava
for day in days: Tuesday apple
for fruit in fruits: Tuesday banana
print(day, fruit) Tuesday guava
Wednesday apple
Wednesday banana
List

 Used to store the sequence of various types of data.

 Mutable type its mean we can modify its element after it created.

 A list can be defined as a collection of values or items of different types.

 Enclosed with the square brackets [ ].

 The items in the list are separated with the comma (,) .
 For Example: L1 = ["John", 102, "USA"]

L2 = [1, 2, 3, 4, 5, 6]

LSM = List Subscript Mutable


Characteristics of List

 The lists are ordered.

 The element of the list can access by index.

 The lists are the mutable type.

 A list can store the number of various elements.


Create List

 There are two way to create a list.

1. To add your items between two square brackets.

For Example: items = [1, 2, 3, 4]

2. To call the Python list built-in function by passing the items to it.

For Example: Items = list(1, 2,3,4)


Create List

 The list can accept any data type.

 You can have a list of integers and strings.

 List in python doesn't enforce to have a single item type in it. You can have a list of different items.

[1, 'name', {"key" : "value"}, list(1, 2, 3)]

 This gives you the flexibility to add multiple data types in the list.

 You can add a list inside this list. This is called a nested list.

my_list = ["mouse", [8, 4, 6], ['a']]


List Methods

Method Description
append() adds an element to the end of the list

extend() adds all elements of a list to another list

insert() inserts an item at the defined index

remove() removes an item from the list

pop() returns and removes an element at the given index

clear() removes all items from the list

index() returns the index of the first matched item

count() returns the count of the number of items passed as an argument


List Methods

Method Description
sort() sort items in a list in ascending order

reverse() reverse the order of items in the list

copy() returns a shallow copy of the list


Access Element from List

 There are different way to access the list element.


 List Index
 Slicing
 Negative Index
Access Element from List : List Index

 We can use the index operator [ ] to access an item in a list.

 In Python, indices start at 0. So, a list having 5 elements will have an index from 0 to 4.

 Trying to access indexes other than these will raise an IndexError.

 The index must be an integer.

 We can't use float or other types, this will result in TypeError.

 Nested lists are accessed using nested indexing.


Access Element from List : List Index

my_list = ['p', 'r', 'o', 'b', 'e'] # Nested List

# first item print n_list = ["Happy", [2, 0, 1, 5]]


# Print 2nd element of first list
(my_list[0]) #p
print(n_list[0][1]) #a
# third item # Print 4th element of 2nd list
print(n_list[1][3]) #5
print(my_list[2]) #o
print(my_list[4.0]) # Error
# fifth item

print(my_list[4]) #e
Access Element from List : slicing

 We can access a range of items in a list by using the slicing operator :

my_list = ['p','r','o','g','r','a','m','i',‘n'] Note:


When we slice lists, the start
# elements from index 2 to index 4
index is inclusive but the end
print(my_list[2:5]) #[‘o’,’g’,’r’] index is exclusive. For
example, my_list[2: 5] returns a
# elements from index 5 to end
list with elements at index 2, 3
print(my_list[5:]) # ['a','m','i','z']
and 4, but not 5.
# elements beginning to end

print(my_list[:]) # ['p','r','o','g','r','a','m','i',‘n']
Access Element from List : Negative Index

 Python provides the flexibility to use the negative indexing also.

 The negative indices are counted from the right.

 The last element (rightmost) of the list has the index -1.

 Its adjacent left element is present at the index -2 and so on until the left-most elements are
encountered.
Access Element from List : Negative Index

# Negative indexing in lists


# Slicing with negative index
my_list = ['p','r','o','b','e']
print(my_list[-2:] # [‘b’,’e’]
# last item

Print(my_list[-4:-2] #[‘r’,’o’]
print(my_list[-1]) #e

# fifth last item

print(my_list[-5]) #p
Updating Element in List

 append() : add one item to a list

 extend(): add several items to a list

 For Example:

odd = [1, 3, 5]
odd. append(7)
print(odd)
Output:
odd. extend([9, 11, 13]) [1, 3, 5, 7]
print(odd) [1, 3, 5, 7, 9, 11, 13]
Updating Element in List

list = [1, 2, 3, 4, 5, 6]
print(list)
print(list) # It will add value at the end of the list
list[-1] = 25
# assign value to the value to the second index
print(list)
list[2] = 10

print(list) Output:
[1, 2, 3, 4, 5, 6]
# Adding multiple-element
[1, 2, 10, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Updating Element in List

 Lists are the most versatile data structures in Python since they are mutable, and their values
can be updated by using the slice and assignment operator.

 Python also provides append() and insert() methods, which can be used to add values to the
list.

 Consider the following example to update the values inside the list.
Updating Element in List

list = [1, 2, 3, 4, 5, 6]
print(list)
print(list) # It will add value at the end of the list
list[-1] = 25
# assign value to the value to the second index
print(list)
list[2] = 10

print(list) Output:
[1, 2, 3, 4, 5, 6]
# Adding multiple-element
[1, 2, 10, 4, 5, 6]
list[1:3] = [89, 78] [1, 89, 78, 4, 5, 6]
[1, 89, 78, 4, 5, 25]
Deleting Element from List

 There are various way to delete element from the list

Method Description

del Delete element using index.

pop Same as delete. If skip index, delete last element of list

remove Delete element by its name rather than index.

Clear Empty whole list


Deleting Element from List

 del keyword is used to delete element

 For Example:

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm‘]


# delete the entire list
del my_list[2]
del my_list

print(my_list) # Error: List not defined


print(my_list)
Output
# delete multiple items
['p', 'r', 'b', 'l', 'e', 'm']
del my_list[1:5]
['p', 'm']
Error
Deleting Element from List

 remove() method if we do not know which element is to be deleted from the list.

 pop() to remove an item at the given index.

 The pop() method removes and returns the last item if the index is not provided. This helps us
implement lists as stacks (first in, last out data structure).

 And, if we have to empty the whole list, we can use the clear() method.
Deleting Element from List

 For Example:

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm‘] # remove ‘m’
print(my_list.pop())
my_list.remove(‘p’) Output
print(my_list)
['r', 'o', 'b', 'l', 'e', 'm']
print(my_list) # Clear whole list
o
my_list.clear()
# remove ‘o’ using pop ['r', 'b', 'l', 'e', 'm']
# Output: []
m
my_list.pop(1) print(my_list)
['r', 'b', 'l', 'e']
[]
Copy List

 There are following way to copy the one list to another.


 copy()
 = operator
 Using slicing
Copy List

 copy() method returns a shallow copy of the list.

 It doesn’t take any argument and return a list.

 For Example:

my_list = ['cat', 0, 6.7]


# copying a list
new_list = my_list.copy()
print('Copied List:', new_list)
Copied List: ['cat', 0, 6.7]
Copy List

Using =
old_list = [1, 2, 3]
new_list = old_list

 However, there is one problem with copying lists in this way.

 If you modify new_list, old_list is also modified. It is because the new list is referencing or
pointing to the same old_list object.
Copy List

For Example:
old_list = [1, 2, 3]
# copy list using =
new_list = old_list
# add an element to list
new_list. append('a')
Output
print('New List:', new_list)
Old List: [1, 2, 3, 'a']
print('Old List:', old_list)
New List: [1, 2, 3, 'a']
Copy List

For Example:
list = ['cat', 0, 6.7]
# copying a list using slicing
new_list = list[:]
# Adding an element to the new list
new_list.append('dog')
# Printing new and old list
print('Old List:', list) Output
Old List: ['cat', 0, 6.7]
print('New List:', new_list
New List: ['cat', 0, 6.7, 'dog']
Reverse List

 reverse() is use to reverse the list.

 For Example:

# create a list of prime numbers


prime_numbers = [2, 3, 5, 7]
# reverse the order of list elements
prime_numbers.reverse()
print('Reversed List:', prime_numbers)

Output: Reversed List: [7, 5, 3, 2]


Reverse List

 List can be reverse using slicing operator

 For Example:

systems = ['Windows', 'macOS', 'Linux']


print('Original List:', systems)
# Reversing a list
# Syntax: reversed_list = systems[start:stop:step]
Output:
reversed_list = systems[::-1]
Original List: ['Windows', 'macOS', 'Linux']
# updated list
Updated List: ['Linux', 'macOS', 'Windows']
print('Updated List:', reversed_list)
Index in List

 Index() return the index of the specified element in list.

Syntax: list. index(element, start, end)

Where element - the element to be searched


 start (optional) - start searching from this index
 end (optional) - search the element up to this index

 For Example:

systems = ['Windows', 'macOS', 'Linux']


Index=system.index(‘macOS’)
Output:
print(index)
1
Index in List

 For Example:

vowels = ['a', 'e', 'i', 'o', 'g', 'l', 'i', 'u']


# Search element which is not in list
index = vowels. index('p')
print('The index of p:', index) # Generate value error
Output:
index = vowels.index('i', 4) #6
ValueError : ‘p’ is not in list
print('The index of i:', index) The index of i: 6
# 'i' between 3rd and 5th index is searched Traceback (most recent call last):
index = vowels.index('i', 3, 5) # Error! File "*lt;string>", line 7, in ValueError: 'i' is
print('The index of i:', index) not in list
Sort List

 sort() method sorts the elements of a given list in a specific ascending or descending order.

Syntax: list. sort(key=..., reverse=...)

Where sorted(list, key=..., reverse=...)

 reverse : If True, the sorted list is reversed (or sorted in Descending order)
 key : function that serves as a key for the sort comparison

 Return value : The sort() method doesn't return any value. Rather, it changes the original list.

 If you want a function to return the sorted list rather than change the original list, use sorted().

sort( ) Vs sorted() : sort( ) changes the list directly and doesn't return any value,
while sorted() doesn't change the list and returns the sorted list.
Sorted List

 For Example:

vowels = ['e', 'a', 'u', 'o', 'i']


vowels. sort()
print('Sorted list:', vowels)
# sort the vowels in descending order
vowels. sort(reverse=True)
print('Sorted list (in Descending):', vowels)
Output:
Sorted list: ['a', 'e', 'i', 'o', 'u']
Sorted list (in Descending): ['u', 'o', 'i', 'e', 'a']
Count Element in List

 count() method returns the number of times the specified element appears in the list.

Syntax: list. count(element)


Where
 Element is the element to be counted.

 Return value : the number of times element appears in the list.

 For Example:

numbers = [2, 3, 5, 2, 11, 2, 7]


numbers.count(2)
Output:
print('Count of 2:', count)
Count of 2 :3
Operation on List

Operations Description Example


Repetition The repetition operator (*) enables the list elements to be L1*2 = [1, 2, 3, 4, 1, 2, 3, 4]
(*) repeated multiple times.

Concatenation It concatenates the list mentioned on either side of the l1+l2 = [1, 2, 3, 4, 5, 6, 7, 8]
(+) operator.

Membership It returns true if a particular item exists in a particular list print(2 in l1)
( in ) otherwise false. Give output as True.
Length It is used to get the length of the list len(l1) = 4
Iteration The for loop is used to iterate over the list elements. for i in l1:
print(i)
Write a program to print the sum of list

list1 = [3,4,5,9,10,12,24]
sum = 0
for i in list1:
sum = sum+i
print("The sum is:",sum)

Output:
The sum is 67
Write the program to find the lists consist of at least one common element.

list1 = [1,2,3,4,5,6]
list2 = [7,8,9,2,10]
for x in list1:
for y in list2:
if x == y:
print("The common element is:",x)

Output:
The common element is 2
Exercise

 Given a list of filenames, we want to rename all the files with extension hpp to the extension h. To do
this, we would like to generate a new list called newfilenames, consisting of the new filenames. Fill in
the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list
comprehension.
Exercise

filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]


newfilenames=[]
for filename in filenames:
if _______________:
-------------------------------
-------------------------------
else:
--------------------------------
print(newfilenames)
# Output Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"]
newfilenames=[]
for filename in filenames:
if ".hpp" in filename:
ind=filename.index(".hpp")
newfilenames.append(filename[0:ind]+".h")
else:
newfilenames.append(filename)
print(newfilenames)
# Output Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]
Exercise

 Write the program to remove the duplicate element of the list.


Exercise

def pig_latin(text):
say = ""
words = text.split()
for word in words:
---------------------------
---------------------------
say=say+text+" "
return say

print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"


print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfa
def pig_latin(text):
say = ""
# Separate the text into words
words = text.split()
for word in words:
# Create the pig latin word and add it to the list
length=len(word)
first=word[0]
ext=word[1:length+1]
text=ext+first+"ay"
say=say+text+" "
# Turn the list back into a phrase
return say
print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay"
print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay"

You might also like