100% found this document useful (1 vote)
89 views

Tinywow - PYTHON PROGRAMS - 9391724

The document contains examples of Python programs that perform various tasks related to lists, strings, numbers, and logic. Some examples include: 1. Accepting user input and performing comparisons on numbers to find the largest/smallest. 2. Using loops and conditional logic to generate patterns of characters and numbers. 3. Performing calculations on series and using functions to find greatest common divisor, least common multiple, etc. 4. Applying string methods to check for palindromes, count characters, and convert case. 5. Accepting a list as input and demonstrating ways to find maximum/minimum, swap elements, search for a value.

Uploaded by

Anant Verma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
89 views

Tinywow - PYTHON PROGRAMS - 9391724

The document contains examples of Python programs that perform various tasks related to lists, strings, numbers, and logic. Some examples include: 1. Accepting user input and performing comparisons on numbers to find the largest/smallest. 2. Using loops and conditional logic to generate patterns of characters and numbers. 3. Performing calculations on series and using functions to find greatest common divisor, least common multiple, etc. 4. Applying string methods to check for palindromes, count characters, and convert case. 5. Accepting a list as input and demonstrating ways to find maximum/minimum, swap elements, search for a value.

Uploaded by

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

PYTHON PROGRAMS

1. Input a welcome message and display it.

message=input("Enter welcome message : ")


print("Hello, ",message)

output:- Enter welcome message : Good morning

Hello , Good morning

2. Input two numbers and display the larger /


smaller number.
#input first number
num1=int(input("Enter First Number"))
#input Second number
num2=int(input("Enter Second Number"))
#Check if first number is greater than second
if (num1>num2):
print("The Larger number is", num1)
else:
print ("The Larger number is", num2)

Output :- Enter First Number23


Enter Second Number35
The Larger number is 35
3. Input three numbers and display the largest /
smallest number.

number1 = int(input('Enter First number : '))


number2 = int(input('Enter Second number : '))
number3 = int(input('Enter Third number : '))

def largest(num1, num2, num3):


if (num1 > num2) and (num1 > num3):
largest_num = num1
elif (num2 > num1) and (num2 > num3):
largest_num = num2
else:
largest_num = num3
print("The largest of the 3 numbers is : ",
largest_num

def smallest(num1, num2, num3):


if (num1 < num2) and (num1 < num3):
smallest_num = num1
elif (num2 < num1) and (num2 < num3):
smallest_num = num2
else:
smallest_num = num3
print("The smallest of the 3 numbers is : ",
smallest_num)

largest(number1, number2, number3)


smallest(number1, number2, number3)

output :-
Enter First number : 25
Enter Second number : 87
Enter Third number : 40
The largest of the 3 numbers ‘is : 87
The smallest of the 3 numbers ‘is : 25

4. Generate the following Patterns using nested


loop in Python.

Pattern 1 :-

# Function to demonstrate printing pattern


def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(0, n):
# inner loop to handle number of
columns
# values changing acc. to outer loop
for j in range(0, i+1):
# printing stars
print("* ",end="")
# ending line after each row
print("\r")
# Driver Code
n = 5
pypart(n)
Pattern 2 :-
# Function to demonstrate printing pattern
Def pypart(n):
# outer loop to handle number of rows
# n in this case
for i in range(n+1,1,-1):
y=i
t=0
# inner loop to handle number of columns
# values changing acc. to outer loop
for j in range(2,y+1,1):
t=t+1
# printing pattern
print(t,end="")
# ending line after each row
print("\r")

n = int(input ("Enter the n.o where patterns


begin"))
pypart(n)
Pattern 3 :-

for i in range(1,6):
for j in range(65,65+i):
a = chr(j)
print(a, end=" ")
print("\r")
5. Generate the following patterns using nested
loop.

Pattern 1 :-
x = float (input ("Enter value of x :"))
n = int (input ("Enter value of n :"))
s = 0

for a in range (n + 1) :
if a%==0
s+= x**a
else
s-= x**a
print ("Sum of series", s)
Pattern 2 :-
x = float (input ("Enter value of x :"))
n = int (input ("Enter value of n :"))
s = 0

for a in range (n + 1) :
if a%2==0:
s+= x**a
else:
s -= x**a
print ("Sum of series", s)

Pattern 3 :-
x = float (input ("Enter value of x :"))
n = int (input ("Enter value of n :"))
s = 0

for a in range (n + 1) :
if a%2==0:
s += x**a
else:
s -= x**a
print ("Sum of series", s)
Pattern 4 :-

x = float (input ("Enter value of x :"))


n = int (input ("Enter value of n :"))
s = 0
a=1
fact=1
for a in range (1,n + 1) :
fact=fact*a
if a%2==0:
s += (x**a)/fact
else:
s -= (x**a)/fact
print ("Sum of series", s)
6. Determine whether a number is a perfect
number, an armstrong number or a palindrome.

def palindrome(n):
temp = n
rev = 0
while n > 0:
dig = n % 10
rev = rev * 10 + dig
n = n // 10
if temp == rev:
print(temp, "The number is a palindrome!")
else:
print(temp, "The number isn't a palindrome!")

def armstrong(n):
count = 0
temp = n
while temp > 0:
digit = temp % 10
count += digit ** 3
temp //= 10
if n == count:
print(n, "is an Armstrong number")
else:
print(n, "is not an Armstrong number")

def perfect(n):
count = 0
for i in range(1, n):
if n % i == 0:
count = count + i
if count == n:
print(n, "The number is a Perfect number!")
else:
print(n, "The number is not a Perfect
number!")

if __name__ == '__main__':
n = int(input("Enter number:"))
palindrome(n)
armstrong(n)
Output:-
7. Input a number and check if the number is a
prime or composite number.

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

if num > 1:

for i in range(2, num):

if (num % i) == 0:

print(num, "is NOT a prime number")

break

else:

print(num, "is a PRIME number")

elif num == 0 or 1:

print(num, "is a neither prime NOR composite


number")

else:

print(num, "is NOT a prime number it is a


COMPOSITE number")

output :-
Enter any number : 1
1 is a neither prime nor composite number
8. Display the terms of a 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

# check if the number of terms is valid


if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
output :- How many terms? 7
Fibonacci sequence
0,1,1,2,3,5,8
9. Compute the greatest common divisor and least
common multiple of two integers.

num1 = int(input('Enter your first number: '))


num2 = int(input('Enter your second number: '))
def compute_lcm(x, y):

# choose the greater number


if x > y:
greater = x
else:
greater = y

while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
break
greater += 1

return lcm
print("The L.C.M. is", compute_lcm(num1, num2))

Output :-
Enter 1st: number: 3
Enter 2nd number: 5

('Greatest Common Divisor (GCD) is ', 1)


('The Least Common Hultiple (LCM) is ', 15)
10. Count and display the number of vowels,
consonants, uppercase, lowercase characters in
string.

// Program to count vowels, consonant, digits and


// special character in a given string.
#include <bits/stdc++.h>
using namespace std;

// Function to count number of vowels, consonant,


// digitsand special character in a string.
void countCharacterType(string str)
{
// Declare the variable vowels, consonant,
digit
// and special characters
int vowels = 0, consonant = 0, specialChar =
0,
digit = 0;

// str.length() function to count number of


// character in given string.
for (int i = 0; i < str.length(); i++) {

char ch = str[i];

if ( (ch >= 'a' && ch <= 'z') ||


(ch >= 'A' && ch <= 'Z') ) {

// To handle upper case letters


ch = tolower(ch);
if (ch == 'a' || ch == 'e' || ch ==
'i' ||
ch == 'o' || ch == 'u')
vowels++;
else
consonant++;}

else if (ch >= '0' && ch <= '9')


digit++;
else
specialChar++;}

cout << "Vowels: " << vowels << endl;


cout << "Consonant: " << consonant << endl;
cout << "Digit: " << digit << endl;
cout << "Special Character: " << specialChar
<< endl;}

// Driver function.
int main()
{string str = "geeks for geeks121";
countCharacterType(str);
return 0;}

Output:-
Vowels = 5
Consonant = 8
Digit = 3
Special characters = 2
11. Input a string and determine whether it is a
palindrome or not; convert the case of characters
in a string.

# Program to check if a string is palindrome or


not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison


my_str = my_str.casefold()

# reverse the string


rev_str = reversed(my_str)

# check if the string is equal to its reverse


if list(my_str) == list(rev_str):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

Output :-
The string is a palindrome.
12. Find the largest/smallest number in a
list/tuple.

lst = []
num = int(input('How many numbers: '))for n in
range(num):
numbers = int(input('Enter number '))
lst.append(numbers)print("Maximum element in the
list is :", max(lst), "\nMinimum element in the list
is :", min(lst))

Output:-
13. Input a list of numbers and swap elements at
the even location with the elements at the odd
location.

val=eval(input("Enter a list "))


print("Original List is:",val)
s=len(val)
if s%2!=0:
s=s-1
for i in range(0,s,2):
val[i],val[i+1]=val[i+1],val[i]
print("List after swapping :",val)

output:-

Enter a list [3,4,5,6]

Original List is: [3, 4, 5, 6]

List after swapping : [4, 3, 6, 5]


14. Input a list/tuple of elements, search for a
given element in thelist/tuple.

listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed',


3)]
test_elem = 'Mon'
#Given list
print("Given list:
",listA)
print("Check value:
",test_elem)
# Uisng for and if
res = [item for item in listA
if item[0] == test_elem and item[1] >= 2]
# printing res
print("The tuples satisfying the conditions:
",res)

Output:-

Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
15. Input a list of numbers and find the smallest
and largest number from the list.

# Python program to find smallest


# number in a list

# list of numbers
list1 = [10, 20, 4, 45, 99]

# sorting the list


list1.sort()

# printing the first element


print("Smallest element is:", list1[0])

Output :- Smallest number :- 4


16. Create a dictionary with the roll number,
name and marks of n students in a class and
display the names of students who have scored
marks above 75.

n=int(input("Enter n: "))
d={}
for i in range(n):
roll_no=int(input("Enter roll no: "))
name=input("Enter name: ")
marks=int(input("Enter marks: "))
d[roll_no]=[name,marks]
for k in d:
if(d[k][1]>75):
print(d[k][0])

Output:-
Enter n: 2

Enter roll no: 1

Enter name: a

Enter marks: 85

Enter roll no: 2

Enter name: b

Enter marks: 55

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy