Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Python - Lists, For Loop

Uploaded by

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

Python - Lists, For Loop

Uploaded by

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

Python

Lists, Loops

Practice Problems
P11) Check if a number is positive, negative, or zero.

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

if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

P12) Find the maximum of three numbers.


num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
num3 = int(input("Enter the third number: "))

if num1 >= num2 and num1 >= num3:


print("The maximum number is:", num1)
elif num2 >= num1 and num2 >= num3:
print("The maximum number is:", num2)
else:
print("The maximum number is:", num3)

P13) Determine the type of triangle (Scalene, Isosceles, Equilateral).

side1 = int(input("Enter the length of side 1: "))


side2 = int(input("Enter the length of side 2: "))
side3 = int(input("Enter the length of side 3: "))

if side1 == side2 == side3:


print("It is an equilateral triangle.")
elif side1 == side2 or side1 == side3 or side2 == side3:
print("It is an isosceles triangle.")
else:
print("It is a scalene triangle.")
P14) Determine the Grade based on the score.

score = float(input("Enter the student's score: "))

if 90 <= score <= 100:


print("Grade: A")
elif 80 <= score < 90:
print("Grade: B")
elif 70 <= score < 80:
print("Grade: C")
elif 60 <= score < 70:
print("Grade: D")
else:
print("Grade: F")

P15) Calculate the car rental price.

days_rented = int(input("Enter the number of days the car was rented: "))
daily_rate = float(input("Enter the daily rental rate: "))
is_damage = input("Is the car damaged upon return? (Y/N)")

if days_rented <= 0:
print("Invalid input. Number of days should be greater than 0.")
else:
total_cost = days_rented * daily_rate
print("Total cost of car rental:", total_cost)

if str.upper(is_damage) == 'Y':
print("There is damage in the car upon return")
adjusted_amount = total_cost + 0.25*total_cost
print("Adjusted amount: ",adjusted_amount)
else:
print("There is no further adjustment needed in the amount.")

Python Lists

Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
 List items are ordered, changeable, and allow duplicate values.

 List items are indexed, the first item has index [0], the second item has index [1] etc.

 When we say that lists are ordered, it means that the items have a defined order, and that order
will not change.

 If you add new items to a list, the new items will be placed at the end of the list.

To determine how many items a list has, use the len() function:

Print the number of items in the list:


thislist = ["apple", "banana", "cherry"]
print(len(thislist))
append(): The append() method is used to add a single element to the end of a list. It takes one
argument, which is the element you want to add to the list. The element is added as a single item at the
end of the list.
extend(): The extend() method is used to add multiple elements to the end of a list. It takes an iterable
(e.g., a list, tuple, or another iterable) as its argument and adds each element from the iterable to the end
of the list.
In Python, a nested list is a list that contains other lists as its elements. This allows you to create a multi-
dimensional data structure, where each element of the outer list is itself a list, and these inner lists can,
in turn, contain more lists, forming a nested structure.

Accessing a List
List items are indexed and you can access them by referring to the index number:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
This will print "banana".

Negative indexing means start from the end. -1 refers to the last item, -2 refers to the second last item
etc.

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


print(thislist[-1])

This will print "cherry".

You can specify a range of indexes by specifying where to start and where to end the range. When
specifying a range, the return value will be a new list with the specified items.
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "mango"]
print(thislist[2:5])

This will print "cherry", "orange", "kiwi".

Python For Loop

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a
string).

This is less like the for keyword in other programming languages, and works more like an iterator
method as found in other object-orientated programming languages.

With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.

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


for x in fruits:
print(x)
for x in "banana":
print(x)

With the break statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break

With the continue statement we can stop the current iteration of the loop, and continue with the next:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)

The range() Function


To loop through a set of code a specified number of times, we can use the range() function,

The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1
(by default), and ends at a specified number.
for x in range(6):
print(x)
range(6) is not the values of 0 to 6, but the values 0 to 5.

for x in range(2, 6):


print(x)

The range() function defaults to 0 as a starting value, however it is possible to specify the starting
value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):

for x in range(2, 30, 3):


print(x)

Increment the sequence with 3.

P16) Calculate the sum of digits of a number

number = int(input("Enter the number: \n"))


total = 0
temp_number = number

while temp_number > 0:


digit = temp_number % 10
total += digit
temp_number //= 10

print("Sum of digits of", number, "is:", total)

number = input("Enter the number: \n")


add = 0
for num in number:
add += int(num)

print("Sum of digits of", number, "is:", add)

P17) Find the common between two lists.

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

common_elements = []

for element in list1:


if element in list2:
common_elements.append(element)

print("Common elements:", common_elements)


P18) Fibbonacci Sequence

n = int(input("Enter the number of Fibonacci numbers to generate: "))

fibonacci = [0, 1]

if n == 0:
exit()

while len(fibonacci) < n:


next_number = fibonacci[-1] + fibonacci[-2]
fibonacci.append(next_number)

if n == 1:
print("Fibonacci sequence:", fibonacci[0])
else:
print("Fibonacci sequence:", fibonacci)

P19) Check if a number is prime


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

if number < 2:
print(number, "is not a prime number.")
else:
is_prime = True
for i in range(2, number):
if number % i == 0:
is_prime = False
break

if is_prime:
print(number, "is a prime number.")
else:
print(number, "is not a prime number.")

You might also like