Raj - Ipynb - Colaboratory

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

21291341091_raj.

ipynb - Colaboratory

EXERCISES -
9

basic examples given in chapter is here

temp=0 while temp!


=-1000:
temp = eval(input('Enter a temperature (-1000 to quit):'))
print('In Fahrenheit that is', 9/5*temp+32)

Enter a temperature (-1000 to quit):1000


In Fahrenheit that is 1832.0
Enter a temperature (-1000 to quit):-1000
In Fahrenheit that is -1768.0

temp = 0 while
temp!=-1000:
temp = eval(input('Enter a temperature (-1000 to quit): '))
if temp!=-1000:
print('In Fahrenheit that is', 9/5*temp+32)
else: print('Bye!')

Enter a temperature (-1000 to quit): 123


In Fahrenheit that is 253.4
Enter a temperature (-1000 to quit): -1023
In Fahrenheit that is -1809.4
Enter a temperature (-1000 to quit): -1000
Bye!

from random import randint


secret_num =
randint(1,10) guess = 5
while guess !=
secret_num: guess =
eval(input('Guess the
secret number: '))
print('You finally got
it!')

Guess the secret number: 1


Guess the secret number: 2
You finally got it!

i=0 while
i<10:
print(i)
i=i+1

0
1
2
3
4
5
6
7
8
9

temp = eval(input('Enter a temperature in Celsius: '))


if temp<-273.15:
print('That temperature is not possible.')
else: print('In Fahrenheit, that is',
9/5*temp+32)

Enter a temperature in Celsius: 123


In Fahrenheit, that is 253.4

temp = eval(input('Enter a temperature in Celsius: '))


while temp<-273.15:
temp = eval(input('Impossible. Enter a valid temperature: '))
print('In Fahrenheit, that is', 9/5*temp+32)

Enter a temperature in Celsius: 123


In Fahrenheit, that is 253.4
21291341091_raj.ipynb - Colaboratory
i = 0 while
i<50:
print(i)
i=i+2
print('Bye!'
)

0
2
4
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
Bye!

for i in range(10):
num = eval(input('Enter number: '))
if num<0:
break

Enter number: 2
Enter number: 1
Enter number: 4
Enter number: 3
Enter number: 5
Enter number: 6
Enter number: 7
Enter number: 8
Enter number: 9
Enter number: 10

i=0 num=1 while i<10


and num>0:
num = eval(input('Enter a number: '))

Enter a number: 4
Enter a number: 3
Enter a number: 2
Enter a number: 1
Enter a number: 5
Enter a number: 6
Enter a number: 7
Enter a number: 8
Enter a number: 9
Enter a number: 10
Enter a number: 1
Enter a number: 1
Enter a number: 132
Enter a number: -24

for i in range(10):
num = eval(input('Enter number: '))
if num<0: print('Stopped early')
break else: print('User entered
all ten values')

Enter number: 12
User entered all ten values
Enter number: 1
User entered all ten values
Enter number: 2
User entered all ten values
Enter number: 3
21291341091_raj.ipynb - Colaboratory
User entered all ten values
Enter number: 4
User entered all ten values
Enter number: 5
User entered all ten values
Enter number: 6
User entered all ten values
Enter number: 7
User entered all ten values
Enter number: 8
User entered all ten values
Enter number: 9
User entered all ten values

from random import randint secret_num =


randint(1,100) num_guesses = 0 guess = 0 while guess
!= secret_num and num_guesses <= 9: guess =
eval(input('Enter your guess (1-100): '))
num_guesses = num_guesses + 1 if guess <
secret_num:
print('HIGHER.', 10-num_guesses, 'guesses left.\n')
elif guess > secret_num:
print('LOWER.', 10-num_guesses, 'guesses left.\n')
else:
print('You got it!') if num_guesses==10 and
guess != secret_num: print('You lose. The correct
number is', secret_num)

Enter your guess (1-100): 60


HIGHER. 9 guesses left.

Enter your guess (1-100): 70


HIGHER. 8 guesses left.

Enter your guess (1-100): 80


HIGHER. 7 guesses left.

Enter your guess (1-100): 90


HIGHER. 6 guesses left.

Enter your guess (1-100): 100


LOWER. 5 guesses left.

Enter your guess (1-100): 98


HIGHER. 4 guesses left.

Enter your guess (1-100): 99


You got it!

basic exercises are completed

1. The code below prints the numbers from 1 to 50. Rewrite the code using a while loop to accomplish the same thing. for i in range(1,51): print(i)

num =0 while
num < 51:
print(num)
num+=1

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
21291341091_raj.ipynb - Colaboratory
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50

2. (a) Write a program that uses a while loop (not a for loop) to read through a string and print the characters of the string one-by-one on separate lines.
(b) Modify the program above to print out every second character of the string.

s = "Sorry" num =0
while num <
len(s):
print(s[num])
num += 2

S
r
y
3. A good program will make sure that the data its users enter is valid. Write a program that asks the user for a weight and converts it from kilograms to
pounds. Whenever the user enters a weight below 0, the program should tell them that their entry is invalid and then ask them again to enter a
weight. [Hint: Use a while loop, not an if statement].

while True:
weight =eval(input("Enter Weight in Kg: "))
if weight < 0:
print("Illegal weight entered")
else:
pounds = weight * 2.2
print("Your weight in Pounds is",pounds)

4. Write a program that asks the user to enter a password. If the user enters the right password, the program should tell them they are logged in to the
system. Otherwise, the program should ask them to reenter the password. The user should only get ve tries to enter the password, after which point
the program should tell them that they are kicked off of the system.

numberoftries = 0

while numberoftries < 5: rightpass


="mihir" askuserpass=input("Enter
Password: ")

if askuserpass == rightpass:
print("User Access Granted")
numberoftries += 1 break
else:
numberoftries += 1
print("Wrong Password","Number of tries left",5-numberoftries)

5. Write a program that allows the user to enter any number of test scores. The user indicates they are done by entering in a negative number. Print how
many of the scores are A’s (90 or above). Also print out the average.

scores=[]
count=5
while True:
21291341091_raj.ipynb - Colaboratory
testscore =eval(input("Enter Test Cores: "))
scores.append(testscore) if testscore >=
90:
count+=1

if testscore == 0:
print("Count Agrade",count)
print("Average",sum(scores)/len(scores)) else:
print("sorry")

sorry
sorry

. Modify the higher/lower program so that when there is only one guess left, it says 1 guess, not 1 guesses.

from random import randint secret_num =


randint(1,100) num_guesses = 0 guess = 0 while
guess != secret_num and num_guesses <= 9:
guess = eval(input('Enter your guess (1-100): '))
num_guesses = num_guesses + 1 if guess <
secret_num:
print('HIGHER.', 10-num_guesses, 'guesses left.\n')
elif guess > secret_num:
print('LOWER.', 10-num_guesses, 'guesses left.\n')
else:
print('You got it!') if num_guesses==10 and
guess != secret_num: print('You lose. The correct
number is', secret_num)

7. Recall that, given a string s, s.index('x') returns the index of the rst x in s and an error if there is no x. (a) Write a program that asks the user for a string
and a letter. Using a while loop, the program should print the index of the rst occurrence of that letter and a message if the string does not contain the
letter. (b) Write the above program using a for/break loop instead of a while loop

def Firstletter2():
user_input =input("Input Word: ")
letter = input("Choose Letter: ")

for character in user_input: if


character == letter:
print(user_input.index(character))
break

Firstletter2()

. The GCD (greatest common divisor) of two numbers is the largest number that both are divisible by. For instance, gcd(18, 42) is 6 because the largest
number that both 18 and 42 are divisible by is 6. Write a program that asks the user for two numbers and computes their gcd.Shown below is a way to
compute the GCD, called Euclid’s Algorithm. • First compute the remainder of dividing the larger number by the smaller number • Next, replace the
larger number with the smaller number and the smaller number with the remainder. • Repeat this process until the smaller number is 0. The GCD is
the last value of the larger number.

def Gcd():
x=int(input("Enter First Number: "))
y = int(input("Enter Second Number: "))
while x or y != 0: if x>y :
remainder = x % y
if remainder== 0:
return "The GCD is",y
break

else:
x = remainder

else:
remainder = y % x
if remainder ==0:
return "The GCD is",x
break else:
y = remainder print(Gcd())

Enter First Number: 123465


Enter Second Number: 321654
('The GCD is', 3)
21291341091_raj.ipynb - Colaboratory
10. Write a program that has a list of ten words, some of which have repeated letters and some which don’t. Write a program that picks a random word
from the list that does not have any repeated letters.

from random import randint word_list


=["henry","laura","gaga","gagayas","monique","marina","thomas","leopold","jackson","abigail"]

listofwords=[] for i in range(len(word_list)):


for j in range(len(word_list[i])):
for k in range(j+1,len(word_list[i])):

if word_list[i][j] == word_list[i][k]:
if word_list[i] not in listofwords:
listofwords.append(word_list[i])
print(listofwords)

 ['laura', 'gaga', 'gagayas', 'marina', 'leopold', 'abigail']

11. Write a program that starts with an 5 × 5 list of zeroes and randomly changes exactly ten of those zeroes to ones.

from random import randint


list_50 =[0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,
0,0,0,0,0,] i=0
total_zeros = len(list_50)
while (i <1):
value = randint(0, total_zeros-1)
list_50[value] = 1 i = i+1
print(list_50)

[0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

12. Write a program in which you have a list that contains seven integers that can be 0 or 1. Find the rst nonzero entry in the list and change it to a 1. If
there are no nonzero entries, print a message saying so.

from random import randint

L = [randint(0, 1) for i in range(7)]


print('The initial list is the following:
') print(L) print('') valid = False while
not valid: try:
i = L.index(0) print(f'The first
zero occurs at index {i}.') print('\nThe new
list is the following: ') L[i] = 1
print(L) valid = True except ValueError:
print('There are no zero entries.')
break

The initial list is the following:


[1, 1, 0, 1, 1, 1, 0] The first

zero occurs at index 2.

The new list is the following:


[1, 1, 1, 1, 1, 1, 0]

14. Write a program to play the following simple game. The player starts with
100.Oneachturnacoinisflippedandtheplayerhastoguessheadsortails.Theplayerwins9 for each correct guess and loses
10foreachincorrectguess.Thegameendseitherwhentheplayerrunsoutofmoneyorgetsto200.

from enum import Enum


from random import
choice

class coin(Enum):
FACE = {'h':'Heads', 't':'Tails'}

MONEY = 100

def heads_tails(MONEY):
while 0 < MONEY < 200:
rand_face = coin_face() message = 'Enter "h"
for heads or "t" for tails: ' user_guess =
validate_input(message) print(rand_face) if
21291341091_raj.ipynb - Colaboratory
rand_face == user_guess: MONEY += 9
print(f'You guessed right! You now have ${MONEY}.')
else: MONEY -= 10 print(f'You guessed
wrong! You now have ${MONEY}.') if MONEY < 0:
print('You do not have any more money to play.')
else: print(f'You have ${MONEY}. Good job.
Good-bye.')

def coin_face():
rand_face = choice(list(coin.FACE.value.keys()))
return rand_face

def validate_input(message):
valid = False
while not valid:
try:
user_input = input(message)
user_input = user_input.lower() if
(user_input == 'h') or (user_input == 't'):
valid = True
else:
print('\nPlease enter "h" or "t".')
except: pass return user_input

def main(): print('Welcome to Heads and Tails.') print('')


print(f'You have ${MONEY} to start with.') print('') print('If you
guess right, you get $9. If you guess wrong, you lose $10.')
heads_tails(MONEY)

if __name__ == '__main__':
main()

Welcome to Heads and Tails.

You have $100 to start with.

If you guess right, you get $9. If you guess wrong, you lose $10.
t
You guessed wrong! You now have $90.
h
You guessed right! You now have $99.
h
You guessed wrong! You now have $89.
h
You guessed wrong! You now have $79.
h
You guessed right! You now have $88.
h
You guessed right! You now have $97.
h
You guessed right! You now have $106.
h
You guessed wrong! You now have $96.
t
You guessed wrong! You now have $86.
t
You guessed wrong! You now have $76.
h
You guessed right! You now have $85.
h
You guessed wrong! You now have $75.
t
You guessed wrong! You now have $65.
h You guessed right! You now have
$74.

Please enter "h" or "t".


t
You guessed wrong! You now have $64.
h
You guessed wrong! You now have $54.
t
You guessed right! You now have $63.
t
You guessed right! You now have $72.
t
You guessed right! You now have $81.
t
You guessed wrong! You now have $71.
t
You guessed right! You now have $80.
t
You guessed wrong! You now have $70.
t
You guessed right! You now have $79.
t
21291341091_raj.ipynb - Colaboratory
You guessed right! You now have $88.
t
You guessed right! You now have $97.
h
$

15. Write a program to play the following game. There is a list of several country names and the program randomly picks one. The player then has to guess
letters in the word one at a time. Before each guess the country name is displayed with correctly guessed letters lled in and the rest of the letters
represented with dashes. For instance, if the country is Canada and the player has correctly guessed a, d, and n, the program would display -ana-da.
The program should continue until the player either guesses all of the letters of the word or gets ve letters wrong.
from random import choice from
string import ascii_lowercase
from re import finditer from sys
import exit

COUNTRY_LIST = ['canada', 'england', 'japan', 'china', 'germany', 'scotland',


'chad', 'ghana', 'mexico', 'ireland', 'korea', 'denmark']

def game_on():
num_guesses = 5 country =
get_country(COUNTRY_LIST)
country_placeholder = country for
i in country:
country = country.replace(i, '*')
while num_guesses > 0:
print(country) message = 'Enter a
letter to guess: ' guess =
validate_letter(message) if guess in
country_placeholder:
valid_letter = [x.start() for x in finditer(guess, country_placeholder)]
for j in valid_letter:
country = country[:j] + country[j].replace('*', guess) + country[j+1:]
else:
num_guesses -= 1 print(f'No "{guess}" in the country\'s name. You have
{num_guesses} number of guesses left.\n') win_lose(num_guesses, country, country_placeholder)

def get_country(COUNTRY_LIST):
rand_country = choice(COUNTRY_LIST)
return rand_country

def validate_letter(message):
valid = False
while not valid:
try:
user_input = input(message) if (user_input in
ascii_lowercase) and (len(user_input) == 1):
valid = True
else:
print('\nPlease enter a valid letter as a guess: ')
except: pass return user_input

def win_lose(num_guesses, country, country_placeholder):


if num_guesses == 0:
print(f'You ran out of guesses. The country is {country_placeholder.capitalize()}. You lose.')
elif country == country_placeholder:
print(f'\nYes the country was {country.capitalize()}.')
print('You Win!') exit() else: pass

def main():
print('Welcome to the Country Guessing Game')
print('You have 5 guesses.\n') game_on()

if __name__ == '__main__':
main()

Welcome to the Country Guessing Game


You have 5 guesses.

*******
Enter a letter to guess: 6

Please enter a valid letter as a guess:


Enter a letter to guess: l No "l" in the country's name. You
have 4 number of guesses left.

*******
Enter a letter to guess: 9

Please enter a valid letter as a guess:


Enter a letter to guess: 0

Please enter a valid letter as a guess:


Enter a letter to guess:
21291341091_raj.ipynb - Colaboratory
17. Ask the user to enter the numerator and denominator of a fraction, and the digit they want to know. For instance, if the user enters a numerator of 1
and a denominator of 7 and wants to know the 4th digit, your program should print out 8, because 1 7 = .142856... and 8 is the 4th digit. One way to
do this is to mimic the long division process you may have learned in grade school. It can be done in about ve lines using the // operator at one point
in the program.

num = eval(input('Enter numerator: ')) denum =


eval(input('Enter denumerator: ')) digit =
int(input('Enter the digit you want to know: ')) i = 0
l=[] while i < digit+1: result=num//denum
mod=num%denum num=mod*10
l.append(str(result))
i+=1 u=l[-1]
print(f'The digit is {u}' )

1 . Randomly generate a 6 × 6 list that has exactly 12 ones placed in random locations in the list. The rest of the entries should be zeroes.

from pprint import pprint


from random import randint

L = [[0 for column in range(6)]for row in range (6)]


i = 0

# Must use a while loop instead of for loop because can not repeat iterations.
while i < 12:
a, b = randint(0, 5), randint(0, 5)
if L[a][b] == 1:
pass
else:
L[a][b] = 1
i += 1 pprint(L)

You might also like