Chapter 10 - Python Crash Course, 2nd Edition (2023)

  • 10-1: Learning Python
  • 10-2: Learning C
  • 10-3: Guest
  • 10-4: Guest Book
  • 10-5: Programming Poll
  • 10-6: Addition
  • 10-7: Addition Calculator
  • 10-8: Cats and Dogs
  • 10-9: Silent Cats and Dogs
  • 10-10: Common Words
  • 10-11: Favorite Number
  • 10-12: Favorite Number Remembered
  • 10-13: Verify User

Back to solutions.

10-1: Learning Python

Open a blank file in your text editor and write a few lines summarizing what you’ve learned about Python so far. Start each line with the phrase In Python you can… Save the file as learning_python.txt in the same directory as your exercises fro mthis chapter. Write a program that reads the file and prints what you wrote three times. Print the contents once by reading in the entire file, once by looping over the file object, and once by storing the lines in a list and then working with them outside the with block.

learning_python.txt:

In Python you can store as much information as you want.In Python you can connect pieces of information.In Python you can model real-world situations.

learning_python.py:

filename = 'learning_python.txt'print("--- Reading in the entire file:")with open(filename) as f: contents = f.read()print(contents)print("\n--- Looping over the lines:")with open(filename) as f: for line in f: print(line.rstrip())print("\n--- Storing the lines in a list:")with open(filename) as f: lines = f.readlines()for line in lines: print(line.rstrip())

Output:

--- Reading in the entire file:In Python you can store as much information as you want.In Python you can connect pieces of information.In Python you can model real-world situations.--- Looping over the lines:In Python you can store as much information as you want.In Python you can connect pieces of information.In Python you can model real-world situations.--- Storing the lines in a list:In Python you can store as much information as you want.In Python you can connect pieces of information.In Python you can model real-world situations.

top

10-2: Learning C

You can use the replace() method to replace any word in a string with a different word. Here’s a quick example showing how to replace 'dog' with 'cat' in a sentence:

>>> message = "I really like dogs.">>> message.replace('dog', 'cat')'I really like cats.'

Read in each line from the file you just created, learning_python.txt, and replace the word Python with the name of another language, such as C. Print each modified line to the screen.

filename = 'learning_python.txt'with open(filename) as f: lines = f.readlines()for line in lines: # Get rid of newline, then replace Python with C. line = line.rstrip() print(line.replace('Python', 'C'))

Output:

In C you can store as much information as you want.In C you can connect pieces of information.In C you can model real-world situations.

You can use rstrip() and replace() on the same line. This is called chaining methods. In the following code the newline is stripped from the end of the line and then Python is replaced by C. The output is identical to the code shown above.

filename = 'learning_python.txt'with open(filename) as f: lines = f.readlines()for line in lines: # Get rid of newline, then replace Python with C. print(line.rstrip().replace('Python', 'C'))

top

10-3: Guest

Write a program that prompts the user for their name. When they respond, write their name to a file called guest.txt.

name = input("What's your name? ")filename = 'guest.txt'with open(filename, 'w') as f: f.write(name)

Output:

What's your name? eric
(Video) Python Crash Course Chapter 10 : Files and Exceptions [2]

guest.txt:

eric

top

10-4: Guest Book

Write a while loop that prompts users for their name. When they enter their name, print a greeting to the screen and add a line recording their visit in a file called guest_book.txt. Make sure each entry appears on a new line in the file.

filename = 'guest_book.txt'print("Enter 'quit' when you are finished.")while True: name = input("\nWhat's your name? ") if name == 'quit': break else: with open(filename, 'a') as f: f.write(f"{name}\n") print(f"Hi {name}, you've been added to the guest book.")

Output:

Enter 'quit' when you are finished.What's your name? ericHi eric, you've been added to the guest book.What's your name? willieHi willie, you've been added to the guest book.What's your name? everHi ever, you've been added to the guest book.What's your name? erinHi erin, you've been added to the guest book.What's your name? quit

guest_book.txt:

ericwillieevererin

top

10-5: Programming Poll

Write a while loop that asks people why they like programming. Each time someone enters a reason, add their reason to a file that stores all the responses.

filename = 'programming_poll.txt'responses = []while True: response = input("\nWhy do you like programming? ") responses.append(response) continue_poll = input("Would you like to let someone else respond? (y/n) ") if continue_poll != 'y': breakwith open(filename, 'a') as f: for response in responses: f.write(f"{response}\n")

Output:

Why do you like programming? Programmers can build almost anything they can imagine.Would you like to let someone else respond? (y/n) yWhy do you like programming? It's really fun, and really satisfying.Would you like to let someone else respond? (y/n) yWhy do you like programming? It just never gets old.Would you like to let someone else respond? (y/n) n

programming_poll.txt:

Programmers can build almost anything they can imagine.It's really fun, and really satisfying.It just never gets old.

top

10-6: Addition

One common problem when prompting for numerical input occurs when people provide text instead of numbers. When you try to convert the input to an int, you’ll get a ValueError. Write a program that prompts for two numbers. Add them together and print the result. Catch the TypeError if either input value is not a number, and print a friendly error message. Test your program by entering two numbers and then by entering some text instead of a number.

try: x = input("Give me a number: ") x = int(x) y = input("Give me another number: ") y = int(y)except ValueError: print("Sorry, I really needed a number.")else: sum = x + y print(f"The sum of {x} and {y} is {sum}.")

Output with two integers:

Give me a number: 23Give me another number: 47The sum of 23 and 47 is 70.
(Video) Working with Files and Exceptions: Python Crash Course - Episode 10

Output with non-numerical input:

Give me a number: 23Give me another number: fredSorry, I really needed a number.

top

10-7: Addition Calculator

Wrap your code from Exercise 10-6 in a while loop so the user can continue entering numbers even if they make a mistake and enter text instead of a number.

print("Enter 'q' at any time to quit.\n")while True: try: x = input("\nGive me a number: ") if x == 'q': break x = int(x) y = input("Give me another number: ") if y == 'q': break y = int(y) except ValueError: print("Sorry, I really needed a number.") else: sum = x + y print(f"The sum of {x} and {y} is {sum}.")

Output:

Enter 'q' at any time to quit.Give me a number: 23Give me another number: 47The sum of 23 and 47 is 70.Give me a number: threeSorry, I really needed a number.Give me a number: 3Give me another number: fiveSorry, I really needed a number.Give me a number: -12Give me another number: 20The sum of -12 and 20 is 8.Give me a number: q

top

10-8: Cats and Dogs

Make two files, cats.txt and dogs.txt. Store at least three names of cats in the first file and three names of dogs in the second file. Write a program that tries to read these files and print the contents of the file to the screen. Wrap your code ina try-except block to catch the FileNotFound error, and print a friendly message if a file is missing. Move one of the files to a different location on your system, and make sure the code in the except block executes properly.

cats.txt:

henryclarencemildred

dogs.txt:

willieannahootzsummit

cats_and_dogs.py:

filenames = ['cats.txt', 'dogs.txt']for filename in filenames: print(f"\nReading file: {filename}") try: with open(filename) as f: contents = f.read() print(contents) except FileNotFoundError: print(" Sorry, I can't find that file.")

Output with both files:

Reading file: cats.txthenryclarencemildredReading file: dogs.txtwillieannahootzsummit

Output after moving cats.txt:

Reading file: cats.txt Sorry, I can't find that file.Reading file: dogs.txtwillieannahootzsummit

top

10-9: Silent Cats and Dogs

Modify your except block in Exercise 10-8 to fail silently if either file is missing.

(Video) Python Crash Course Chapter 10 : Files and Exceptions [1]

filenames = ['cats.txt', 'dogs.txt']for filename in filenames: try: with open(filename) as f: contents = f.read() except FileNotFoundError: pass else: print(f"\nReading file: {filename}") print(contents)

Output when both files exist:

Reading file: cats.txthenryclarencemildredReading file: dogs.txtwillieannahootzsummit

Output when cats.txt has been moved:

Reading file: dogs.txtwillieannahootzsummit

top

10-10: Common Words

Visit Project Gutenberg (https://gutenberg.org/) and find a few texts you’d like to analyze. Download the text files for these works, or copy the raw text from your browser into a text file on your computer.

You can use the count() method to find out how many times a word or phrase appears in a string. For example, the following code counts the number of times 'row' appers in a string:

>>> line = "Row, row, row your boat">>> line.count('row')2>>> line.lower().count('row')3 

Notice that converting the string to lowercase using lower() catches all appearances of the word you’re looking for, regardless of how it’s formatted.

Write a program that reads the files you found at Project Gutenberg and determines how many times the word ‘the’ appears in each text. This will be an approximation because it will also count words such as ‘then’ and ‘tehre’. Try counting ‘the ‘, with a space in the string, and see how much lower your count is.

common_words.py

def count_common_words(filename, word): """Count how many times word appears in the text.""" # Note: This is a really simple approximation, and the number returned # will be higher than the actual count. try: with open(filename, encoding='utf-8') as f: contents = f.read() except FileNotFoundError: pass else: word_count = contents.lower().count(word) msg = f"'{word}' appears in {filename} about {word_count} times." print(msg)filename = 'alice.txt'count_common_words(filename, 'the')

Output:

'the' appears in alice.txt about 2505 times.

This solution only examines one text, but the function can be applied to any number of texts.

10-11: Favorite Number

Write a program that prompts for the user’s favorite number. Use json.dump() to store this number in a file. Write a separate program that reads in this value and prints the message, “I know your favorite number! It’s _____.”

favorite_number_write.py:

import jsonnumber = input("What's your favorite number? ")with open('favorite_number.json', 'w') as f: json.dump(number, f) print("Thanks! I'll remember that.")

Output:

What's your favorite number? 42Thanks! I'll remember that.

favorite_number_read.py:

(Video) Python Crash Course Chapter 10

import jsonwith open('favorite_number.json') as f: number = json.load(f)print(f"I know your favorite number! It's {number}.")

Output:

I know your favorite number! It's 42.

top

10-12: Favorite Number Remembered

Combine the two programs from Exercise 10-11 into one file. If the number is already stored, report the favorite number to the user. If not, prompt for the user’s favorite number and store it in a file. Run the program twice to see that it works.

import jsontry: with open('favorite_number.json') as f: number = json.load(f)except FileNotFoundError: number = input("What's your favorite number? ") with open('favorite_number.json', 'w') as f: json.dump(number, f) print("Thanks, I'll remember that.")else: print(f"I know your favorite number! It's {number}.")

Output, first run:

What's your favorite number? 42Thanks, I'll remember that.

Output, second run:

I know your favorite number! It's 42.

top

10-13: Verify User

The final listing for remember_me.py assumes either that the user has already entered their username or that the program is running for the first time. We should modify it in case the current user is not the person who last used the program.

Before printing a welcome back message in greet_user(), ask the user if this is the correct username. If it’s not, call get_new_username() to get the correct username.

import jsondef get_stored_username(): """Get stored username if available.""" filename = 'username.json' try: with open(filename) as f_obj: username = json.load(f_obj) except FileNotFoundError: return None else: return usernamedef get_new_username(): """Prompt for a new username.""" username = input("What is your name? ") filename = 'username.json' with open(filename, 'w') as f_obj: json.dump(username, f_obj) return usernamedef greet_user(): """Greet the user by name.""" username = get_stored_username() if username: correct = input(f"Are you {username}? (y/n) ") if correct == 'y': print(f"Welcome back, {username}!") else: username = get_new_username() print(f"We'll remember you when you come back, {username}!") else: username = get_new_username() print(f"We'll remember you when you come back, {username}!")greet_user()

Output:

> python verify_user.pyWhat is your name? ericWe'll remember you when you come back, eric!> python verify_user.pyAre you eric? (y/n) yWelcome back, eric!> python verify_user.pyAre you eric? (y/n) nWhat is your name? everWe'll remember you when you come back, ever!> python verify_user.pyAre you ever? (y/n) yWelcome back, ever!

You might notice the identical else blocks in this version of greet_user(). One way to clean this function up is to use an empty return statement. An empty return statement tells Python to leave the function without running any more code in the function.

Here’s a cleaner version of greet_user():

def greet_user(): """Greet the user by name.""" username = get_stored_username() if username: correct = input(f"Are you {username}? (y/n) ") if correct == 'y': print(f"Welcome back, {username}!") return # We got a username, but it's not correct. # Let's prompt for a new username. username = get_new_username() print(f"We'll remember you when you come back, {username}!")

The return statement means the code in the function stops running after printing the welcome back message. When the username doesn’t exist, or the username is incorrect, the return statement is never reached. The second part of the function will only run when the if statements fail, so we don’t need an else block. Now the function prompts for a new username when either if statement fails.

The only thing left to address is the nested if statements. This can be cleaned up by moving the code that checks whether the username is correct to a separate function. If you’re enjoying this exercise, you might try making a new function called check_username() and see if you can remove the nested if statement from greet_user().

top

(Video) Python Crash Course Chapter 10 : Files and Exceptions [3]

FAQs

How many chapters does Python crash course have? ›

Aimed at newcomers to the programming world, specially young people, it keeps you interested on learning more and more. Initially I wanted to do one chapter per day. I ended doing the basics (11 chapters) in a week or less.

Is Python crash course free? ›

Python is the most popular programming language in the world. Master it with this free crash course. Python is a flexible, open source, interpreted, high level programming language, which is appropriate for use in a variety of real world settings.

What is new in Python Crash Course 3rd Edition? ›

New and updated coverage includes VS Code for text editing, the pathlib module for file handling, pytest for testing your code, as well as the latest features of Matplotlib, Plotly, and Django.

What is crash course Python? ›

Python Crash Course is the world's best-selling guide to the Python programming language. This fast-paced, thorough introduction to programming with Python will have you writing programs, solving problems, and making things that work in no time.

Can I learn Python in 7 days? ›

You don't need to join both the courses, in fact, you just need to join one course and then spend around 4 to 5 hours every day watching the course and doing exercises, this should be enough to learn Python in 7 days.

Is 2 Months enough to learn Python? ›

In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.

Can I learn Python in 3 days? ›

On average, it can take anywhere from five to 10 weeks to learn the basics of Python programming, including object-oriented programming, basic Python syntax, data types, loops, variables, and functions.

Can I learn Python in 2 weeks? ›

If you're interested in learning the fundamentals of Python programming, it could take you as little as two weeks to learn, with routine practice. If you're interested in mastering Python in order to complete complex tasks or projects or spur a career change, then it's going to take much longer.

How many hours a day should I learn Python? ›

Another option is to devote yourself to Python for five months. This is for those of you who work full time. The plan must be to spend 2-3 hours a day on the computer. Learn one day, practice the same thing the other day.

Is Python 4 coming soon? ›

Python 4.0 will probably never come — according to the creator of Python, Guido van Rossum. The lessons learned from migrating from Python 2 to Python 3 demonstrated what a hassle it is to move to a new language version. Thus, there will probably not be a new version of Python soon.

Why is Python 3 better than 2? ›

Python 3 better supports AI, machine learning, and data science. It has more updates that don't exist in Python 2. Python 3 is still supported and has a wide range of users to assist support, while Python 2 was sunsetted in 2020. Python 3 is one of the fastest-growing programming languages.

Can I master Python in 3 years? ›

If you're looking for a general answer, here it is: If you just want to learn the Python basics, it may only take a few weeks. However, if you're pursuing a data science career from the beginning, you can expect it to take four to twelve months to learn enough advanced Python to be job-ready.

What is the shortest Python course? ›

Intelligent Award: Shortest Course

Udemy's “Python from Beginner to Intermediate in 30 min” program can help quickly fill in the knowledge gaps between basic and advanced Python coding.

Is Python Crash Course enough? ›

Many people have asked if reading a book like Python Crash Course is enough to get a job as a programmer. The short answer is no; the material in Python Crash Course is necessary for getting hired, but it's not sufficient.

What are the 5 easy steps to learn Python? ›

This guide will show you how to learn Python the right way.
  1. Step 1: Understand Why Most Fail. ...
  2. Step 2: Identify What Motivates You. ...
  3. Step 3: Learn the Basic Syntax, Quickly. ...
  4. Step 4: Make Structured Projects. ...
  5. Step 5: Work on Python Projects on Your Own. ...
  6. Step 6: Keep Working on Harder (and Harder) Projects.
Dec 23, 2022

Is Python enough to get a job? ›

Even the most popular software development companies in India don't have the required resources that are skilled in python. While the language is gaining popularity, there is still not enough interest in pursuing a course or certification in acquiring this skill to start a career.

How much Python do I need to know to get a job? ›

You should have a clear understanding of Python syntax, statements, variables & operators, control structures, functions & modules, OOP concepts, exception handling, and various other concepts before going out for a Python interview. There are numerous quality courses available over the web that can help you in this.

Is Python worth learning 2022? ›

Yes, Python is worth the investment of your time and money. As one of the most popular coding languages, Python enjoys tremendous versatility, giving Python developers the freedom to enter a wide range of applications from software development, machine learning, data science, and web development.

Can I learn Python at 45 and get a job? ›

For sure yes , if you have the desired skills and knowledge . No one will ever care about the age , there are plenty of jobs available in the field of python . Beside this you can also go for freelancing as an option.

What is the hardest programming language? ›

7 Hardest Programming Languages to Learn for FAANG Interviews
  • C++ C++ is an object-oriented programming language and is considered the fastest language out there. ...
  • Prolog. Prolog stands for Logic Programming. ...
  • LISP. LISP stands for List Processing. ...
  • Haskell. ...
  • Assembly Language (ASM) ...
  • Rust. ...
  • Esoteric Languages.
Mar 25, 2021

Is Java or Python easier? ›

Java and Python are two of the most popular programming languages. Of the two, Java is the faster language, but Python is simpler and easier to learn. Each is well-established, platform-independent, and part of a large, supportive community.

How long does Python crash course take? ›

If you plan to spend a couple hours each week studying and practicing, then you can expect to take several weeks to complete a Python crash course. If you plan to spend an hour or two each day, then you can expect to complete a Python crash course more quickly.

How long did it take to finish Python crash course? ›

How long did it take me? Learning the syntax and the basics with the first part of the book took me around three weeks. The first project that I finished, the web application, only took me three days.

How many pages is Python crash course? ›

December 2022, 552 pp. Look Inside! Python Crash Course is the world's best-selling guide to the Python programming language.

How long does it take to read Python crash course? ›

Python Crash Course: A Hands-On, Project-Based Introduction to Programming. The average reader, reading at a speed of 300 WPM, would take 3 hours and 21 minutes to read Python Crash Course: A Hands-On, Project-Based Introduction to Programming by Eric Matthes.

Can I master Python in 2 weeks? ›

It's possible to learn the basics of Python in two weeks of full-time study and practice, but it will likely take more time to gain enough experience working on projects to become truly proficient.

Can I learn Python in 3 months and get a job? ›

If you're looking for a general answer, here it is: If you just want to learn the Python basics, it may only take a few weeks. However, if you're pursuing a data science career from the beginning, you can expect it to take four to twelve months to learn enough advanced Python to be job-ready.

How many hours should I study Python a day? ›

Another option is to devote yourself to Python for five months. This is for those of you who work full time. The plan must be to spend 2-3 hours a day on the computer. Learn one day, practice the same thing the other day.

How many hours a week should I learn Python? ›

After lunch, you will practice more and if you get stuck you will search online. Strictly maintains, 4–5 hours of learning and 2–3 hours of practice every single day (max you can take 1-day/week break).

Can we learn Python in 30 days? ›

Python has a wealth of educational options at their disposal. 30 days of Python programming challenge is a step-by-step guide to learning the Python programming language in 30 days. Python can be used for web development, data analysis, and more.

Can you learn Python in 24 hours? ›

In just 24 sessions of one hour or less, Sams Teach Yourself Python in 24 Hours will help you get started fast, master all the core concepts of programming, and build anything from websites to games.

Is Python Crash Course enough to learn Python? ›

“Learning Python with Python Crash Course was an extremely positive experience! A great choice if you're new to Python.” "While Python Crash Course uses Python to teach you to code, it also teaches clean programming skills that apply to most other languages."

What is the fastest time to learn Python? ›

First, I'll address how quickly you should be able to learn Python. If you're interested in learning the fundamentals of Python programming, it could take you as little as two weeks to learn, with routine practice.

Videos

1. PYTHON tutorials || Demo - 1 || by Mr. Prakash Babu On 03-02-2023 @10AM IST
(Durga Software Solutions)
2. Become a Professional Python programmer: Classes and OOP - Python Crash Course - Episode 9
(Learning Python)
3. "Python Crash Course" - best book to learn Python?
(makes sense)
4. Python Crash Course by Eric Matthes: Review | Learn Python for beginners
(Python Programmer)
5. Python Crash Course For Beginners
(Traversy Media)
6. Python Tutorial | Python Crash Course | Python for Beginners
(Block Explorer)
Top Articles
Latest Posts
Article information

Author: Prof. An Powlowski

Last Updated: 12/30/2022

Views: 6782

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Prof. An Powlowski

Birthday: 1992-09-29

Address: Apt. 994 8891 Orval Hill, Brittnyburgh, AZ 41023-0398

Phone: +26417467956738

Job: District Marketing Strategist

Hobby: Embroidery, Bodybuilding, Motor sports, Amateur radio, Wood carving, Whittling, Air sports

Introduction: My name is Prof. An Powlowski, I am a charming, helpful, attractive, good, graceful, thoughtful, vast person who loves writing and wants to share my knowledge and understanding with you.