CE376 Python Practical List
CE376 Python Practical List
if(y%x==0):
print("check divides your number
evenly")
1. Instead of printing the elements one by one, make a new list that has all the
Take a list, say for example this one: elements less than 5 from this list in it and print out this new list.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] a=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
and write a program that prints out all the elements of the list that are less
than 5.
k=[]
for i in a:
a=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
if(i<5):
for i in a:
if(i<5):
k.append(i)
print(i)
print(k)
2. Write this in one line of Python.
print(k)
3. Ask the user for a number and return a list that contains only elements from the
original list a that are smaller than that number given by the user.
k=int(input("enter a number"))
print([i for i in range(0,k)])
Create a program that asks the user for a number and then prints out a list
of all the divisors of that number. (If you don’t know what a divisor is, it is a
number that divides evenly into another number. For example, 13 is a
divisor of 26 because 26 / 13 has no remainder.)
x=int(input("enter a number:"))
for i in range(1,int(x/2)+1):
3 if(x%i==0): 2
print(i)
print(x)
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] 1. Randomly generate two lists to test this
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] import random
and write a program that returns a list that contains only the elements that a = [random.randrange(0,100) for i in
are common between the lists (without duplicates). Make sure your
program works on two lists of different sizes. range(0,random.randrange(0,100))]
for i in a:
for j in b:
common=set()
if(i==j):
common.add(i)
for i in a:
for j in b:
print(common)
if(i==j):
common.add(i)
print(a)
print(b)
print(common)
2. Write this in one line of Python (don’t worry if you can’t figure this out at this
point - we’ll get to it soon)
import random
a = [random.randrange(0,100) for i in
range(0,random.randrange(0,100))]
b = [random.randrange(0,100) for i in
range(0,random.randrange(0,100))]
print(a)
print(b)
print(common)
Ask the user for a string and print out whether this string is a palindrome or
not. (A palindrome is a string that reads the same forwards and backwards.)
x=input("enter a string:")
y=x[::-1]
if(x==y):
print("the given string is palindrome")
else:
print("not a palindrome")
Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64,
81, 100]. Write one line of Python that takes this list a and makes a new list
that has only the even elements of this list in it.
a=x.upper()
b=y.upper()
elif a==b:
print("it's a tie")
elif func(a,b):
print("Player A wins")
else:
print("Player B wins")
Generate a random number between 1 and 9 (including 1 and 9). Ask the
user to guess the number, then tell them whether they guessed too low, too 1. Keep the game going until the user types “exit”
high, or exactly right. (Hint: remember to use the user input lessons from import random
the very first practical)
x=random.randrange(1,10)
import random
i=0;
x=random.randrange(1,10) flag=True
i=0;
flag=True while(flag):
while(flag and (i<10)):
print(str(10-i)+" chances remaining")
i=i+1
y=input("enter a number:") i=i+1
if (int(y)==x):
flag=False;
y=input("enter a number:")
print("you made correct guess CONGRATULATION") if(y=="EXIT"):
elif(int(y)>x): break
print("you have guessed too high, try lower number")
if (int(y)==x):
else:
print("you have guessed too low, try greater number") flag=False;
print("you made correct guess
CONGRATULATION")
elif(int(y)>x):
print("you have guessed too high,
try lower number")
else:
print("you have guessed too low,
try greater number")
i=i+1
y=input("enter a number:")
if(y=="EXIT"):
break
if (int(y)==x):
flag=False;
print("you made correct guess
CONGRATULATION")
elif(int(y)>x):
print("you have guessed too high,
try lower number")
else:
print("you have guessed too low,
try greater number")
b = [random.randrange(0,100) for i in
range(0,random.randrange(0,100))]
print(a)
print(b)
print(sett)
Ask the user for a number and determine whether the number is prime or
not. (For those who have forgotten, a prime number is a number that has no
divisors.). You can (and should!) use your answer to Practical 2 to help you.
Take this opportunity to practice using functions, described below.
x=input("enter a number")
flag=True
if flag==True:
print("x is a prime number")
else:
print("x is not a prime number")
Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20,
25]) and makes a new list of only the first and last elements of the given list.
For practice, write this code inside a function.
def firstandlast(x):
return([x[0],x[len(x)-1]])
a = [5, 10, 15, 20,25]
print(firstandlast(a))
Write a program that asks the user how many Fibonnaci numbers to
generate and then generates them. Take this opportunity to think about
how you can use functions. Make sure to ask the user to enter the number
of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a
sequence of numbers where the next number in the sequence is the sum of
the previous two numbers in the sequence. The sequence looks like this: 1,
1, 2, 3, 5, 8, 13, …)
def fib(a,b,n):
6 c=a+b 2
print(c,end=" ")
if(n>0):
fib(b,c,n-1)
Write a program (function!) that takes a list and returns a new list that Write two different functions to do this - one using a loop and constructing a list,
contains all the elements of the first list minus all the duplicates. and another using sets.
print(customlist)
Write a program (using functions!) that asks the user for a long string
containing multiple words. Print back to the user the same string, except
with the words in backwards order. For example, say I type the string:
My name is Michele
Then I would see the string:
Michele is name My
shown back to me.
def reverse(s):
y=s.split()
k=""
for i in reversed(y):
k=k+(i+" ")
return k
k=[]
for i in range(0,1000000000):
k.append(float(i))
print(k)
x=input("enter a long string")
print(reverse(x))
Write a password generator in Python. Be creative with how you generate Ask the user how strong they want their password to be. For weak passwords, pick
passwords - strong passwords have a mix of lowercase letters, uppercase a word or two from a list.
letters, numbers, and symbols. The passwords should be random,
generating a new password every time the user asks for a new password.
Include your run-time code in a main method.
import string
from random import *
characters = string.ascii_letters + string.punctuation +
string.digits
password = "".join(choice(characters) for x in range(randint(8,
16)))
print(password)
Use the BeautifulSoup and requests Python packages to print out a list of all
the article titles on the New York Times homepage.
result=requests.get("http://www.charusat.ac.in")
print(result.status_code)
print(result)
c=result.content
soup=BeautifulSoup(c,features="lxml")
#print (soup.prettify())
for link in soup.find_all('a'):
print(link.get('href'))
Create a program that will play the “cows and bulls” game with the user.
The game works like this:
def numberofmatch(randomnumber,x):
firstdigit = (randomnumber // 1000) % 10
seconddigit = (randomnumber // 100) % 10
thirddigit = (randomnumber // 10) % 10
fourthdigit = (randomnumber // 1) % 10
firstdigitguessed = (x // 1000) % 10
seconddigitguessed = (x // 100) % 10
thirddigitguessed = (x // 10) % 10
fourthdigitguessed = (x // 1) % 10
count=0
if(firstdigit==firstdigitguessed):
count+=1
if(seconddigit==seconddigitguessed):
count+=1
if(thirddigit==thirddigitguessed):
count+=1
if(fourthdigit==fourthdigitguessed):
count+=1
return count
flag=True
while flag:
x=int(input("enter a guess of four digit "))
c=numberofmatch(randomnumber,x)
print("{} cows,{} bulls".format(c,4-c))
if(c==4):
flag=False
print("congratulation you guessed correctly.")
Using the requests and BeautifulSoup Python libraries, print to the screen
the full text of the article on this website: http://www.vanityfair.
com/society/2014/06/monica-lewinsky-humiliation-culture.
The article is long, so it is split up between 4 pages. Your task is to print out
the text to the screen so that you can read the full article without having to
8 click any buttons. This will just print the full text of the article to the screen. 2
It will not make it easy to read, so next exercise we will learn how to write
this text to a .txt file.
import requests
from bs4 import BeautifulSoup
import codecs
import textwrap
def get_web_page(url):
r = requests.get(url)
return r.text
url = 'http://www.vanityfair.com/society/2014/06/monica-lewinsky-
humiliation-culture'
fileName = 'VanityFair.txt'
html_fileName = 'VanityFair_html.txt'
FormattedFileName = 'VanityFair_Formatted.txt'
html = get_web_page(url)
soup = BeautifulSoup(html, 'html.parser', from_encoding='utf-8')
article = soup.find_all(class_="content-section")
Write a function that takes an ordered list of numbers (a list where the Use Binary Search
elements are in order from smallest to largest) and another number. The
function decides whether or not the given number is inside the list and
returns (then prints) an appropriate boolean.
def contains(x,y):
for i in x:
if(i==y):
return True
return False
Take the code from the How To Decode A Website exercise , and instead Ask the user to specify the name of the output file that will be saved.
of printing the results to a screen, write the results to a txt file. In your
code, just make up a name for the file you are saving to.
from bs4 import BeautifulSoup as soup
import requests
import re
9 2
my_url = 'https://www.nytimes.com'
# html parsing
page_soup = soup(page_html, 'html.parser')
open_file.close()
Instead of using the .txt file from above (or instead of, if you want the challenge),
Given a .txt file that has a list of a bunch of names, count how many of each take this .txt file, and count how many of each “category” of each image there are.
name there are in the file, and print out the results to the screen. This text file is actually a list of files corresponding to the SUN database scene
count=dict()
recognition database, and lists the file directory hierarchy for the images. Once you
with open("jainil",'r') as f: take a look at the first line or two of the file, it will be clear which part represents
x=f.read()
y=x.split() the scene category. To do this, you’re going to have to remember a bit about string
for i in y: parsing in Python 3. I talked a little bit about it in this post.
count[i]=0
for i in y:
count[i]+=1
print(count)
print()
print()
k=0
while True:
k+=1
print(k)
if(k==3):
continue
elif(k==5):
pass
elif(k==9):
break
print("loop complete")
l.append(n)
n+=1
a(n)
return l
else:
return
print(a(1))
t
Develop programs to understand working of exception handling and assertions
fh=open("testfile", "w")
11 try: 2
fh = open("testfile", "w")
fh.write("This is my test file for exception handling!!")
except IOError:
print ("Error: can\'t find file or read data")
else:
print ("Written content in the file successfully") Recalling all concepts of above practicals
finally:
fh.close()