Chapter 10

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 from this chapter. Write a program that reads the file and prints what you wrote two times: print the contents once by reading in the entire file, and once by storing the lines in a list and then looping over each line.

from pathlib import Path
path = Path('python.txt')
contents = path.read_text()
lines = contents.splitlines()
# printing in list

for line in lines:
  print(line)

# priting entire file.
contents
The Project Gutenberg eBook of Debating for boys, by William Horton
Foster

This eBook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United States, you
will have to check the laws of the country where you are located before
using this eBook.

Title: Debating for boys

Author: William Horton Foster

Release Date: April 16, 2023 [eBook #70568]

Language: English

Produced by: Charlene Taylor and the Online Distributed Proofreading
             Team at https://www.pgdp.net (This file was produced from
             images generously made available by The Internet
             Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK DEBATING FOR BOYS ***





DEBATING FOR BOYS




                            DEBATING FOR BOYS
'The Project Gutenberg eBook of Debating for boys, by William Horton\nFoster\n\nThis eBook is for the use of anyone anywhere in the United States and\nmost other parts of the world at no cost and with almost no restrictions\nwhatsoever. You may copy it, give it away or re-use it under the terms\nof the Project Gutenberg License included with this eBook or online at\nwww.gutenberg.org. If you are not located in the United States, you\nwill have to check the laws of the country where you are located before\nusing this eBook.\n\nTitle: Debating for boys\n\nAuthor: William Horton Foster\n\nRelease Date: April 16, 2023 [eBook #70568]\n\nLanguage: English\n\nProduced by: Charlene Taylor and the Online Distributed Proofreading\n             Team at https://www.pgdp.net (This file was produced from\n             images generously made available by The Internet\n             Archive/American Libraries.)\n\n*** START OF THE PROJECT GUTENBERG EBOOK DEBATING FOR BOYS ***\n\n\n\n\n\nDEBATING FOR BOYS\n\n\n\n\n                            DEBATING FOR BOYS'

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.

contents.replace('python',"C")
'The Project Gutenberg eBook of Debating for boys, by William Horton\nFoster\n\nThis eBook is for the use of anyone anywhere in the United States and\nmost other parts of the world at no cost and with almost no restrictions\nwhatsoever. You may copy it, give it away or re-use it under the terms\nof the Project Gutenberg License included with this eBook or online at\nwww.gutenberg.org. If you are not located in the United States, you\nwill have to check the laws of the country where you are located before\nusing this eBook.\n\nTitle: Debating for boys\n\nAuthor: William Horton Foster\n\nRelease Date: April 16, 2023 [eBook #70568]\n\nLanguage: English\n\nProduced by: Charlene Taylor and the Online Distributed Proofreading\n             Team at https://www.pgdp.net (This file was produced from\n             images generously made available by The Internet\n             Archive/American Libraries.)\n\n*** START OF THE PROJECT GUTENBERG EBOOK DEBATING FOR BOYS ***\n\n\n\n\n\nDEBATING FOR BOYS\n\n\n\n\n                            DEBATING FOR BOYS'

10-3. Simpler Code:

The program file_reader.py in this section uses a temporary variable, lines, to show how splitlines() works. You can skip the temporary variable and loop directly over the list that splitlines() returns:

for line in contents.splitlines():

Remove the temporary variable from each of the programs in this section, to make them more concise.

for line in contents.splitlines():
  print(line)
The Project Gutenberg eBook of Debating for boys, by William Horton
Foster

This eBook is for the use of anyone anywhere in the United States and
most other parts of the world at no cost and with almost no restrictions
whatsoever. You may copy it, give it away or re-use it under the terms
of the Project Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United States, you
will have to check the laws of the country where you are located before
using this eBook.

Title: Debating for boys

Author: William Horton Foster

Release Date: April 16, 2023 [eBook #70568]

Language: English

Produced by: Charlene Taylor and the Online Distributed Proofreading
             Team at https://www.pgdp.net (This file was produced from
             images generously made available by The Internet
             Archive/American Libraries.)

*** START OF THE PROJECT GUTENBERG EBOOK DEBATING FOR BOYS ***





DEBATING FOR BOYS




                            DEBATING FOR BOYS

10-4. 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? ")

from pathlib import Path
path = Path('user.txt')

path.write_text(name)

10-5. Guest Book:

Write a while loop that prompts users for their name. Collect all the names that are entered, and then write these names to a file called guest_book.txt. Make sure each entry appears on a new line in the file.

while True:
  name = input("What's your first name? Write 'q' any time to quit")
  if name == 'q':
    break
  last = input("What's your last name? Write 'q' any time to quit ")
  if last == 'q':
    break
  
path = Path('guest_book.txt')

if name !='q' and last !='q':
  path.write_text(name,last)

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 ValueError 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.

while True:
  first_number = input("\nFirst number: ")
  if first_number == 'q':
    break
  second_number = input("Second number: ")
  if second_number == 'q':
    break

try:
  answer = int(first_number) + int(second_number)
except ValueError:
  print("You can't add by words and numbers")
else:
  print(answer)

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.

while True:

  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}.")
    break

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.

from pathlib import Path
path1 = Path('cats.txt')
path2 = Path("dogs.txt")


cats = path1.read_text()
dogs = path2.read_text()

billian = cats.splitlines()
kuttay = dogs.splitlines()

# printing in list

for line in billian:
  print(line)

for line in kuttay:
  print(line)
# priting entire file.
billian
kuttay
billi
kalli billi
laal billi
lachechen
kutta
doggy
['lachechen', 'kutta', 'doggy']

Wrap your code in a try-except block to catch the FileNotFound error, and print a friendly message if a file is missing.

try:
  cats = path1.read_text()
  dogs = path2.read_text()
  billian = cats.splitlines()
  kuttay = dogs.splitlines()  

  for line in billian:
    print(line)

  for line in kuttay:
    print(line)

except FileNotFound:
  print("File es folder mein mojood nahi")
billi
kalli billi
laal billi
lachechen
kutta
doggy

Move one of the files to a different location on your system, and make sure the code in the except block executes properly.

path1 = Path('./images/cats.txt')
path2 = Path("dogs.txt")

try:
  cats = path1.read_text()
  dogs = path2.read_text()
  billian = cats.splitlines()
  kuttay = dogs.splitlines()  

  for line in billian:
    print(line)

  for line in kuttay:
    print(line)

except FileNotFoundError:
  print("File es folder mein mojood nahi")
File es folder mein mojood nahi

10-9. Silent Cats and Dogs:

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

path1 = Path('./images/cats.txt')
path2 = Path("dogs.txt")

try:
  cats = path1.read_text()
  dogs = path2.read_text()
  billian = cats.splitlines()
  kuttay = dogs.splitlines()  

  for line in billian:
    print(line)

  for line in kuttay:
    print(line)

except FileNotFoundError:
  print("File es folder mein mojood nahi")
File es folder mein mojood nahi

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’ appears 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 ‘there’. Try counting ‘the’, with a space in the string, and see how much lower your count is.

# We copied text from this link in python.txt

# https://gutenberg.org/cache/epub/70568/pg70568.txt
path1 = Path('python.txt')

boys = path1.read_text()


boys.count('the ')

boys.lower().count('the ')
12