Python for Java Programmers
Chapter 1: Introduction
Example Python program
It is probably easier to showcase the features of Python with an example program.
Let us say we want to write a simple guessing game. Users are asked to guess a pre-defined secret integer, and they can make at most 5 guesses.
Here is the pseudocode of one possible algorithm.
secret_number = 42
num_of_guesses = 1
user_guess = input("Please enter a number: ")
while user_guess != secret_number and num_of_guesses < 5:
print("Incorrect.")
user_guess = input("Please enter a number: ")
num_of_guesses = num_of_guesses + 1
if user_guess == secret_number:
print("Correct")
else:
print("Incorrect. Game over.")
Here is an example Java implementation of the above algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
A Python implementation looks like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Compare my Python implementation to the pseudocode earlier. Notice the similarities.
Ok, I lied when I said that it was pseudocode. 🤥
That was not pseudocode. That was actually a valid piece of Python code. 😈
The only things I changed were the extra comment (line 5) and converting the user input from a string into an integer (lines 6 and 10)!
This demonstrates the simplicity of the Python language.