0% found this document useful (0 votes)
9 views13 pages

Python Unit2 Notess

Uploaded by

Tanya Singh
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)
9 views13 pages

Python Unit2 Notess

Uploaded by

Tanya Singh
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/ 13

Loops and Conditional Statements in Python

In Python, loops and conditional statements are fundamental concepts that allow for the
execution of code based on certain conditions and the repetition of code blocks. This note
will cover the various types of loops, how to use them with lists and dictionaries, and the use
of conditional statements.

Types of Loops

There are two primary types of loops in Python:

 While Loop: Executes a block of code as long as a specified condition is true.


 For Loop: Iterates over a sequence (like a list, tuple, or string) and executes a block
of code for each item in the sequence.

While Loop

The while loop continues to execute as long as the condition remains true. Here is a simple
example:

count = 0
while count < 5:
print(count)
count += 1

For Loop

The for loop is used to iterate over a sequence. Here’s an example:

for i in range(5):
print(i)

For Loop with String List and Dictionary

For loops can also be used to iterate over lists and dictionaries. Here are examples for both:

Iterating Over a List

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


for fruit in fruits:
print(fruit)

Iterating Over a Dictionary

person = {'name': 'John', 'age': 30, 'city': 'New York'}


for key, value in person.items():
print(key, value)

Conditional Statements
Conditional statements allow you to execute certain blocks of code based on conditions. The
main types are:

 If Statement: Executes a block of code if the condition is true.


 Else Statement: Executes a block of code if the condition is false.
 Elif Statement: Checks multiple expressions for truth and executes a block of code as
soon as one of the conditions is true.

Example of Conditional Statements

age = 20
if age < 18:
print("You are a minor.")
elif age >= 18 and age < 65:
print("You are an adult.")
else:
print("You are a senior.")

Using Break, Continue, and Pass

Python provides control statements that can alter the flow of loops:

 Break: Exits the loop prematurely.


 Continue: Skips the current iteration and moves to the next one.
 Pass: A null operation; it is a placeholder that does nothing when executed.

Examples

Here are examples of each control statement:

# Break example
for i in range(10):
if i == 5:
break
print(i)# Continue example
for i in range(10):
if i % 2 == 0:
continue
print(i)# Pass example
for i in range(5):
if i < 3:
pass # Do nothing
else:
print(i)

Q--Write a Python program to find those numbers which are divisible by 7


and multiples of 5, between 1500 and 2700 (both included).

# Create an empty list to store numbers that meet the given


conditions
nl = []

# Iterate through numbers from 1500 to 2700 (inclusive)


for x in range(1500, 2701):
# Check if the number is divisible by 7 and 5 without any
remainder
if (x % 7 == 0) and (x % 5 == 0):
# If the conditions are met, convert the number to a
string and append it to the list
nl.append(str(x))

# Join the numbers in the list with a comma and print the
result
Aprint(','.join(nl))

Q>-
Write a Python program to convert temperatures to and from Celsius
and Fahrenheit.
[ Formula : c/5 = f-32/9 [ where c = temperature in celsius and f =
temperature in fahrenheit ]
Expected Output :
°C is 140 in Fahrenheit
45°F is 7 in Celsius

Solution-
# Prompt the user to input a temperature in the
format (e.g., 45F, 102C, etc.)
temp = input("Input the temperature you like to convert?
(e.g., 45F, 102C etc.) : ")

# Extract the numerical part of the temperature and convert it


to an integer
degree = int(temp[:-1])

# Extract the convention part of the temperature input (either


'C' or 'F')
i_convention = temp[-1]

# Check if the input convention is in uppercase 'C' (Celsius)


if i_convention.upper() == "C":
# Convert the Celsius temperature to Fahrenheit
result = int(round((9 * degree) / 5 + 32))
o_convention = "Fahrenheit" # Set the output convention
as Fahrenheit
# Check if the input convention is in uppercase 'F'
(Fahrenheit)
elif i_convention.upper() == "F":
# Convert the Fahrenheit temperature to Celsius
result = int(round((degree - 32) * 5 / 9))
o_convention = "Celsius" # Set the output convention as
Celsius
else:
# If the input convention is neither 'C' nor 'F', print an
error message and exit the program
print("Input proper convention.")
quit()

# Display the converted temperature in the specified output


convention
print("The temperature in", o_convention, "is", result,
"degrees.")

Q-Write a Python program to construct the following pattern, using a nested for
loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

Solution-# Set the value of 'n' to 5 (this will determine the


number of lines in the pattern)
n = 5

# Iterate through the range of numbers from 0 to 'n'


(exclusive)
for i in range(n):
# Iterate through the range of numbers from 0 to 'i'
(exclusive) for each 'i' in the outer loop
for j in range(i):
# Print '*' followed by a space without a new line
(end="" ensures printing in the same line)
print('* ', end="")
# Move to the next line after printing '*' characters for
the current 'i'
print('')

# Iterate through the range of numbers from 'n' down to 1


(inclusive), decreasing by 1 in each iteration
for i in range(n, 0, -1):
# Iterate through the range of numbers from 0 to 'i'
(exclusive) for each 'i' in the outer loop
for j in range(i):
# Print '*' followed by a space without a new line
(end="" ensures printing in the same line)
print('* ', end="")
# Move to the next line after printing '*' characters for
the current 'i'
print('')

Q-> Write a Python program to count the number of even and odd numbers in
a series of numbers
Sample numbers : numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Expected Output :
Number of even numbers : 5
Number of odd numbers : 4

# Create a tuple named 'numbers' containing integer values


from 1 to 9
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)

# Initialize counters for counting odd and even numbers


count_odd = 0
count_even = 0

# Iterate through each element 'x' in the tuple 'numbers'


for x in numbers:
# Check if the current number 'x' is even by evaluating
'not x % 2'
if not x % 2: # If 'x' modulo 2 equals 0, it's even
# Increment the count of even numbers
count_even += 1
else:
# If 'x' modulo 2 doesn't equal 0, it's odd; increment
the count of odd numbers
count_odd += 1

# Print the total count of even and odd numbers


print("Number of even numbers:", count_even)
print("Number of odd numbers:", count_odd)

Q-> Write a Python program that prints all the numbers from 0 to 6 except 3
and 6.
Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5

# Iterate through numbers from 0 to 5 using the range function


for x in range(6):
# Check if the current value of 'x' is equal to 3 or 6
if (x == 3 or x == 6):
# If 'x' is 3 or 6, skip to the next iteration without
executing the code below
continue
# Print the value of 'x' with a space and without a
newline (end=' ')
print(x, end=' ')

# Print a new line after printing all numbers satisfying the


condition
print("\n")

Q->. Write a Python program to get the Fibonacci series between 0 and 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
Every next number is found by adding up the two numbers before it.
Expected Output : 1 1 2 3 5 8 13 21 34

# Initialize variables 'x' and 'y' with values 0 and 1, respectively


x, y = 0, 1

# Execute the while loop until the value of 'y' becomes greater than or equal to
50
while y < 50:
# Print the current value of 'y'
print(y)

# Update the values of 'x' and 'y' using simultaneous assignment,


# where 'x' becomes the previous value of 'y' and 'y' becomes the sum of 'x'
and the previous value of 'y'
x, y = y, x + y

Q->. Write a Python program that accepts a sequence of comma separated 4


digit binary numbers as its input. The program will print the numbers that are
divisible by 5 in a comma separated sequence.
Sample Data : 0100,0011,1010,1001,1100,1001
Expected Output : 1010

# Create an empty list named 'items'


items = []

# Take user input and split it into a list of strings using ',' as the delimiter
num = [x for x in input().split(',')]

# Iterate through each element 'p' in the 'num' list


for p in num:
# Convert the binary string 'p' to its decimal equivalent 'x'
x = int(p, 2)

# Check if 'x' is divisible by 5 (i.e., when divided by 5 there's no remainder)


if not x % 5:
# If 'x' is divisible by 5, add the binary string 'p' to the 'items' list
items.append(p)

# Join the elements in the 'items' list separated by ',' and print the result
print(','.join(items))

Q-> Write a Python program that accepts a string and calculates the number
of digits and letters.
Sample Data : Python 3.2
Expected Output :
Letters 6
Digits 2

Solution- # Prompt the user to input a string and store it in the variable 's'
s = input("Input a string")

# Initialize variables 'd' (for counting digits) and 'l' (for counting letters) with
values 0
d=l=0

# Iterate through each character 'c' in the input string 's'


for c in s:
# Check if the current character 'c' is a digit
if c.isdigit():
# If 'c' is a digit, increment the count of digits ('d')
d=d+1
# Check if the current character 'c' is an alphabet letter
elif c.isalpha():
# If 'c' is an alphabet letter, increment the count of letters ('l')
l=l+1
else:
# If 'c' is neither a digit nor an alphabet letter, do nothing ('pass')
pass

# Print the total count of letters ('l') and digits ('d') in the input string 's'
print("Letters", l)
print("Digits", d)

Q->. Write a Python program to check the validity of passwords input by


users.
Validation :

 At least 1 letter between [a-z] and 1 letter between [A-Z].

 At least 1 number between [0-9].

 At least 1 character from [$#@].

 Minimum length 6 characters.

 Maximum length 16 characters.

# Import the 're' module for regular expressions


import re
# Prompt the user to input a password and store it in the variable 'p'
p = input("Input your password")

# Set 'x' to True to enter the while loop


x = True

# Start a while loop that continues until 'x' is True


while x:
# Check conditions for a valid password:
# Password length should be between 6 and 12 characters
if (len(p) < 6 or len(p) > 12):
break
# Password should contain at least one lowercase letter
elif not re.search("[a-z]", p):
break
# Password should contain at least one digit
elif not re.search("[0-9]", p):
break
# Password should contain at least one uppercase letter
elif not re.search("[A-Z]", p):
break
# Password should contain at least one special character among '$', '#', '@'
elif not re.search("[$#@]", p):
break
# Password should not contain any whitespace character
elif re.search("\s", p):
break
else:
# If all conditions are met, print "Valid Password" and set 'x' to False to
exit the loop
print("Valid Password")
x = False
break

# If 'x' remains True, print "Not a Valid Password"


if x:
print("Not a Valid Password")

Q->Write a Python program to print the alphabet pattern 'A'.


Expected Output:
***
* *
* *
*****
* *
* *
* *

# Initialize an empty string named 'result_str'


result_str = ""
# Iterate through rows from 0 to 6 using the range function
for row in range(0, 7):
# Iterate through columns from 0 to 6 using the range function
for column in range(0, 7):
# Check conditions to determine whether to place '*' or ' ' in the result
string

# If conditions are met, place '*' in specific positions based on row and
column values
if (((column == 1 or column == 5) and row != 0) or ((row == 0 or row == 3)
and (column > 1 and column < 5))):
result_str = result_str + "*" # Append '*' to the 'result_str'
else:
result_str = result_str + " " # Append space (' ') to the 'result_str'

result_str = result_str + "\n" # Add a newline character after each row in


'result_str'

# Print the final 'result_str' containing the pattern


print(result_str)

Q->. Write a Python program to print the alphabet pattern 'L'.


Expected Output:
*
*
*
*
*
*
*****

# Initialize an empty string named 'result_str'


result_str = ""

# Iterate through rows from 0 to 6 using the range function


for row in range(0, 7):
# Iterate through columns from 0 to 6 using the range function
for column in range(0, 7):
# Check conditions to determine whether to place '*' or ' ' in the result
string

# If conditions are met, place '*' in specific positions based on row and
column values
if (column == 1 or (row == 6 and column != 0 and column < 6)):
result_str = result_str + "*" # Append '*' to the 'result_str'
else:
result_str = result_str + " " # Append space (' ') to the 'result_str'

result_str = result_str + "\n" # Add a newline character after each row in


'result_str'

# Print the final 'result_str' containing the pattern


print(result_str)

Q-> Write a Python program that reads two integers representing a month and
day and prints the season for that month and day.
Expected Output:
Input the month (e.g. January, February etc.): july
Input the day: 31
Season is autumn

# Request input from the user for the name of the month and assign it to the
variable 'month'
month = input("Input the month (e.g. January, February etc.): ")

# Request input from the user for the day and convert it to an integer,
assigning it to the variable 'day'
day = int(input("Input the day: "))

# Check the input 'month' to determine the season based on the month and
day provided

# Check if the input month falls within the winter season


if month in ('January', 'February', 'March'):
season = 'winter'
# Check if the input month falls within the spring season
elif month in ('April', 'May', 'June'):
season = 'spring'
# Check if the input month falls within the summer season
elif month in ('July', 'August', 'September'):
season = 'summer'
# For other months, assign the season as autumn by default
else:
season = 'autumn'

# Adjust the season based on the specific day within certain months

# Check if the input month is March and the day is after March 19, updating
the season to spring
if (month == 'March') and (day > 19):
season = 'spring'
# Check if the input month is June and the day is after June 20, updating the
season to summer
elif (month == 'June') and (day > 20):
season = 'summer'
# Check if the input month is September and the day is after September 21,
updating the season to autumn
elif (month == 'September') and (day > 21):
season = 'autumn'
# Check if the input month is December and the day is after December 20,
updating the season to winter
elif (month == 'December') and (day > 20):
season = 'winter'

# Display the determined season based on the provided month and day
print("Season is", season)

Q->Write a Python program to create the multiplication table (from 1 to 10) of


a number.
Expected Output:
Input a number: 6
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60

# Prompt the user to input a number and convert it to an integer, assigning it


to the variable 'n'
n = int(input("Input a number: "))

# Use a for loop to iterate 10 times, starting from 1 up to 10 (excluding 11)


for i in range(1, 11):
# Print the multiplication table for the entered number 'n' by multiplying it
with each iteration 'i'
print(n, 'x', i, '=', n * i)

You might also like