Let us write a small code that mimics a dice by generating a random number between 1 and 6. It then asks you to enter a number between 1 and 6. If what you enter equals the dice value you win or else you loose.
In [1]:
from random import randint #From the random library we import the randint function.
def dice(user_input):
'''This function mimics a dice. It generates a random number between 1 and 6 and
sees if the value given by the user equals to the dice value'''
dice_value = randint(1,6) #Generate a randome number between 1 and 6
if int(user_input) == dice_value:
print('Congratulations ! The value entered is the dice value')
else:
print('Sorry, the dice showed: ', dice_value)
user_input = int(input('Input a number between 1 and 6: '))
#!!!Input always passes strings !!!
dice(user_input) #we pass the user_input as an argument to the function.
Now lets improve the previous function "dice()" such that the user has 5 attempts at entering the number and getting the right dice value.
In [3]:
from random import randint
def dice(user_input):
dice_value = randint(1,6) #Generate a random number between 1 and 6
if user_input == dice_value:
print('Congratulations ! The value entered is the dice value')
else:
print('Sorry, the dice showed: ', dice_value)
iterate = 0
while iterate < 5:
user_input = int(input('Input a number between 1 and 6: '))
dice(user_input)
iterate = iterate + 1
Excercise : Can you edit the the previous code so that it stops asking the user to enter a number when the value entered matches the dice value ? Hint: You will need to use the "break" command within the while loop. Also remember that you can use the "return" command to pass values back to the calling function.
In [6]:
# Enter code here
Let us write a program that asks the user to enter a text sentence and counts the number of times a particular character occurs in the sentence.
In [4]:
def count(sentence, char):
'''This function counts the number of times a particular charactors occurs in a given
sentence'''
count = 0
for x_char in sentence:
if x_char == char:
count += 1
print("Number of times the character '",char, "' occurs is: ", count) # Careful with the quotes !
sentence = input('Input your sentence: ')
sentence = sentence.lower() #the lower() comand converts the sentence to lower case
char = input('Input the character that needs to be counted: ').lower()
count(sentence, char)
Excercise: Can you use the for loop so that it counts the number of times a given word occurs in a sentence ? Hint: Use the split() command to split the sentence into a list of words and then use the for loop to traverse through the list.
In [ ]:
# Enter code here