Raj - Ipynb - Colaboratory
Raj - Ipynb - Colaboratory
Raj - Ipynb - Colaboratory
ipynb - Colaboratory
EXERCISES -
9
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!')
i=0 while
i<10:
print(i)
i=i+1
0
1
2
3
4
5
6
7
8
9
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
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
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
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.
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: ")
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())
if word_list[i][j] == word_list[i][k]:
if word_list[i] not in listofwords:
listofwords.append(word_list[i])
print(listofwords)
11. Write a program that starts with an 5 × 5 list of zeroes and randomly changes exactly ten of those zeroes to ones.
[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.
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.
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
if __name__ == '__main__':
main()
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.
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
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 main():
print('Welcome to the Country Guessing Game')
print('You have 5 guesses.\n') game_on()
if __name__ == '__main__':
main()
*******
Enter a letter to guess: 6
*******
Enter a letter to guess: 9
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.
# 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)