Майкл Доусон - Программируем на Python 4 глава

Задача 1

#Напишите программу, которая бы считала по просьбе пользователя. Надо позволить
# пользователю ввести начало и конец счета, а также интервал между называемыми целыми числами.

print('Hi! I will count for you!')
first=int(input('Please write the first number: '))
last=int(input('and the last: '))
gap=int(input('ang gap finally: '))
for i in range(first, last+1, gap):
    print(i, end=' ')
input("\nPress Enter to exit")

Задача 2

#Напишите программу, которая принимала бы текст из пользовательского ввода и
# печатала этот текст на экране наоборот.

word=input('Write something: ')
while word:
    print(word[len(word)-1], end='')
    word=word[:(len(word)-1)]
input("\nPress Enter to exit")

Задача 3

#Доработайте игру «Анаграммы» так, чтобы к каждому слову полагалась подсказка.
#  Игрок должен получать право на подсказку в том случае, если у него нет никаких
# предположений. Разработайте систему начисления очков, по которой бы игроки,
# отгадавшие слово без подсказки, получали больше тех, кто запросил подсказку.

import random

WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
word = random.choice(WORDS)
correct = word
jumble = ""
while word:
    position = random.randrange(len(word))
    jumble += word[position]
    word = word[:position] + word[(position + 1):]

print(
"""
           Welcome to Word Jumble!
       
   Unscramble the letters to make a word.
(Press the enter key at the prompt to quit.)
"""
)
print("The jumble is:", jumble)
guess = input("\nYour guess: ")
hint=''
x=0
score=0

while guess != correct:
    print("Sorry, that's not it.")
    hint = input('If you want a hint, tap y, else Enter ')
    if hint.lower()=="y":
          x=random.randrange(len(correct))
          print("The {} letter is {}".format(x, correct[x]))
          score-=1
    else:
        score+=1
    guess = input("Your guess: ")
   
   
if guess == correct:
    print("That's it!  You guessed it!\n")
    score+=1
    print("your score ", score)

print("Thanks for playing.")

input("\n\nPress the enter key to exit.")

Задача 4

#Создайте игру, в которой компьютер выбирает какое-либо слово, а игрок должен его отгадать.
#  Компьютер сообщает игроку, сколько букв в слове, и дает пять попыток узнать, есть
# ли какая-либо буква в слове, причем программа может отвечать только «Да» и «Her».
# Вслед за тем игрок должен попробовать отгадать слово.

import random

WORDS=('pie', 'cat', 'hard', 'mouse', 'computer')
word= random.choice(WORDS)
correct=word
print('Welcome! Try to guess a word! You have only 5 tries!')
print('\nWord consist of {} letters'.format(len(word)))
guess=''
guessed=''
hint=5

while hint:
    guess=input('\nask any letter ')
    if guess.lower() in word:
        print('yes, it is in there ')
        guessed+=guess
        print('\nnow you have guessed these letters: ', guessed)
        hint-=1
    else:
        print('\nsorry, it is not there')
        hint-=1
        print('\nnow you have guessed these letters: ', guessed)
guess=input('\nnow try to guess the whole word: ')
if guess.lower()==correct:
    print('\nYou won! It was ', correct)
   
else:
    print('\nYou lose! It was ', correct)
input('\nPress enter')

Michael Dawson
Python
Programming
for the Absolute Beginner
Зrd Edition
4 chapter

Комментарии

  1. Спасиб, помог твой пример...

    ОтветитьУдалить
  2. В 3,4 задаче используются какието функции, которых ты не знаешь при прохождении 4-х глав, не очень пример соответствует решению выходит

    ОтветитьУдалить

Отправить комментарий

Популярные сообщения из этого блога

Майкл Доусон - Программируем на Python 8 глава задача 1

Майкл Доусон - Программируем на Python 3 глава