- Introduction
- Tutorial Video
- Full Code
- Improvements
Introduction
Python Higher or Lower Card Game Tutorial
In this tutorial we walk through the steps for how to create a simple higher or lower card game using Python 3.
- How to create a deck of cards and shuffle them
- How to check for valid user inputs
- How to keep score
- How to repeatedly picks a card until the user guesses incorrectly.
The tutorial is great for Python beginners, as it reviews a number of beginner concepts, in an easy to follow manner.
- How to use 2 Dimensional Lists
- How to use nest for loops
- How user input / print
- How to improve program robustness using while loops
Tutorial Video
Full Code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time, os, random | |
ranks = ["Ace","2","3","4","5","6","7","8","9","10","Jack","Queen","King"] | |
suits = ["Clubs","Hearts","Diamonds","Spades"] | |
deck = [] | |
value = 1 | |
for rank in ranks: | |
for suit in suits: | |
deck.append([rank + " of " + suit, value]) | |
value = value + 1 | |
random.shuffle(deck) | |
score = 0 | |
card1 = deck.pop(0) | |
while True: | |
os.system("cls") # linux "clear | |
print("Your score so far is", score) | |
print("\n\nThe current card is", card1[0]) | |
while True: | |
choice = input("higher or lower?") | |
if len(choice) > 0: | |
if choice[0].lower() in ["h","l"]: | |
break | |
card2 = deck.pop(0) | |
print("The next card picked is", card2[0]) | |
time.sleep(1) | |
if choice[0].lower() == "h" and card2[1] > card1[1]: | |
print("Correct!") | |
score +=1 | |
time.sleep(1) | |
if choice[0].lower() == "h" and card2[1] < card1[1]: | |
print("Wrong!") | |
time.sleep(1) | |
break | |
if choice[0].lower() == "l" and card2[1] < card1[1]: | |
print("Correct!") | |
score +=1 | |
time.sleep(1) | |
if choice[0].lower() == "l" and card2[1] > card1[1]: | |
print("Wrong!") | |
time.sleep(1) | |
break | |
else: | |
print("draw!") | |
card1 = card2 | |
os.system("cls") | |
print("Game over!") | |
print("You final score is", score) | |
time.sleep(4) | |
os.system("cls") | |
Improvements
Finished the tutorial?
Here are some improvements you can make to the game!
Save the user’s score to a CSV file