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

Задача 1

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

import random

WORDS=[]
word=""
for i in range(4):
    word=input("Write {} word ".format(i+1))
    WORDS.append(word)
result=''
while WORDS:
    word=random.choice(WORDS)
    WORDS.remove(word)
    result=result+word+' '
print(result)
input("Press Enter to exit")

Задача 2

#Напишите программу «Генератор персонажей» для ролевой игры. Пользователю должно быть
# предоставлено30 пунктов, которые можно распределить между четырьмя характеристиками:
#Сипа, Здоровье, Мудростьи Ловкость. Надо сделать так, чтобы пользователь мог не только
# брать эти пункты из общего «Пупа», но и возвращать их туда из характеристик, которым
# он решит присвоить другие значения

print('Hi! You have 30 points and you can distribute \
them between 4 characteristics \n-Strength\n-Health\n-Wisdom\n-Skill')
table={'Strength':0, 'Health':0, 'Wisdom':0, 'Skill':0}
characteristics=['Strength', 'Health', 'Wisdom', 'Skill']
all_points=30
choose=None
choose_ch=None
while choose!=0:
  print('\n0-Exit\n1-Add points to characteristic\n2-Remove points from characteristic\n3-Look at the list with points')
  choose=int(input('\nYour choice: '))
  if choose==1:
    print('What do you want to change?\n1-Strength\n2-Health\n3-Wisdom\n4-Skill''')
    choose_ch=int(input('\nYour choice: '))
    points = int(input('\nHow many points: '))
    if points<0:
        points=points*(-1)
    x=all_points-points
    while x<0:
        print('You run out of points. Left {} points at all'.format(all_points))
        points = int(input('\nHow many points: '))
        x = all_points - points
    table[characteristics[choose_ch-1]]+=points
    all_points-=points
  if choose==2:
        print('What do you want to change?\n1-Strength\n2-Health\n3-Wisdom\n4-Skill''')
        choose_ch = int(input('\nYour choice: '))
        points = int(input('\nHow many points: '))
        if points>0:
            points=points*(-1)
        y=table[characteristics[choose_ch - 1]]+points
        if y<0:
            table[characteristics[choose_ch - 1]]=0
            all_points+=(-points+y)
        else:
            table[characteristics[choose_ch - 1]] += points
            all_points += points
  if choose==3:
      for characteristic, point in table.items():
          print(characteristic, point)
      print("Left {} spare points".format(all_points))
input('\nPress enter')

Задача 3

'''Напишите программу «Кто твой папа?», в которой пользователь будет вводить имя человека,
 а программа - называть отца этого человека. Чтобы было интереснее, можно «научить»
 программу родственным отношениям среди литературных персонажей, исторических лиц и
 современных знаменитостей. Предоставьте пользователю возможность добавлять,
 заменять и удалять пары «СЫН - отец».'''

menu = ("0 - Exit\n1 - Search father\n2 - Change data\n3 - Delete data\n4 - Add new data")

family = {"Bob":"Dilan", "Mike":"Sam", "Jon Snow":"Rhaegar Targaryen", "Rob Stark":"Ned Stark"}

choice = None
son = ""
father = ""
while choice != 0:
    print(menu)
    choice = int(input("Choose what do you want to do: "))
    if choice == 1:
        son = str(input("Write name: "))
        if son in family:
            print("{}'s father is {}".format(son, family[son]))
        else:
            print("I don't know this person")

    elif choice == 2:
        son = str(input("Write name: "))
        if son in family:
            father = str(input("Write his father's new name: "))
            family[son] = father
            print("{}'s father is {}".format(son, family[son]))
        else:
            print("I don't know this person")

    elif choice == 3:
        son = str(input("Write name: "))
        if son in family:
            del family[son]
            print("Deleted")
        else:
            print("I don't know this person")

    elif choice == 4:
        son = str(input("Write name: "))
        if son in family:
            print("I already have this person")
        else:
            father = str(input("Write his father's name: "))
            family[son] = father
            print("Added")

input("Press Enter to exit")

Задача 4

"""Доработайте программу «Кто твой папа?» так, чтобы можно было, введя имя человека,
узнать, кто его дед. Программа должна по-прежнему пользоваться одним словарем с парами
 «сын - отец». Подумайте, как включить в этот словарь несколько поколений."""

menu = ("0 - Exit\n1 - Search father and grandfather\n2 - Change data\n3 - Delete data\n4 - Add new data")

family = {"Bob":{"Sam":"Ben"}, "Luke":{"Anakin":"The Force"},\
          "Jon Snow":{"Rhaegar Targaryen":"Aerys II Targaryen "},\
                      "Robb Stark":{"Ned Stark":"Rickard Stark "}}

choice = None
son = ""
father = ""
dad=[]
g_dad=''
while choice != 0:
    print(menu)
    choice = int(input("Choose what do you want to do: "))
    if choice == 1:
        son = str(input("Write name: "))
        if son in family:
            dad = list(family[son].keys())
            g_dad = family[son][dad[0]]
            print("{}'s father is {} and grandfather is {}".\
                  format(son, dad[0], g_dad))
        else:
            print("I don't know this person")

    elif choice == 2:
        son = str(input("Write name: "))
        if son in family:
            father = str(input("Write his father's new name: "))
            g_dad = str(input("Write his grandfather's new name: "))
            family[son] = {father:g_dad}
            print("{}'s father is {} and grandfather is {}".\
                  format(son, father, family[son][father]))
        else:
            print("I don't know this person")

    elif choice == 3:
        son = str(input("Write name: "))
        if son in family:
            del family[son]
            print("Deleted")
        else:
            print("I don't know this person")

    elif choice == 4:
        son = str(input("Write name: "))
        if son in family:
            print("I already have this person")
        else:
            father = str(input("Write his father's name: "))
            g_dad = str(input("Write his grandfather's new name: "))
            family[son] = {father: g_dad}
            print("Added")

input("Press Enter to exit")

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

Комментарии

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

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

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

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