Challenge Question Solution
If you didn’t know what a palindrome was, hopefully you looked it up. It’s where a word is spelled the same forward and backward, like “racecar.” There are a couple different ways you could’ve gotten the answer to this question. The following is an example of a simple and clean solution to the problem:
>>> def palindrome(word):
>>> return True if word == word[::-1] else False
Remember that we covered ternary operators in the previous chapter, which allow us to write a one-line conditional statement. If you wrote out the entire if else statement but were able to achieve the same result, then good job! Going forward you should start trying to understand how to condense your code further to be properly optimized.
Weekly Challenges
To test out your skills, try these challenges:
Changing Passwords: Add a function called “changePassword” to the project from Friday that will allow users to change their password when logged in.
Favorite Food: Write a new program that will ask users what their favorite food is. Save the answers to a CSV file called “favorite_ food.csv”. After answering, display a table of tallied results.
Example of table:
Favorite Food?
|
# of Votes
|
Turkey
|
5
|
Salad
|
3
|
CHAPTER 7
Object-Oriented Programming
Many languages are known as object-oriented programming (OOP) languages. Python, JavaScript, Java, and C++ are just a couple of names that use OOP. Throughout this week, we’ll begin to understand what OOP is, why it’s so useful, and how to implement it within a program.
In Python (and most languages), we create objects through classes that we build. You can think of a class as a blueprint for how an object is created. Take a first-person shooter video game, for instance. All players, vehicles, and weapons are objects. There could be five people each on two teams, but each one of those people are created from the same blueprint. They all have similar features like weight, height, hair color, etc. Rather than writing the same lines of code for ten different people, you write a single blueprint and create each person from that blueprint. This condenses code and makes programs easier to manage and maintain. At the end of the week, we’ll build out a full game of Blackjack together and see the power of Python classes!
Overview
Understanding the basics of object-oriented programming
What and how to use attributes (variables within a class)
What and how to use methods (functions within a class)
Understanding the basics of inheritance (parent or base classes)
Creating Blackjack with classes
© Connor P. Milliken 2020
C. P. Milliken, Python Projects for Beginners, https://doi.org/10.1007/978-1-4842-5355-7_7
ObjeCt-Oriented prOgramming
Do'stlaringiz bilan baham: |