Loading...
More Python Posts
mydict = {'carl':40, 'alan':2, 'bob':1, 'danny':0}# How to sort a dict by value Python 3>sort = {key:value for key, value in sorted(mydict.items(), key=lambda kv: (kv[1], kv[0]))}print(sort)# How to sort a dict by key Python 3>sort = {key:mydict[key] for key in sorted(mydict.keys())}print(sort)
from time import sleepdef delay(fn, ms, *args):sleep(ms / 1000)return fn(*args)delay(lambda x: print(x), 1000, 'later') # prints 'later' after one second
my_list = [1, 2, 3, 4, 5]removed_element = my_list.pop(2) # Remove and return element at index 2print(removed_element) # 3print(my_list) # [1, 2, 4, 5]last_element = my_list.pop() # Remove and return the last elementprint(last_element) # 5print(my_list) # [1, 2, 4]
""" Number Guessing Game----------------------------------------"""import randomattempts_list = []def show_score():if len(attempts_list) <= 0:print("There is currently no high score, it's yours for the taking!")else:print("The current high score is {} attempts".format(min(attempts_list)))def start_game():random_number = int(random.randint(1, 10))print("Hello traveler! Welcome to the game of guesses!")player_name = input("What is your name? ")wanna_play = input("Hi, {}, would you like to play the guessing game? (Enter Yes/No) ".format(player_name))// Where the show_score function USED to beattempts = 0show_score()while wanna_play.lower() == "yes":try:guess = input("Pick a number between 1 and 10 ")if int(guess) < 1 or int(guess) > 10:raise ValueError("Please guess a number within the given range")if int(guess) == random_number:print("Nice! You got it!")attempts += 1attempts_list.append(attempts)print("It took you {} attempts".format(attempts))play_again = input("Would you like to play again? (Enter Yes/No) ")attempts = 0show_score()random_number = int(random.randint(1, 10))if play_again.lower() == "no":print("That's cool, have a good one!")breakelif int(guess) > random_number:print("It's lower")attempts += 1elif int(guess) < random_number:print("It's higher")attempts += 1except ValueError as err:print("Oh no!, that is not a valid value. Try again...")print("({})".format(err))else:print("That's cool, have a good one!")if __name__ == '__main__':start_game()
def check_prop(fn, prop):return lambda obj: fn(obj[prop])check_age = check_prop(lambda x: x >= 18, 'age')user = {'name': 'Mark', 'age': 18}check_age(user) # True
""" Calculator----------------------------------------"""def addition ():print("Addition")n = float(input("Enter the number: "))t = 0 //Total number enterans = 0while n != 0:ans = ans + nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def subtraction ():print("Subtraction");n = float(input("Enter the number: "))t = 0 //Total number entersum = 0while n != 0:ans = ans - nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def multiplication ():print("Multiplication")n = float(input("Enter the number: "))t = 0 //Total number enterans = 1while n != 0:ans = ans * nt+=1n = float(input("Enter another number (0 to calculate): "))return [ans,t]def average():an = []an = addition()t = an[1]a = an[0]ans = a / treturn [ans,t]// main...while True:list = []print(" My first python program!")print(" Simple Calculator in python by Malik Umer Farooq")print(" Enter 'a' for addition")print(" Enter 's' for substraction")print(" Enter 'm' for multiplication")print(" Enter 'v' for average")print(" Enter 'q' for quit")c = input(" ")if c != 'q':if c == 'a':list = addition()print("Ans = ", list[0], " total inputs ",list[1])elif c == 's':list = subtraction()print("Ans = ", list[0], " total inputs ",list[1])elif c == 'm':list = multiplication()print("Ans = ", list[0], " total inputs ",list[1])elif c == 'v':list = average()print("Ans = ", list[0], " total inputs ",list[1])else:print ("Sorry, invilid character")else:break