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

Python Module-1 QB Solution (21EC643)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Python Module-1 QB Solution (21EC643)

Uploaded by

kgaddigoudar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

PYTHON PROGRAMMING

Module -1

1. List the features of python programming language (at least 6)


Features of python:
1. Python is free and open-source programming. The software can be downloaded and used
freely.
2. It high level programming language.
3. Easy Syntax: Python uses easy-to-read syntax and easy to learn.
4. Portable: It means python programs can be executed on various platforms without altering
them.
5. Interpreted: Python is an interpreted language, meaning that code is executed line by line.
6. It is an object oriented programming language
7. It can be embedded within your C or C++ programs.
8. It has very rich set libraries and library functions
9. It has very powerful built in data types.
10. Dynamic Typing: No need to declare the type of a variable explicitly. Python automatically
determines the data type during execution.
11. Dynamic Memory Management: Python automatically handles memory allocation and
deallocation.
12. Cross-Platform: Python is available on multiple platforms, including Windows, macOS, and
Linux.

2. List the rules to declare the variable in python. Demonstrate at least 3 types of variables
uses with an example program

Rules to declare the Variable names


• The keywords (reserved words) cannot be used for naming the variable.
• A variable name can only contain alphabets (lowercase and uppercase) and numbers,
but should not start with a number
• A variable name must start with a letter or the underscore character
• Variable names are case-sensitive (Sachin, sachin and SACHIN are three different
variables).
• No other special characters like @, $ etc. are allowed
Invalid Variable Names
2a=15 #starting with a number

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

SyntaxError: invalid syntax

x$=4 #contains $
SyntaxError: invalid syntax

if=10 # if is a keyword
SyntaxError: invalid syntax

3 types of variables uses with an example program


• Integer
• Float
• String

1. Integer
# An integer assignment
Roll_number = 45
print(“Roll number”, Roll_number)
type(Roll_number)

output
Roll number: 45
int

2. float
# A floating point
height = 5.8
print('height:', height)
type(height)

Output: height: 5.8


float

3. String
# A string
name = "Sachin Tendulkar"
print (‘name:’, name)
type(name)

Output:
name: Sachin Tendulkar
str

3. Explain the rules of precedence used by python to evaluate an expression.


Evaluate Expression: (5 - 1) * ((7 + 1) / (3 - 1))
• If an expression contains more than one operator, then order of evaluation depends on the
rules of precedence.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

• For mathematical operators, Python follows following order


1. Parentheses
2. Exponentiation
3. Multiplication & Division
4. Addition and Subtraction
The acronym PEMDAS is a used to remember rules:

• Parentheses: have the highest precedence in any expression. The operations within
parenthesis will be evaluated first.
Examples: 2 * (3-1) => Output= 4
(1+1)**(5-2) => Output= 8
The addition has to be done first and then the sum is multiplied with c

• Exponentiation: It has the 2nd precedence and Right to left Associative. That is, if there are
two exponentiation operations continuously, it will be evaluated from right to left
Examples: 2**1+1 => Output= 3
3*1**3 => Output= 3
2**3**2 => Output= 512

• Multiplication and division, modulus : The Multiplication and Division have same priority
& 3rd precedence and left-to-right associative. If there are two or more
Multiplication/Division operations continuously, then evaluated from left-to-right.
Examples: 2*3-1 => Output= 5
5-2*2 => Output= 1
5*2/4 => Output= 2.5
• Addition and Subtraction:
The Addition and Subtraction have same priority & 4th precedence (least priority) and left-
to-right associative.
Examples: 5-3-1 => Output= 1
5-2+2 => Output= 5
6-(3+2) => Output= 1

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Expression: (5 - 1) * ((7 + 1) / (3 - 1))

1. Step 1 - Evaluate Parentheses:


▪ Evaluate (5 - 1) = 4
▪ Evaluate (7 + 1)= 8
▪ Evaluate (3 - 1)= 2
o Now the expression is: 4 * (8 / 2)
2. Step 2 - Division:
▪ Evaluate 8 / 2 = 4
o Now the expression is: 4 * 4
3. Step 3 - Multiplication:
▪ Evaluate 4 * 4= 16

So, the final value of the expression (5 - 1) * ((7 + 1) / (3 - 1)) is 16.

4. Describe the Python functions int ( ), float ( ) and str ( ) with example
str():
This function Converts a value to string form.
Examples:
>>> str(0)
Output : '0'

>>> str(-3.14)
Output : '-3.14'

Using str() for Concatenation


To concatenate an integer with a string, convert the integer to a string using str().

>>> print('I am ' + str(29) + ' years old.')


Output : I am 29 years old.

int()
This function converts a value to its integer form.

Examples:
>>> int('42')
Output : 42

>>> int('-99')
Output : -99

>>> int(1.25)
Output: 1

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

>>> int(1.99)
Output: 1
float():
This function converts a value to its floating-point form.

Examples:
>>> float('3.14')
3.14

>>> float(10)
10.0

Practical Use of int() with input()


By default input() function returns a string.
So, first convert it to an integer or float to perform mathematical operations.

>>> spam = input()


Entered value : '101' #by default string
>>> spam = int(spam) # convert to integer
>>>print(spam)
101

Now Perform math operations with the converted integer:


>>> spam * 10 / 5
202.0

Handling Errors with int()


Converting non-integer strings to an integer causes an error.
>>> int('99.99')
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>

int('99.99')
ValueError: invalid literal for int() with base 10: '99.99'

>>> int('twelve')
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
int('twelve')
ValueError: invalid literal for int() with base 10: 'twelve'

Using int() to Round Down Floats


int() rounds down floating-point numbers.
>>> int(7.7)
7
>>> int(7.7) + 1
8

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Example Program :
print('What is your age?') # ask for their age
myAge = int (input())
print('You will be ' + str(myAge + 1) + ' in a year.')

Output
If the user enters: ‘4’
myAge : 4 #integer
myAge+1 = 5.
str(myAge+1) converts 5 to string '5'.
Final output: "You will be 5 in a year.

5. Write a python program to find the best of two test average marks out of 3 tests marks
accepted from the user

m1 = int (input("Enter the marks in the first test: "))


m2 = int (input("Enter the marks in second test: "))
m3 = int (input("Enter the marks in third test: "))

if (m1 >= m2) and (m2 >= m3):


total = m1 + m2

elif (m2 >= m3) and (m3 >= m1):


total = m2 + m3

else: (# This covers the case where m3 >= m1 and m1 >= m2)
total = m1 + m3

Avg = total / 2
print ("The average of the best two test marks is: ",Avg)

Output :
Enter the marks in the first test: 20
Enter the marks in the second test: 15
Enter the marks in the third test: 22
The average of the best two test marks is: 21.0

6. How python handles the exception? Explain with an example program


Exception:
• When a Python script encounters a situation which it cannot handle, it raises an exception.
In python, an exception represents an error.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

• Errors that occur at runtime (after passing the syntax test) are called exceptions
Handling an exception
Python can handle exceptions using try & except statements
• try block: If the code is suspicious or prone to runtime error, then put this code within the try
block.
• except block: Put the remedy code or information about what may go wrong and what is the
way to come of it.
• During the execution, first try block will be executed, if something goes wrong within try
block, then except block will be executed. Otherwise, the except-block will be skipped.

Example 1:
• For example, consider the following code segment
a=int(input("Enter value for a:"))
b=int(input("Enter the value for b:"))
c=a/b
print(c)
• Let us run the above code, and see output
Output :
Enter value for a:5
Enter the value for b:0
--------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
ZeroDivisionError: division by zero

• Here because of the wrong input, during runtime, error has occurred and error message is
generated, but for the user, it is difficult to understand the such type of system-generated error
messages and handle the errors.
• By using try and except statements, we can display our own messages or solution to the user so
that problem can be handled or solved easily.

Consider the example


a=int(input("Enter value for a:"))
b=int(input("Enter the value for b:"))
try:
c=a/b
print(c)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

except:
print ("Division by zero is not possible, enter non zero value for b")

Output:
Enter value for a:5
Enter the value for b:0
Division by zero is not possible, enter non zero value for b

7. Write a single user defined function named “solve” that returns remainder and quotient
on division of two numbers accepted from the user. Print remainder and quotient
separately on the console

def solve(a,b):
rem=a%b
div=a/b
return[rem, div] #if multiple values to be returned use []

num1=int(input(‘Enter the first value:’))


num2=int(input(‘Enter the first value:’))
s=solve(num1, num2) #function call
print('Remainder :', s[0], '\n', 'Division=',s[1])

Output
Enter the first value: 5
Enter the first value: 2

Remainder = 1
Division= 2.5

8. Predict the output and justify your answer

i. (200-70)*10/5
ii. not “false” = False
iii. 5*1**2 = 5
iv. 2**1+1=3

i. (200-70)*10/5 = 260
Justification:
• First parenthesis, so (200-70)= 130.
• The Multiplication and Division have same priority & so evaluated from left-to-right.
• So, then 130*10 = 1300, and finally 1300/5 = 260.0.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

iii. not “false” = False


Justification:
The not operator in Python returns the opposite of a Boolean value.
In case of string, if string is non-empty=> True,
if string is empty=> False.
In this given case, string is not empty, so it is True. Then, opposite of True is False

iv. 5*1**2 = 5

Justification:
This expression has * (multiplication) & ** (exponentiation) operators.
The ** has higher precedence than the operator * .
Therefore, the exponentiation expression is evaluated first; 1**2 =1. Then, multiplication
operation is performed; 5*1=5.

v. 2**1+1=3

9. List and explain the different comparison and Boolean operators, along with examples
Comparison operators
• Comparison operators return Boolean values by comparing two values.
• Essential for making decisions in flow control statements (if, while).
• Used widely beyond flow control, such as in loops and conditions.

Operator Description Notations Example


Equal to 42==42
== True if a is equal to b a == b Output: True
False otherwise
!= Not equal to a != b 42 != 43
True if a is not equal to b Output: True
False otherwise
< Less than a < b 42 < 43
True if a is less than b Output: True
False otherwise
<= Less than or equal to 42 < =43
True if a is less than or equal to b a <= b Output: False
False otherwise
> Greater than a > b 43 > 42
True if a is greater than b Output: True
False otherwise
>= Greater than or equal to 43 > =42
True if a is greater than or equal to b; a >= b Output: True
False otherwise

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Boolean Operators
• The three Boolean operators (and, or, and not) are used to compare Boolean values.
• Used in conditional statements (if, elif, else), loops (while, for), and other decision-
making contexts.

Operator Description Notation Example Result


Not Logically reverses the sense of x not x not (4 > 5) True
Or True if either x or y is True x or y (4 > 5) or (5 > 4) True
False otherwise
And True if both x and y are True x and y (4 < 5) and (5 < 6) True
False otherwise

Mixing Boolean and Comparison Operators


Expression Description Result

(4 < 5) and (5 < 6) Both are True, so the result is True TRUE

(4 < 5) and (9 < 6) First is True, second is False, so the FALSE


result is False

(1 == 2) or (2 == 2) First is False, Second is True, so the TRUE


result is True

2 + 2 == 4 and not 2 + 2 == 5 and 2 * 2 == 2 + 2 Evaluates math first, then comparison, TRUE


then not, then and: (4 == 4) and not (4
== 5) and (4 == 4)

10. Explain while and for loops with examples in python


While loop
while loop is used to repeat block of code till condition is true/met. This is condition-
controlled loop.
The while loop iterates till the condition is met and hence, the number of iterations are
usually unknown prior to the loop. Hence, it is sometimes called as indefinite loop
Syntax of the while loop

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Example 1: Write program to Print “Hi how are you” 10 times


count = 0
while count <= 10:
print(“Hi, how are you”)
count = count +1
Explain this example in your own words

Example 2: Write program to Print first 5 natural numbers using while loop
count = 1
while count <= 5:
print(count)
count = count +1
Output:
1
2
3
Explain this example in your own words

for loop
• for loops are used to repeat the block of code for fixed number of times. This is count
controlled loop.
• In case of for loop, we know number of times the block of code to be executed or repeated
in prior, so this is called as a definite loop. But in case of while loop, it repeats, until some
condition becomes False, so it is called as indefinite loop
• The for-loop is always used in combination with an iterable object, like range or sequence
(that is either a list, a tuple, a dictionary, a set, or a string).

Syntax:

Here for and in are keywords.

Examples
Example1:
for loop using range function
for i in range(1, 6):

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

print(i)

Output:
1
2
3
4
5

Explain this example in your own words

Example2
Iterating over a list
seq= [2,5,8,18,10] #List is created with name seq
for i in seq:
print(i)
Output:
2
5
8
18
10

11. Write a python program to demonstrate the counting, summing, and average of n
natural numbers using loops

n=int(input('Enter the number :'))

i=0
sum=0
while i<n:
sum=sum+i
i=i+1

average = sum/n
print('Sum of n numbers is :' , sum)
print('Average of n numbers is :', average)
print('Count is :', i)

Output :
Enter the number : 5
Sum of n numbers is : 10
Average of n numbers is : 2.0
Count is : 5

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

12.Explain the local and global scope of the variable with a suitable example.

Scope refers to the area of code where a variable is accessible. In Python, there are two main types
of scopes: global scope and local scope.

• Global Scope: Variables defined outside of any function have global scope. They can be
accessed from anywhere within the program.
• Local Scope: Variables defined inside a function have local scope. They are only accessible
within that function.

# Global Scope Example


global_var = 10 # This variable has global scope

def func():
print("Inside func():", global_var) # Accessing global_var

func() # Output: Inside func(): 10


print("Outside func():", global_var) # Accessing global_var outside the function
Output: Outside func(): 10

# Local Scope Example


def func():
local_var = 20 # This variable has local scope and is accessible only inside func()
print("Inside func():", local_var)

func() # Output: Inside func(): 20


print(local_var) # This will cause an error as local_var is not accessible outside func()

In the example above:

• global_var is defined outside any function, making it globally accessible.


• local_var is defined inside the func() function, making it accessible only within that
function. Trying to access it outside func() will result in an error.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

13. List and give syntax of all python supported conditional statements (if, if else, if elif )
along with its usage with an example program to check whether given number is positive
or negative or zero

• Conditional statements are also called decision-making statements. We use these statements,
when we want to execute a block of code, only if the given condition is met (true or false).
1. if statements
2. Alternative Execution (if else)
3. Chained Conditionals: if elif else
4. Nested Conditionals

if statements

• The boolean expression in the if header is called the condition.


• Header of if statement ends with a colon character (:) and then set (block) of statements after
the if-header statement are indented.
• If the logical condition is true, then the indented statements get executed. If the logical
condition is false, the indented statement is skipped
Example 1
age=int(input(“Enter your age”)
if age>= 18: #colon at the end of if header
print(“Eligible for voting”) #Indentation (part of if block)

• There is no limit for, the number of statements in the if body, but there must be at least one.

Alternative Execution (if else)


• A second form of the if statement is alternative execution (if else), in which there are two
possibilities

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

• Here, when the condition is true, one set of statements will be executed and when the
condition is false, another set of statements will be executed.
• The syntax and flowchart are as given below

• Example: Program to Find If a Given Number Is Odd or Even


num = int(input("Enter a number"))
if num % 2 == 0:
print(num, “is Even number")
else:
print(num, “is Odd number")

Chained Conditionals: if elif else


• In some situations, more than one possibility has to be checked to execute executing a set of
statements.
• That means, we may have more than one branch. This is solved with the help of chained
conditionals.

Example: Program to check whether the given number is positive or negative


num = int(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num == 0:
print("Number is Zero")

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

else:
print("Negative number")

Nested Conditionals
• One conditional statement can be nested within another conditional statement.
Example
gender=input("Enter gender:")
age=int(input("Enter age:"))
if gender ==’M’
if age >= 21:
print("Boy, Eligible for Marriage")
else:
print("Boy, Not Eligible for Marriage")
elif gender == "F" :
if age >= 18:
print("Girl, Eligible for Marriage")
else:
print("Girl, Not Eligible for Marriage")

12. Write python programs using function


a. Find the largest of 3 numbers
b. Check the given year is leap year or not with functions
largest of 3 numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

if (num1 >= num2) and (num1 >= num3):


largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3

print("The largest number is", largest)

Using function
def largest(num1, num2, num3):
if (num1 >= num2) and (num1 >= num3):
return num1

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

elif (num2 >= num1) and (num2 >= num3):


return num2
else:
return num3

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

# Call the function and print the result


largest_number = largest(num1, num2, num3)
print("The largest number is", largest_number)

Given year is leap year or not using used defined functions


def leap(year): #function definition
if (year % 400 == 0) and (year % 100 == 0):
print("Leap year”)
elif (year % 4 ==0) and (year % 100 != 0):
print(“Leap year”)
else:
print("Not leap year”)

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


leap(year) #function call

13. Illustrate the flow of execution of python user define function with an example program
to convert given Celsius to Fahrenheit temperature

def convert(c):
F = (9/5)*c + 32
return (F)

cel = float(input("Enter temperature in celsius: "))


fah = convert(cel)
print ("The temperature in Fahrenheit is ", fah)

explain in your own words

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

14. Write a python program to calculate the area of square, rectangle and circle. Take the
input from user

op = input(" Area to be out, choose : square or rectangle or circle :)


if op == "square":
side = int(input("Enter side of the square: "))
area = side* side
print(“Area of square is”, area)
elif op == "rectangle":
length = int(input("Enter length of the rectangle: "))
breadth = int(input(" Enter breadth of the rectangle:"))
area = int(length) * int(breadth)
print(Area of rectangle is”, area)
elif op == "circle":
r = int(input("radius of the circle: "))
area = 3.14 * r * r
print(“Area of circle is”, area)

15. Mention the uses of continue statement. Write program to compute only even numbers
sum within the given natural number using continue statement.

Use of continue statement


Python continue statement is used to skip or reject next the set of statements as per the external
condition. And control moves to the beginning of the loop.
Program: To find the sum of first “n” natural even numbers using continue statement
n=int(input("Enter the value of n:"))
sum=0
i=0
while i<n:
i=i+1
if i%2!=0:
continue
sum=sum+i
print(sum)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

16. With syntax explain the finite and infinite looping constructs in python. What is the need
for break and continue statements?

Finite loop:
Example :
Write program to Print even numbers from 0 to 10 using while loop.
i=0
while i <= 10:
print(i)
i = i +2

Here loop terminates once the condition is met, ie after finite number of iterations.

Infinite Loop:

• Infinite Loop is loop, in which condition never becomes false, hence block of code will be
executed infinite number of times.
• Example 1
n = 10
while True:
print(n)
n = n -1
Here, in this example, the condition specified is the constant value True, so all the time it
is true, no way to make it false, so once it gets into loop, it will never get terminated.

While, break
• In case of infinite loop, we can use the break statement to jump out of the loop.
• The break statement terminates the current loop and passes the control to the next statement,
which is immediately after the body of loop

• Example: Let us consider above infinite loop using break statement


n = 10

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

while True:
print(n)
n = n -1
if n= =5:
break

Here break statement is placed within loop, after the if statement & break statement
provides chance to exit the loop, when external condition is generated.

while, continue
• The continue statement in returns the control to the beginning of the while loop.
• The continue statement rejects or skips all the remaining statements in the current loop and
moves the control back to the top of the loop.

Example: Program to generate the natural numbers from 1 to 5 except 3


Hint : Skip the iteration if the variable i is 3, but continue with the next iteration

i=0
while i<=5
i=i+1
if i == 3:
continue
print(i)

17. What is the user defined function? How we pass parameters in user defined functions,
explain with program?

User defend function: set of statements to perform specific task, is known as user defined
function.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Example:
def fun_add(x, y): # x and y are parameters
z=x+y
return z

num 1= int(input("Enter first number: "))


num2= int(input("Enter second number: "))
s= fun_add(num1, num2) # function call, here num1 and num2 are arguments
print("The sum of 2 numbers is : ", s)
Output:
Enter first number: 5
Enter second number: 6
The sum of 2 numbers is: 11

• In the above example, the function fun_add () takes two arguments and returns the result to
the calling function. Here returned value to calling function is stored in the variable s.
• When a function returns something and if it is not stored using the variable, then the return
value will vanish and not be available for the future use.
• Here in case, if we just use the statement fun_add(num1, num2) instead of
s= fun_add(num1, num2), then the value returned from the function is of no use.

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

19. Write python program to calculate the labour Pay from the hours and rate. The values of hour and
rate have to be taken from user.
(Hint: pay= hour*rate).

Rewrite the above program using try and except, so that your program handles nonnumeric input
gracefully by printing a message and exiting the program. The following shows two executions of the
program
Enter Hours: 20
Enter rate: nine
Error, please enter the numeric input
Enter Hours: forty
Error, please enter the numeric input

Normal program
hour=int(input("Enter Hours:"))
rate=int(input("Enter Rate:"))
pay = hours *rate
print("Pay:", pay)

Using try and except

try:
hour=int(input("Enter Hours:"))
rate=int(input("Enter Rate:"))
pay = hours *rate
print("Pay:", pay)

except:
print("Error, Error, please enter the numeric input”)
exit()

20. Explain the break and continue statements using examples.


Break statement
The break statement terminates the current loop and control jumps out of the current loop. The
control moves to the next statement, which is immediately after the body of loop

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Example: Let us consider above infinite loop using break statement


n = 10
while True:
print(n)
n = n -1
if n= =5:
break

Example:
n=1
while n>0:
print(n)
n = n +1
if n==8:
break

Note ; explain in your own words


Continue statement
• The continue statement in Python returns the control to the beginning of the while loop.
• The continue statement rejects or skips all the remaining statements in the current loop and
moves the control back to the top of the loop.

Example: Program to generate the natural numbers from 1 to 5 except 3


Hint : Skip the iteration if the variable i is 3, but continue with the next iteration

i=0
while i<=5
i=i+1
if i == 3:
continue
print(i)

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

Write a program to find the factorial of a number using a function .


def fact(n):
result = 1
for i in range(1, n + 1):
result=result * i
return result

num = int(input(“Enter the value: “);


result = fact(num) #function call
print("The factorial of number is”, result)

21. Write a program to print the Fibonacci series

# Program to display the Fibonacci sequence up to n-th term


nterms = int(input("How many terms? "))

# first two terms


n1, n2 = 0, 1
count = 0

# if there is only one term, return n1


if nterms == 1:
print("Fibonacci sequence :", n1)

# generate fibonacci sequence


else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1

Prof. Sujay Gejji ECE, SGBIT, Belagavi


PYTHON PROGRAMMING

22. Write the python program to generate and print prime numbers from numbers between
2 to 50

Python program to display all the prime numbers within an interval

lower = 2
upper = 50

print("Prime numbers :")

for num in range(lower, upper + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)

Prof. Sujay Gejji ECE, SGBIT, Belagavi

You might also like