PROject Python | Blackjack (#extremely.cool.it’s.kinda.unbelieveable,just.saying)

Quote of AWESOMENESS: “Thinking is already a conversation” ~ Paul Pangaro

 

Hey there!

I know it’s been awhile but here I am with another Python project. Today, you will be learning the code for blackjack! Just put it out on your editor, study the code, and explore the game on your terminal. It was quite some challenge getting toward the end of finishing up the game. And, at some point, problems and bugs constantly came up that I didn’t that it would actually get done. BUT, nevertheless, it’s finally hereeee!!

*ahem, drum rollllllllll*

*cricket sounds*

*Umm….. DRUMMM ROLLLL!!!……. please?*

*DRUM ROLLLLLLLLLL (in the background, finally)*

TADA!!!!:

#import the random library from python
from random import *


#Function Definitions 
def deal_from_deck(deck):
    if len(deck)<1:
         create_deck(deck)
         shuffle_deck(deck)
         deal_cards()

def deal_cards(deck):
    return deck.pop(0)

def define_cards(n):
    rank_string = ("ace", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen","king")
    suit_string = ("clubs", "diamonds", "hearts", "spades")
    cards = []

    for suit in range(4):
        for rank in range(13):
            card_string = rank_string[rank] + " of " + suit_string[suit]
            cards.append(card_string)
    return cards[n]

def create_deck(deck):
    for i in range(52):
        deck.append(i)
    return

def shuffle_deck(deck):
    shuffle(deck)
    return

def card_value(n):
    vals = (11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10)
    card_vals = []

    for s in range(4):
        for r in range(13):
            card_vals.append(vals[r])
    return card_vals[n]

def card_display(n):
    name = define_cards(n)
    val = card_value(n)
    print (name + " : " + str(val))

def show_cards(hand):
    for card in hand:
        card_display(card)


def hand_val(hand):
    list = []
    for card in hand:
        list.append(card_value(card))
    if sum(list) > 21:
        for i in range(len(list)):
            if list[i] == 11:
                list[i] = 1
    return sum(list)





# Initializing
drawn_hands = 0
player_wins = 0
dealer_win = 0
deck = []
player_hand = []
dealer_hand = []
playing = True


#Processing
create_deck(deck)
shuffle_deck(deck)

for i in range(2):
    card = deal_cards(deck)
    card2 = deal_cards(deck)
    player_hand.append(card)
    dealer_hand.append(card2)


# put in a loop for player hand
print()
print("--------------------")
print("Dealer shows: ")
card_display(dealer_hand[0])
print("--------------------")

while playing == True:
    player_val = hand_val(player_hand)
    print()
    print()
    print("* * * * * * * * * * *")
    print("Your current hand is...")
    show_cards(player_hand)
    print(hand_val(player_hand))
    print("* * * * * * * * * * *")
    print()
    print()
    if player_val < 22:
        response = input("Would you like another card?")
        if response == "yes":
            player_hand.append(deal_cards(deck))
        else:
            playing = False
    else:
        playing = False
        print("sorry you busted")
        print("Thanks for playing")
        exit()

# check if it is higher than 21, if yes then end program, dealer hand wins
show_cards(dealer_hand)

playing = True
while playing == True:
    if hand_val(dealer_hand) < 17:
        dealer_hand.append(deal_cards(deck))
    else:
        playing = False

print()
print()
print("****************")
print("Dealer has:")
print(show_cards(dealer_hand))
print("****************")
print()
print()

if hand_val(dealer_hand) > 21:
    print("The dealer busted")
    show_cards(dealer_hand)
    print("You win!")
    exit()
elif hand_val(dealer_hand) > hand_val(player_hand):
    print("Dealer wins")
    show_cards(dealer_hand)
    exit()
elif hand_val(player_hand) > hand_val(dealer_hand):
    print("You win!")
    show_cards(player_hand)
    exit()
else:
    print("It's a draw")
    exit()

 

don’t forget to smile & be awesome 🙂

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria

PROject Python: Hangman Game!

Quote of AWESOMENESS: “First, solve the problem. Then, write the code.” ~ John Johnson

Yup, I know, this is like the fourth blog in a row that relates to Python. BUT, it’s okay! This one is really fun. The program we will be making today is Hangman. The code is shown below:


import random

def print_game_rules(max_incorrect,word_len):
    print("This game we will be playing hangman!")

def display_figure(bad_guesses):
    gallows = (
        """
            +----------+
            |
            |
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |          +---
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |
            |
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |         /
            |        /
        ================
        """,
        """
            +----------+
            |          o
            |       ---+---
            |          |
            |         / \
            |        /   \
        ================
        """
    )
    print(gallows[bad_guesses])
    return()

def prompt_for_letter():
    print("")
    player_guess = str(input("Guess a letter in the mystery word: "))
    player_guess = player_guess.strip()
    player_guess = player_guess.lower()
    print("")
    return(player_guess)

animal_words = ("horse", "mall", "desktop", "apple", "earth", "tree", "sun", "can", "love", "dog", "door", "house", "mansion", "beach", "computer", "window", "keyboard", "airplane", "hotel", "cat")
theword = random.choice(animal_words)
word_len = len(theword)
letterguess = word_len * ["_"]
max_incorrect = 6
alphabet = ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z")
letters_tried = []
number_guesses = 0
letters_correct = 0
incorrect_guesses = 0
###############################
# PROCESSING SECTION
# Branching code: if/else
# Looping code: for-loop, while-loop
###############################

print("This game is hangman.")
while (incorrect_guesses != max_incorrect) and (letters_correct != word_len):
    letter = prompt_for_letter()
    if letter in alphabet:
        if letter in letters_tried:
            print("You already picked", letter)
        else:
            letters_tried.append(letter)
            if theword.find(letter) == -1:
                print("the letter", letter,"is not in the word")
                incorrect_guesses += 1
                print("***********************")
                print(incorrect_guesses)
            else:
                print("the letter", letter,"is in the word")
                for i in range(word_len):
                    if letter == theword[i]:
                        letterguess[i] = letter
                        letters_correct += 1
                    else:
                        pass
    else:
        print("Please guess a single letter in the alphabet.")


    x = ""
    print(x.join(letterguess))
    a = ""
    print("Letters tried so far: ", a.join(letters_tried))
    if incorrect_guesses == max_incorrect:
        print("Sorry, too many incorrect guesses. You are hanged.")
        print("The word was", theword)
    if letters_correct == word_len:
        print("You guessed all the letters in the word!")
        print("The word was", theword)



    display_figure(incorrect_guesses)

 

Honestly, this was a challenging project at the start and I had quite a few obstacles that were highly annoying but eventually here we are!

 

Pssst, don’t forget to be awesome today.

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

 

 

PROject Python: Making a function

Quote of AWESOMENESS: “The function of leadership is to produce more leaders, not more followers” ~ Ralph Leader

Hiii!

Functions are so useful and cool at the same time and right now I’m going to teach just how to make one!

But, before we go there, what exactly is a function? It’s somewhat like a pre-made command that you get to customize yourself. For example, you wanted to make five circles, imagine you would have to make each circle repeating how big you wanted it to be, the color, locations, and others. But, if you had a function, you would make it so much simpler in just adding the code and copy-pasting the function.

Here’s the code for a function:

[rememberWHITESPACE is very important in Python]

# This hastag is a comment and won't affect the code
# We start making function by defining it with the word def
# The thing written inside the parenthesis is called the argument
# Remember to put the colon then the indentation will be proper, too

def list(alist):
    # Here, I'm setting the variable a to number 0
    a = 0

    # This is a for-loop and the i just stands for index 
    for i in alist:
        if i > 0:
            a += 1
        else:
            pass
    print(a)


# Here is the actual function in action!
# Test section
mylist = [2,-4,5,-16,-20]
mylist2 = [2,6,8,-4]
mylist3 = [-5,-6,-7,-8,10]


list(mylist)
list(mylist2)
list(mylist3)

This is just a simple example of what you can make of a function. Try it out! 

 

Don’t forget to be awesome!

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

 

Project Python: Advanced Number Guessing Game (#fun)

Quote of AWESOMENESS: “Creativity is intelligence having fun” ~ Albert Einstein

Hey, guys!

Back again with another python program.

Awesome isn’t?

Now, this program is an “advanced” version of a guessing number game. So basically, the program gives the user three guesses and the numbers are ranging from 1-10. Through each time the user types in the answer and is wrong, the input would spit out either “too high” or “too low” indicating what the user’s next move should be.

Mix around with it and experiment like maybe adding a wider range of numbers to guess from or maybe adding riddles to guess the number. This code is somewhat the basis of what else can be built with it, so be creative and have fun! 

Here’s the code:



import random

range = random.randint(1, 10)

user_guess = 0

guess_counter = 0

print(“This is a guessing game and you will be given three tries to win! \nThe range will be between 1 and 10. \nGood luck!!”)

while guess_counter < 3:

user_guess = input(“What’s your guess?”)

guess_counter += 1

if user_guess.isnumeric():

user_guess = int(user_guess)

if user_guess < range:

print(“too low”)
elif user_guess > range:
print(“too high”)
else:
break

else:
print(“Not a number!”)

if user_guess == range:
print(“Awesome! You won!!”)
else:
print(“The number was actually”, range)
print(“Try again!”)



 

Have an awesome weekend!

Yours truly, 

L.O.A.S.H

 


 © Elizabeth Anne Villoria 

Python Basics!!!

Quote of awesomeness: “It’s harder to read code than to write it.” ~ Joel Spolsky

Let’s learn some basics!

Here are some simple datatypes:

  • Integers (whole number)
    • 1, 2, 3, 4, 5, 6….

 

  • Floats (decimals)
    • 1.1, 1.2, 1.3, 1.4, 1.5…..

 

  • String (anything in “quotation marks”)
    • “hello”, “my”, “awesome”, “readers!”

 

  • Boolean (I know, sounds kinda funny right)
    • these datatypes are values at two constant objects
    • a boolean is either True or False (yes, with a capital T and a capital F)

 

Want to do something cool? Yeah, me too. Okay, once you open up your terminal, type in and press enter. The next that should have happened is that your terminal should have showed this:

>>>

Did you know??!!: #when a hashtag is put in python, this is known as a comment and it doesn’t affect the code

Did you know that we can keep datatypes stored into variables? It works like this. When you write a variable a word or letter, for example, then followed by this is a equal sign you can assign a variable. Let’s try it out on your terminal! Try doing something similar to the following:

>>> x = “helllloooooo thereeee!!!”

When you pressed enter, you must have not seen anything happen but just another >>>. But, it’s okay, here’s the thing. The string I just put with the variable is now stored. So when I put my variable alone this is what happens:

>>> x

Press enter and theeeeen!!

>>> helllloooooo thereeee!!!

TADA! WASN’T THAT SUPER COOL?!?! And, that’s just the very basics of what can be reached with python. 

You can even do some math with python. The arithmetics might be slightly different but I’m sure you will get the hang of it soon!:

  • Multiply (it’s the asterisks sign)
  • Division (it’s the slash)
  • Addition (it’s the plus sign)
    • +
  • Subtraction (it’s the minus sign)
  • Exponentiation (it’s two asterisks)
    • **
  • Modulus (it’s the percentage sign) 
    • %
    • this divides a number with another number and inputs the remainder

Here’s an example of each of these signs and their outputs. You can also test this out on the python which we opened up earlier on the terminal.


multiplication, *

>>> 2 * 9

When we put the equation above, our output would be

>>> 18


 

division, /

>>> 256 / 2

The output would be:

>>> 128


 

addition, +

>>> 1000 + 1000

The output would be

>>> 2000


 

subtraction, –

>>> 500 – 200

The output would be:

>>> 300


exponentiation, **

>>> 4 ** 2

The output would be:

>>> 16


 

modulus, %

>>> 2 % 5

Would get the output of:

>>> 1


 

Go on. Try experimenting at your terminal!

!important! : Unlike other programming types, python is very picky with whitespace. Meaning the indentations! Sometimes an error on expected or unexpected indentations may rise here and there but it’s nothing a few backspaces or the tab button can’t handle.

We’ve gotten down with some of the very basics that can be done with programming. With what you’ve learned here so far try exploring and trying this out! 

Yours truly,

L.O.A.S.H

Project Python | Command Line Calender

You can make your own calendar and even add, update and view.

For your python code, copy and paste the following:


from time import sleep, strftime
name = “Libster”calendar = {}
def welcome():    print(“Welcome, ” + name + “!”)    print(“Calendar starting…”)    sleep(1)    print (“Today is “) + strftime( “%A %B %d, %Y”)     print (“The time is “) + strftime(“%I:%M:%S”)    sleep(1)    print(“What would you like to do?”)    def start_calendar():  welcome()  start = True  while start:    user_choice = raw_input(“Please choose A to Add, U to Update, V to View, X to Exit. “)    user_choice=user_choice.upper()    if user_choice == “V”:      if len(calendar.keys()) <1:        print “Your calendar is empty”      else:        print calendar    elif user_choice == “U”:        date = raw_input(“What date? “)        update = raw_input(“Enter the update: “)        calendar[date] = update        print(“Update successful.”)        print calendar    elif user_choice == “A”:        event = raw_input(“Enter event: “)        date = raw_input(“Enter date (MM/DD/YYYY): “)        if len(date) > 10 or int(date[6:]) < int(strftime(“%Y”)):            print(“Invalid date.”)              try_again = raw_input(“Try again? Y for Yes, N for No: “)            try_again = upper.try_again()            if try_again == “Y”:                continue            else:                start = False            else:            calendar[date] = event            print(“Event update successful.”)            print calendar    elif user_choice == “D”:        if calendar.keys(len(date)) < 1: #check this line if fail            print(“The calendar is empty.”)        else:            event = raw_input(“What event?”)             for date in calendar.keys():                if event == calendar[date]:                     del calendar[date] # deletes entire entry, inc date & event                print(“Event deleted.”)                print calendar            else:                print(“Incorrect date.”)    elif user_choice == “X”:        start = False    else:        print(“Invalid command.”)        breakstart_calendar()


 

Then in the command line, play your python code.

Screen Shot 2017-07-02 at 17.40.47

Above, the picture is an example of how it should turn out to be. I added an event, updated that same event and viewed! Don’t forget to try to experiment and maybe make this cooler.

Yours truly,

L.O.A.S.H