Python Homework Help, Project Help, Python Assignment Solution

Python is one of the popular languages that are widely used by many industries for high level programming. It supports a variety of programming paradigms such as functional programming and object-oriented styles. This has made Python to be offered as a coursework in most universities all around the world. We at ProgrammingHomeworkHelp.com provide help in programming in python to students seeking help with their Python tasks. We will help you understand why python is used as a scripting language in different non-scripting contexts.

ProgrammingHomeworkHelp.com is the right place for you to get help with python homework. We have all the tools required to provide you with an exceptional computer programming help online. Our experts can work with all the arrays of systems used such as RPython, PyPy CPython and Jython and all the cross-platform systems available. We guarantee top-notch solutions for your python homework and assignments

Python is a language that is very suitable for beginners, and is used in a wide variety of fields, from data processing, web sites, biology. If you have a Python assignment please make sure you specify which version of Python (Python 2 and Python 3 have some differences, and there is also JES which is Python running on the Java Virtual Machine, there is also IPython notebooks which allows you to mix html and code together). One advantage of Python is that it has a huge library of packages, so it can handle plotting graphs (with Matplotlib), websites (Django, Flask, etc), natural language (NLTK).

Below you can see a sample Python home work, I’ve had to provide multiple solutions to assignments, and can alter the solution to match your style.

What is Python Programming Language?

Although Python programming language has similar qualities with PERL, it has more object-oriented functions and is more powerful. Python is an interactive, general-purpose and high level language. It was introduced in the late 1980s to help combat coding flaws. The language allows programmers to express their concepts in just a few lines of code.

Python was first released in 1991 after being created by Guido Van Rossum. Python programming language uses a significant whitespace to emphasize its code readability. It also supports many other paradigms such as design by contract and logic programming via extensions. Python has a reference counting and a cycle-detecting garbage collector to help manage its memory. During program execution, a feature known as late binding or dynamic name resolution is used to bind the method and variable names. Python programming language is designed to be highly extensible and programmable interfaces can be added to existing applications.

Equipped with complex dynamic features and automated memory management, students may find it hard grasping the basic concepts of Python. We are here with an outstanding python homework help that will clear all your doubts in programming.

Many programming languages are influenced by the design philosophy of Python. Our python programming assignment help will help you understand the beneficial aspects of all these languages. An assignment that is not well researched and inaccurate will definitely lead to low marks. Do not leave your career at stake by struggling with complex Python tasks. Our python programming assignment help platform enhances the computation skills of students while at the same time assuring them top grades. We only provide high-quality write-ups that will impress any programming professor.

We know the stress you go through everyday trying to find a site with an efficient work-process and the expertise to solve intricate Python assignments. Well, we are happy to inform you that we are the best in the business. We have been sorting the exam blues of students for years now. We only hire proficient and highly qualified python programming tutors to help you with all your tasks. Our experts are rigorously tested and have proved beyond any reasonable doubt that they have extensive skills and techniques needed to provide you with an impeccable online python help.

Python is very popular because it favors simple and less cluttered grammar. It rejects exuberant syntax philosophy “there is more than one way to do it” that is applied in PERL in favor of “there should be one preferred and obvious way to do it”. Signing up for our python programming assignments help will help you avoid “premature optimization” and guide you on why patches to non-critical parts of CPython should be rejected. Programmers can move time-critical functions to extension modules which are written in languages such as C or use a Just-in-time compiler- PyPy – when they want Python to execute faster. They can also use Cython to translate python scripts into C to make direct C-level API calls into the Python Interpreter.

The aim of the developers of Python was to make it fun to use and easily readable. However, most programming students still make errors while writing the codes. We offer help with python error service that can clean your codes for you and ensure your code is accurate. We will help you understand the special tags and regulations that are used in the Python language. Python does not use curly brackets to delimit block like in other languages. It also uses English keywords instead of punctuations. Failing to understand these rules will make your codes return errors. Avail our python programming homework help now and learn from the best.

The assignment code in python is being provided by highly qualified and accomplished experts in computer programming. Our Python live help is the most reliable computer programming homework assistance facility on the World Wide Web. The assignment code in python is being provided by highly qualified and accomplished experts in computer programming. Our Python live help is the most reliable computer programming homework assistance facility on the World Wide Web.

JES based questions

Question 1

A programmer has intended to write a function that draws a gradient across the screen. :

def Q1SE():
    width=200
    height=100
    image=makeEmptyPicture(width,height)
    for x in range(height):
        for y in range(width):
            p = getPixel(image, x, y)
            col = makeColor(x, x, y)
            setColor(p, col)
    show(image)

Can the above code achieve the intended outcome?

If yes, describe where the brightest pixel would be found, in plain English:

Answer:

WRONG ANSWER SINCE IT HAS A BUG

The bottom right hand corner.

If no, state whether the problem is a syntax error or if it is an error in the logic. Give a short description in plain English:

Answer:

It uses x for height and y for width, but width is more than height so it will get an error. Changing the for x line and for y line, so for y in range(height), and for x in range(width) fixes the bug.

Question 2

In plain English, what is the result when the following function is run?

def Q2SE():
    width=200   
    height=200
    image=makeEmptyPicture(width,height)
    for p in getPixels(image):
        x = getX(p) - 100
        y = getY(p) - 100
        if x * x + y * y < 10000:
        setColor(p, blue)
    show(image)

Your description must be short and in “plain English”. I.e. explain the effect to someone who does not understand programming. Do not translate individual lines of code.Write your answer below:

Answer:

It draws a solid blue circle at the middle of the screen.

Question 3

Consider the following function that produces an image with a particular pattern:

def Q4SE():
    pic = makePicture("c:\course\JES-week3\lena.bmp")
    for p in getPixels(pic):
        x = getX(p) / 16 % 2
        y = getY(p) / 16 % 2
        if x ^ y:
            setGreen(p, 255)
        else:
            setRed(p, 255)
    show(pic)

 

a. What is the output of this function? Please write your shortest answer that explains everything in “plain English” to someone who is not a programmer.

Write your answer below:

Answer:

It makes a chess board style pattern over the picture, each square is 16 pixels wide.
The squares are tinted red or green.

b. Currently, the function has three limitations: (1) it works only on the file lena.bmp,

(2) there is no control over size of the pattern and (3) the result is only shown on the screen.

Your task is to overcome the above limitations by re-writing this function in a more general form. The function must now take 4 parameter inputs as follows: pattern(picture, size, color1, color2)

Your code must meet the following requirements:

  1. Your code must work correctly for images of any size that is provided via the “picture” parameter.
  2. The pattern size and colors are now provided via remaining 3 parameters. Their values are provided as a color. You may assume that no other values will be provided.
  3. Instead of displaying the result on the screen, your function must return it to the
    calling function.
  4. There is no need to perform input/data validation on any of the parameters.

Write your answer below (show your code indentation clearly):

Answer:

def pattern(pic, size, color1, color2):
    for p in getPixels(pic):
        x = getX(p) / size % 2
        y = getY(p) / size % 2
        r = getRed(p)
        g = getGreen(p)
        b = getBlue(p)
        if x ^ y:
            color = color1
        else:
            color = color2
        r += color.getRed()
        g += color.getGreen()
        b += color.getBlue()
        setRed(p, r)
        setGreen(p, g)
        setBlue(p, b)
    return pic

This Python assignment that illustrates the help with Python problems we can solve.

Object Oriented Language Concepts Using Python

Class Rectangle

Create a class named ‘Rectangle’ with the following attributes and methods (sample run for each method included):

1: Each instance should have an x, y, width, and height attributes.

2: You should be able to pass the attributes when creating the rectangle as follows, (where x=5, y=10, width=50, height=100 in that order):

r = Rectangle(5, 10, 50, 100)

3: Create a method that returns the rectangle as a string (hint: implement str ). For a rectangle object with attribute values x=5, y=10, width=50, height=100, it should return the string “Rectangle(5, 10, 50, 100)”.

>>>r2 = Rectangle(5, 10, 50, 100) 
>>>print(r2)
Rectangle(5, 10, 50, 100)

4: Create a method called right that gets the value of the right edge of the rectangle. It should take no arguments:

>>>r3 = Rectangle(3, 5, 10, 20)
>>>r3.right()
13
>>>r4 = Rectangle(12, 10, 72, 35)
>>>r4.right()
84

5: Create a method called bottom that gets the value of the bottom edge of the rectangle.

>>>r5 = Rectangle(5, 7, 10, 6)
>>>r5.bottom()
13
>>>r5.y += 12 
>>>r5.bottom()
25

6: Create a method called size that returns the width and height of your rectangle.

>>>r6 = Rectangle(1, 2, 3, 4) 
>>>r6.size()
(3, 4)

7: Create a method called position that returns the x and y coordinates of your rectangle.

>>>r6.position()
(1, 2)

8: Create a method called area that returns the area of your rectangle.

>>>r6.area()
12

9: Create a method called expand that takes an offset value and returns a copy of the rectangle expanded with offset in all directions.

>>>r = Rectangle(30, 40, 100, 110) 
>>>r
Rectangle(30, 40, 100, 110)
>>>r1 = r.expand(offset=3) 
>>>r1
Rectangle(27, 37, 106, 116)

The original rectangle should not be modified.
>>>r
Rectangle(30, 40, 100, 110)

Negative values should return a shrunken rectangle.
>>>r.expand(-5)
Rectangle(35, 45, 90, 100)

Create a method called contains_point that takes coordinates x and y as parameters and returns True if the point in inside (or on the edge) of the rectangle and False otherwise.

>>>r = Rectangle(30, 40, 100, 110)
>>>r.contains_point(50, 50)
True 
>>>r.contains_point(30,40)
True
>>>r.contains_point(130, 150)
True
>>>r.contains_point(131, 50)
False
>>>r.contains_point(0,0)
False

Solution:

class Rectangle:
    x = 0
    y = 0
    width = 0
    height = 0

    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.width = w
        self.height = h

    def __str__(self):
        return "Rectangle(%d, %d, %d, %d)" % (self.x, self.y, self.width, self.height)

    def right(self):
        return self.x + self.width

    def bottom(self):
        return self.y + self.height

    def size(self):
        return (self.width, self.height)

    def position(self):
        return (self.x, self.y)

    def area(self):
        return self.width * self.height

    def expand(self, offset):
        return Rectangle(self.x - offset, self.y - offset, self.width + 2 * offset, self.height + 2 *  offset)

    def contains_point(self, x, y):
        return (x >= self.x and x <= self.x + self.width and y >= self.y and y <= self.y + self.height)

if __name__ == '__main__':
    # test code
    r2 = Rectangle(5, 10, 50, 100)
    print (r2)

    r3 = Rectangle(3, 5, 10, 20)
    print (r3.right())

    r4 = Rectangle(12, 10, 72, 35)
    print (r4.right())

    r5 = Rectangle(5, 7, 10, 6)
    print (r5.bottom())

    r5.y += 12
    print (r5.bottom())

    r6 = Rectangle(1, 2, 3, 4)
    print (r6.size())

    print (r6.position())
    print (r6.area())

    r = Rectangle(30, 40, 100, 110)

    print (r)

    r1 = r.expand(offset = 3)
    print (r1)
    print (r)

    print (r.expand(-5))

    r = Rectangle(30, 40, 100, 110)
    print (r.contains_point(50, 50))
    print (r.contains_point(30, 40))
    print (r.contains_point(130, 150))
    print (r.contains_point(131, 50))
    print (r.contains_point(0, 0))

This is an example Python assignment. We can custom design the solutions to your skill level (so advanced, intermediate or basic), just let us know.

Filtering a dictionary

Write a function that takes the name of a dictionary file that contains 1 word per line, and the
minimum and maximum word lengths. Your function will return (a list of) the words from the
original dictionary file whose length is within the user-specified bounds. So for instance,
if the min is 3 and max is 7, then only words with length >= 3 and length <= 7 will be returned
in the list.

Some popular word lists can be found at http://www.puzzlers.org/dokuwiki/doku.php?id=solving:wordlists:about:start&s=ospd,
here are just a few you may want to try:

ospd.txt – official Scrabble player’s list (79,338 entries)

enable1.txt – (172,823 entries)

web2.txt – Webster’s New International Dictionary, 2nd ed. (234,936 entries)

Gematria (Kabbalistic calculator)

“Gematria is the act of assigning numeric values to letters in an alphabet”. Once each letter is assigned
a value you can compute the value of a word or phrase by simply summing the values of each letter in the
word/phrase. Using a mapping of a=1, b=2, c=3, …, z=26, “Phil” has a value of P=16 + h=8 + i=9 + l=12 == 45.
Write a function that takes a word and the name of a dictionary file, and then returns (a list of) all the
entries from the dictionary that gematrically match the given word. Note that the case of a letter does
not change its value.

You can use the same input files you used for filtering a dictionary.

CreditCheck

The last digit of a credit card number is the check digit, which protects against transcription errors
such as an error in a single digit or switching two digits. The following method is used to verify actual
credit card numbers but, for simplicity, we will describe it for numbers with 8 digits instead of 16:
Starting from the rightmost digit, form the sum of every other digit. For example, if the credit card number
is 4358 9795, then you form the sum 5 + 7 + 8 + 3 = 23.

Double each of the digits that were not included in the preceding step. Add all digits of the resulting numbers.
For example, with the number given above, doubling the digits, starting with the next-to-last one, yields 18 18 10 8.
Adding all digits in these values yields 1 + 8 + 1 + 8 + 1 + 0 + 8 = 27.

Add the sums of the two preceding steps. If the result is evenly divisible by 10, the number is valid. In our
case, 23 + 27 = 50, so the number is valid

Write a function that implements this algorithm. The function should take an 8-digit
number, and returns True if the number is valid and False otherwise.

Solution:

def readwords(filename, minlen, maxlen):
    words = []
    with open (filename, "r") as fin:
        for word in fin:
            # remove \n and skip empty line
            word = word.strip()
            if not word: continue
            if minlen <= len(word) <= maxlen:
                words.append(word)
    return words

def gematria(match, filename):
    words = []
    # use lambda function to transfer letter to number
    transfer = lambda c: \
            ord(c) - ord('A') + 1 if c <= 'Z' else ord(c) - ord('a') + 1

    # calculate numeric values of the given word
    g1 = sum([transfer(x) for x in match])

    with open (filename, "r") as fin:
        for word in fin:
            # remove \n and skip empty line
            word = word.strip()
            if not word: continue
            g2 = sum([transfer(x) for x in word])
            if g1 == g2:
                words.append(word)
    return words

def creditcard(number):
    # transfer number to a string of 8 digits
    number = "%08d" % (number)
    # reverse the string
    number = number[::-1]
    # start from the rigtmost(leftmost in the reversed string)
    # form the sum of every other
    s1 = sum([int(x) for x in number[0::2]])
    # double the remain and add digit together
    s2 = 0
    for x in number[1::2]:
        x = 2 * int(x)
        s2 += x if x < 10 else (x - 10) + 1
    # check whether the sum is evenly divisible by 10
    # print (s1, s2)
    return (s1 + s2) % 10 == 0

if __name__ == '__main__':
    # print (readwords("web2.txt", 3, 7))
    # gematria("Theresa", "web2.txt")
    creditcard(43589795)

As a demonstration of a Python project, this demonstrates the type of solution we can provide.

Simplified Texas Hold′em Poker Game

Problem:

This assignment focuses on the design, implementation and testing of a Python program which uses classes to solve the problem described below. Note: you are using a class we provide; you are not designing a class.

Background

The goal of this project is to gain practice with use of classes and creating functions. You will design and implement a Python program which plays simplified Texas Hold′em Poker.

The program should deal two cards to two players (one card to each player, then a second card to each player), and then five community cards which players share to make their hands. A poker hand is the best five cards from the community cards plus the player′s cards (i.e., best 5 out of 7 cards total). The goal
of this assignment is to find the category of each player′s hand and determine the winner.

The rules of this game are relatively simple and you can find information about the game and about the poker hands in the links below. Keep in mind that you will only find the category of the hands and all nine cards can be dealt at once (a real poker game deals cards in stages to allow for betting, but we aren′t betting).

http://en.wikipedia.org/wiki/Texas_holdem
http://en.wikipedia.org/wiki/Poker_hands

The categories in order from lowest to highest are:

  • High card
  • 1 pair
  • 2 pair
  • 3 of a kind
  • straight
  • flush
  • full house
  • 4 of a kind
  • straight flush.

You will not find a player′s hand′s value, but just the category of the hand.

It is a tie if both players have hands in the same category. That is, if both of them have straights, it is considered a tie no matter who has the higher straight.

Our game is simplified in two ways:

  1. We only compare categories to determine the winner, not the value of the hands. For example, in a real poker game the winner of hands with exactly one pair would be determined by which pair had the highest card rank. That is, a pair of 10s wins over a pair of 3s. In our game, two
    hands with exactly one pair is considered a tie with no consideration given to the card ranks.
  2. The Card class ranks an Ace as the lowest card in a suit; whereas traditional poker ranks an Ace as highest. For simplicity, we will keep Aces as the lowest ranked card because we are only comparing categories not values. In particular, the cards 10h, Jh, Qh, Kh, Ah are not considered
    to make a straight in our game (they would under normal poker rules).

Specifications

  1. Your program will use the Card and Deck classes found in the file named cards.py. You may not modify the contents of that file: we will test your project using our copy of cards.py. We have included a cardsDemo.py program to illustrate how to use the Card and Deck classes.
  2. Your program will be subdivided into meaningful functions. Use a function for each category (except that “high-card” doesn′t need a function). See hints below.
  3. Your program will display each player′s dealt cards, the community cards, and announce the winner of the hand. Also, your program will display the winning combination (or either of the winning combinations, if a tie) as well as the category of the winning hand (see sample output
    below). For example, if the winning combination is “four-of-a-kind”, those four cards will be displayed; the fifth card in the hand will not be displayed. The display will be appropriately labeled and formatted.
  4. After each run, the program will prompt the user if they want to see another hand: {“Do you want to continue: y or n”}. The program should continue if user enters ‘y’ or ‘Y’; otherwise, the program should halt. Also, if there are fewer than 9 cards left in the deck, the program should halt. Do not shuffle between hands; only shuffle at the beginning of the program.
  5. Using dictionaries in this assignment is very useful as you can find how many cards have the same suit, or how many of them have the same rank. Most of my functions used a dictionary that had rank as the key, so I created a separate function to build such a dictionary from a hand.

Hints

  1. There are 9 categories of hands. For each category (except high-card), I wrote a function that would take as an argument a list of 7 cards and return either a sub-list of cards that satisfied that category or an empty list. That design let me use the functions in Boolean expressions since an
    empty list evaluates to False whereas a non-empty list evaluates to True. Returning a list of cards also allowed me to use functions within functions, e.g., a straight flush must be a flush. Returning a list of cards also made testing easier because I could see not only that the function
    had found a combination of that type, but I also could easily check that it was correct. By the way, the function to find a straight was the hardest function to write.
  2. Finding a winner is simple: start with the highest category and work your way down the categories in a cascade of “if” and “elif” statements. The result is a long, but repetitive structure. (You do not need to check all possible combinations of hands because you are only trying to find the highest category that a hand fits.)
  3. Think strategically for testing. Custom build a set of hands for testing by creating particular cards, e.g. H1 = [5c, 2c, 5h, 4s, 3d, 2h, 5d] can be used to test for a full house (I had to create each card first, e.g. c1 = cards.Card(5,1) to create the 5c card in H1. It took many lines
    to create the testing hands, but once built they proved useful.) Test each category function separately using the custom hands you created for testing. For example,
    result = full_house(H1) should yield a result [5c, 5h, 5d, 2c, 2h].
  4. I found dictionaries useful within functions. Sometimes using the rank as key worked best; other times using the suit as key was best.
  5. In order for sort() and sorted() to work on any data type the less-than operation must be defined. That operation is not defined in the Cards class so neither sort() nor sorted() work on Cards. (We tried to make the Cards class as generic as possible to work with a wide variety of card games, and the ordering of cards considering both rank and suit varies across card games.)

Students from various corners of the world come to us with request like do my Python homework because we have established ourselves as one of the most reliable homework service provider on the web.  The Python assignment questions that we have gathered in our repository is an anthology collected from the question papers of the finest universities of the world. The solution to Python homework assignments offered by us is thorough and all inclusive in all respects. Students can take the advantage of our online Python help chat which is an indelible offering and a part of our services.

Students from various corners of the world come to us with request like do my Python homework because we have established ourselves as one of the most reliable homework service provider on the web.  The Python assignment questions that we have gathered in our repository is an anthology collected from the question papers of the finest universities of the world. The solution to Python homework assignments offered by us is thorough and all inclusive in all respects. Students can take the advantage of our online Python help chat which is an indelible offering and a part of our services.

Sample Output

Let's play poker!
Community cards: [9d, 3d, 6s, 2s, 2d]
Player 1: [4h, 5c]
Player 2: [9c, 5h]
Player 1 wins with a straight: [2s, 3d, 4h, 5c, 6s]
Do you wish to play another hand?(Y or N) y

----------------------------------------

Let's play poker!
Community cards: [Ks, 6d, Kc, 5s, 9h]
Player 1: [4c, 10s]
Player 2: [7s, Qc]
TIE with one pair: [Ks, Kc]
Do you wish to play another hand?(Y or N) y

----------------------------------------

Let's play poker!
Community cards: [Jc, 8h, Jd, Js, 3c]
Player 1: [3h, 4d]
Player 2: [As, 7c]
Player 1 wins with a full house: [Jc, Jd, Js, 3h, 3c]
Do you wish to play another hand?(Y or N) y

----------------------------------------

Let's play poker!
Community cards: [Qs, 4s, 8d, 2h, Qd]
Player 1: [7d, 6c]
Player 2: [2c, 8s]
Player 2 wins with two pairs: [8s, 8d, 2c, 2h]
Do you wish to play another hand?(Y or N) y

----------------------------------------

Let's play poker!
Community cards: [10h, 7h, 10d, Kh, Ah]
Player 1: [9s, Ad]
Player 2: [Ac, 3s]
TIE with two pairs: [10h, 10d, Ad, Ah]
Deck has too few cards so game is done.

Solution:

cards.py

import random    # required for shuffle method of Deck

class Card(object):
    ''' Suit and rank are ints, and index into suit_list and rank_list.
        Value is different from rank: for example face cards are equal in value (all 10)
    '''
    # Use these lists to map the ints of suit and rank to nice words.
    # The 'x' is a place holder so that index-2 maps to '2', etc.
    suit_list = ['x','c','d','h','s']
    rank_list = ['x', 'A', '2', '3', '4', '5', '6', '7', '8', '9', '10','J', 'Q', 'K']

    def __init__(self, rank=0, suit=0):
        ''' Rank and suit must be ints. This checks that they are in the correct range.
            Blank card has rank and suit set to 0.
        '''
        if type(suit) == int and type(rank) == int:
            # only good indicies work
            if suit in range(1,5) and rank in range(1,15):
                self.__suit = suit
                self.__rank = rank

            else:
                self.__suit = 0
                self.__rank = 0
        else:
            self.__suit = 0
            self.__rank = 0
    def get_rank(self):
        return self.__rank

    def get_suit(self):
        return self.__suit

##    These two "set" methods are for testing: turn them on for testing and
##    and then turn off.  These allow you to change a card's rand and suit so
##    you can test situations that might occur infrequently.
##
##    def set_rank(self, rank):
##        self.__rank = rank
##
##    def set_suit(self, suit):
##        self.__suit = suit

    def get_value(self):
        ''' Face cards return 10, the rest return their rank values. Aces are low.
        '''
        # ternary expression:
        return self.__rank if self.__rank < 10 else 10

    def equal_suit(self, other):
        '''Returns True if suits are equal.'''
        return self.__suit == other.__suit

    def equal_rank(self, other):
        '''Returns True if ranks are equal.'''
        return self.__rank == other.__rank

    def equal_value(self, other):
        '''Returns True if values are equal.'''
        return self.get_value() == other.get_value()

    def __str__(self):
        ''' Called by print() so you can print a card, just like any other data structure.
        '''
        # Uses rank to index into rank_list of names; uses suite to index into suit_list of names.
        #print(self.__rank)
        return "{:s}{:s}".format((self.rank_list)[self.__rank], (self.suit_list)[self.__suit])

    def __repr__(self):
        ''' This method is called if you simply enter a card name in the shell.
            It simply calls, the same method that prints a card.
        '''
        return self.__str__()

class Deck(object):
    ''' Deck of cards, implemented as a list of card objects.
        The last card in the deck (list) is the top of deck.
    '''
    def __init__(self):
        self.__deck=[Card(rank,suit) for suit in range(1,5) for rank in range(1,14)]

    def shuffle(self):
        '''Shuffle the deck using a call to random.'''
        random.shuffle(self.__deck)

    def deal(self):
        '''Return the top card from the deck (only if the deck is not empty).'''
        # ternary expression
        return self.__deck.pop() if len(self.__deck) else None

    def cards_count(self):
        '''Returns the number of cards in the deck.'''
        return len(self.__deck)

    def is_empty(self):
        '''Returns True if the deck is empty.'''
        return len(self.__deck) == 0

    def __str__(self):
        ''' Print a deck, simple but messy!
        '''
        return ','.join([str(card) for card in self.__deck])

    def __repr__(self):
        ''' Messy print deck, if you enter a deck's name in the shell.
        '''
        return self.__str__()

    def pretty_print(self, column_max=10):
        ''' Column-oriented printing of a deck.
        '''
        for index,card in enumerate(self.__deck):
            if index%column_max == 0:  # at final column so print a carriage return
                print()
            print("{:4s}".format(card), end='')
        print()
        print()

cardsDemo.py

import cards
''' The basic process is this:
    1) You create a Deck instance, which is filled (automatically) with 52 Card instances
    2) You can deal those cards out of the deck into hands, each hand a list of cards
    3) You then manipulate cards as you add/remove them from a hand
'''
my_deck = cards.Deck()
print("======messy print a deck=====")
print(my_deck)

print("======pretty print a deck=====")
my_deck.pretty_print()

my_deck.shuffle()
print("======shuffled deck=====")
my_deck.pretty_print()

a_card = my_deck.deal()
print("Dealt card is:",a_card)
print('How many cards left:',my_deck.cards_count())

print("Is the deck empty?",my_deck.is_empty())

# deal some hands and print
hand1_list=[]
hand2_list=[]
for i in range(5):
    hand1_list.append(my_deck.deal())
    hand2_list.append(my_deck.deal())

print("\nHand 1:", hand1_list)
print("Hand 2:", hand2_list)
print()

# take the last card dealt out of each hand
last_card_hand1 = hand1_list.pop()
last_card_hand2 = hand2_list.pop()
print("Hand1 threw down",last_card_hand1, ", Hand2 threw down", last_card_hand2)
print("Hands are now:",hand1_list, hand2_list)

# check the compares
if last_card_hand1.equal_rank(last_card_hand2):
    print(last_card_hand1, last_card_hand2, "of equal rank")
elif last_card_hand1.get_rank() > last_card_hand2.get_rank():
    print(last_card_hand1, "of higher rank than",last_card_hand2)
else:
    print(last_card_hand2, "of higher rank than",last_card_hand1)

if last_card_hand1.equal_value(last_card_hand2):
    print(last_card_hand1, last_card_hand2, "of equal value")
elif last_card_hand1.get_value() > last_card_hand2.get_value():
    print(last_card_hand1, "of higher value than",last_card_hand2)
else:
    print(last_card_hand2, "of higher value than",last_card_hand1)

if last_card_hand1.equal_suit(last_card_hand2):
    print(last_card_hand1,'of equal suit with',last_card_hand2)
else:
    print(last_card_hand1,'of different suit than',last_card_hand2)

# a foundation, a list of lists. 4 columns in this example
foundation_list = [[],[],[],[]]
column = 0
while not my_deck.is_empty():
    foundation_list[column].append(my_deck.deal())
    column += 1
    if column % 4 == 0:
        column = 0
for i in range(4):
    print("foundation",i,foundation_list[i])

Solution
import cards

def get_one_pair(cards):
    # sort the cards by their ranks
    cards.sort(key=lambda card: card.get_rank())

    # check each possibility
    for start in range(len(cards) - 2 + 1):
        if cards[start].get_rank() == cards[start + 1].get_rank():
            return cards[start:start+2]
    return []

def get_two_pair(cards):
    one_pair = get_one_pair(cards)
    if one_pair: # find one pair, remove them from the cards, then try to find another pair
        remaining = [c for c in cards if c not in one_pair]
        another_pair = get_one_pair(remaining)
        if another_pair:
            one_pair.extend(another_pair)
            return one_pair
    return []

def get_straight_flush(cards):
    # sort the cards by their ranks
    cards.sort(key=lambda card: card.get_rank())

    # check each possibility
    for start in range(len(cards) - 5 + 1):
        end = start + 1
        while end < len(cards):
            if cards[end].get_suit() != cards[end - 1].get_suit(): # not the same suit
                break
            if cards[end].get_rank() - cards[end - 1].get_rank() != 1: # not continuous rank
                break
            end = end + 1
        if end - start >= 5: # found
            return cards[start:start + 5]
    return []

def get_four_of_a_kind(cards):
    # sort the cards by their ranks
    cards.sort(key=lambda card: card.get_rank())

    # check each possibility
    for start in range(len(cards) - 4 + 1):
        if cards[start].get_rank() == cards[start + 3].get_rank():
            return cards[start:start+4]
    return []

def get_three_of_a_kind(cards):
    # sort the cards by their ranks
    cards.sort(key=lambda card: card.get_rank())

    # check each possibility
    for start in range(len(cards) - 3 + 1):
        if cards[start].get_rank() == cards[start + 2].get_rank():
            return cards[start:start+3]
    return []

def get_full_house(cards):
    three = get_three_of_a_kind(cards)
    if three: # find the three, remove them from the cards, then try to find one pair
        remaining = [c for c in cards if c not in three]
        pair = get_one_pair(remaining)
        if pair:
            three.extend(pair)
            return three
    return []

def get_flush(cards):
     # sort the cards by their suit
    cards.sort(key=lambda card: card.get_suit())

    # check each possibility
    for start in range(len(cards) - 5 + 1):
        if cards[start].get_suit() == cards[start + 4].get_suit():
            return cards[start:start+5]
    return []

def get_straight(cards):
    # sort the cards by their ranks
    cards.sort(key=lambda card: card.get_rank())

    # check each possibility
    for start in range(len(cards) - 5 + 1):
        end = start + 1
        while end < len(cards):
            if cards[end].get_rank() - cards[end - 1].get_rank() != 1: # not continuous rank
                break
            end = end + 1
        if end - start >= 5: # found
            return cards[start:start + 5]
    return []

# some test cases
def test():
    c = [cards.Card(1, 1), cards.Card(7, 1), cards.Card(6, 1), cards.Card(8, 1), cards.Card(9, 1), cards.Card(10, 1), cards.Card(3, 1)]
    print (get_straight_flush(c))
    c = [cards.Card(1, 1), cards.Card(7, 1), cards.Card(6, 2), cards.Card(8, 1), cards.Card(9, 1), cards.Card(10, 2), cards.Card(11, 1)]
    print (get_straight_flush(c))

    c = [cards.Card(1, 1), cards.Card(1, 2), cards.Card(1, 3), cards.Card(1, 4), cards.Card(9, 1), cards.Card(10, 2), cards.Card(11, 1)]
    print (get_four_of_a_kind(c))
    c = [cards.Card(3, 1), cards.Card(1, 2), cards.Card(1, 3), cards.Card(1, 4), cards.Card(9, 1), cards.Card(10, 2), cards.Card(11, 1)]
    print (get_four_of_a_kind(c))
    print (get_three_of_a_kind(c))
    c = [cards.Card(3, 1), cards.Card(3, 2), cards.Card(1, 3), cards.Card(1, 4), cards.Card(9, 1), cards.Card(10, 2), cards.Card(11, 1)]
    print (get_two_pair(c))
    print (get_one_pair(c))

    c = [cards.Card(3, 1), cards.Card(3, 2), cards.Card(1, 3), cards.Card(1, 1), cards.Card(9, 1), cards.Card(10, 1), cards.Card(11, 1)]
    print (get_flush(c))

    c = [cards.Card(1, 1), cards.Card(7, 2), cards.Card(6, 1), cards.Card(8, 1), cards.Card(9, 1), cards.Card(10, 1), cards.Card(3, 1)]
    print (get_straight(c))

    c = [cards.Card(1, 1), cards.Card(1, 2), cards.Card(1, 3), cards.Card(8, 1), cards.Card(9, 1), cards.Card(10, 1), cards.Card(8, 2)]
    print (get_full_house(c))
    c = [cards.Card(1, 1), cards.Card(1, 2), cards.Card(2, 3), cards.Card(8, 1), cards.Card(9, 1), cards.Card(10, 1), cards.Card(8, 2)]
    print (get_full_house(c))
    print (get_two_pair(c))

# this function tries to get the cards for each player according to the category
# the will call get_straight_flush, get_four_of_a_kind, and etc, based on the value of category
# the result is returned in a tuple
def get(player1, player2, category):
    if category == 'straight flush':
        return (get_straight_flush(player1), get_straight_flush(player2))
    if category == '4 of a kind':
        return (get_four_of_a_kind(player1), get_four_of_a_kind(player2))
    if category == 'full house':
        return (get_full_house(player1), get_full_house(player2))
    if category == 'flush':
        return (get_flush(player1), get_flush(player2))
    if category == 'straight':
        return (get_straight(player1), get_straight(player2))
    if category == '3 of a kind':
        return (get_three_of_a_kind(player1), get_three_of_a_kind(player2))
    if category == '2 pair':
        return (get_two_pair(player1), get_two_pair(player2))
    if category == '1 pair':
        return (get_one_pair(player1), get_one_pair(player2))
    # high card category
    return (player1, player2)

def main():
    # test()

    # create a shuffled deck
    deck = cards.Deck()
    deck.shuffle()

    # loop until the user quit or not enough cards on the deck
    while True:
        print ("----------------------------------------")
        print ("Let's play poker!")

        # deal cards
        community_cards = []
        player1_cards = []
        player2_cards = []

        player1_cards.append(deck.deal())
        player2_cards.append(deck.deal())
        player1_cards.append(deck.deal())
        player2_cards.append(deck.deal())
        for i in range(5):
            community_cards.append(deck.deal())

        # display the list of cards
        print ()
        print ("Community cards: %s" % (community_cards))
        print ("Player 1: %s" % (player1_cards))
        print ("Player 2: %s" % (player2_cards))
        print ()

        # now add the community cards to each player
        player1_cards.extend(community_cards)
        player2_cards.extend(community_cards)

        # now try to gets cards to form each category (from highest category to lowest) for each player
        # the category order is important, must from the highest to lowest category.
        for category in ('straight flush', '4 of a kind', 'full house', 
                     'flush', 'straight', '3 of a kind', '2 pair', '1 pair', 'high card'):
            player1, player2 = get(player1_cards, player2_cards, category)

            if player1 and player2: # both have this category, the cards of player 1 is shown
                print ("TIE with a %s: %s" % (category, player1))
                break
            elif player1 and not player2: # player 1 has a straight flush
                print ("Player %d wins with a %s: %s" % (1, category, player1))
                break
            elif not player1 and player2:
                print ("Player %d wins with a %s: %s" % (2, category, player2))
                break

        # check whether enough cards on the deck
        if deck.cards_count() < 9:
            print ("Deck has too few cards so game is done.")
            break

        print ()
        c = input ("Do you wish to play another hand? (Y or N) ")
        if c not in ('y', 'Y'): # user inputs to quit
            break

if __name__ == '__main__':
    main()

If you need a solution for your Python home work, then we can provide what you need. See the following sample Python problem solutions.

Python was developed in the late eighties and early nineties by Guido van Rossum at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python programming language is derived from other languages that includes languages like UNIX shell, ABC, Algol-68, C, C++, Smalltalk, Modula-3 and other scripting languages. The source code of Python is available under the GNU General Public License to be maintained by a core development team. Our experts provide plagiarism free help with Python programming assignment.

Random phone number

Problem: 2. Write a Python procedure, call it phn(), that will return a random phone number xxx-xxx-xxxx with the following restrictions:

  • a. The area code cannot start with a zero,
  • b. None of the middle three digits can be a 9,
  • c. Middle three digits cannot be 000,
  • d. Last 4 digits cannot all be the same.

So, 012-233-3335, 123-294-1234, 123-000-1234, and 123-232-4444 are examples of unacceptable phone numbers. Your code should include a for
loop. (Extra credit: what is the probability that your procedure would return your phone number?)

Validation Code: (Use this to check code)

#Check phn
test = phn()
if type(int(str(test[0:2]))) is int and type(int(str(test[4:6]))) is int and type(int(str(test[8:11]))) is int and str(test[3])==str(test[7])=='-':
    print("Your code for phn can be evaluated, but make sure you have met all conditions for a valid number.")
else:
    print ("Your code for myS can not be evaluated.  Make sure the format is xxx-xxx-xxxx.")

 

Solution:

import random

def phn():
    random.seed()
    # generate an area code
    area = random.randint(100, 999)

    # generate middle digits
    middle = 0
    while middle == 0: # continue until middle is not 000
        for i in range(0, 3):
            middle = middle * 10 + random.randint(0, 8)

    # generate last four digits
    l1 = random.randint(0, 9)
    l2 = random.randint(0, 9)
    l3 = random.randint(0, 9)
    if l1 == l2 == l3: # l4 cannot be the same, if the first three are the same
        l4 = l1
        while l4 == l1:
            l4 = random.randint(0, 9)
    else:
        l4 = random.randint(0, 9)

    phone = "%3d-%03d-%d%d%d%d" % (area, middle, l1, l2, l3, l4)
    return phone

#Check phn
test = phn()
if type(int(str(test[0:2]))) is int and type(int(str(test[4:6]))) is int and type(int(str(test[8:11]))) is int and str(test[3])==str(test[7])=='-':
    print("Your code for phn can be evaluated, but make sure you have met all conditions for a valid number.")
else:
    print ("Your code for myS can not be evaluated.  Make sure the format is xxx-xxx-xxxx.")

Here is a sample of a Python home work, compare our solutions to anyone else. Check out our Python programming homework help.

Mondthly sales

Problem:

Your employer needs a program that analyzes the monthly sales figures for each division. Write a Python program that allows the user to enter a series of numbers and places the numbers in a list. Each number entered by the user is the monthly sales amount for one division.
Use a sentinel-controlled loop to get input from the user and place each value entered into the list as long as the value is not negative. As soon as any negative value is entered, stop the loop (without putting that illegal value into the list).

One objective of this assignment is to apply algorithms we have studied to solve problems. You will do this by writing a function definition to implement each algorithm. Several of these tasks can also be accomplished with built-in functions. In those cases, your code should
demonstrate both approaches and show that the results are the same.

Add code to your program to do the following:

  1. Write a function definition that uses a loop and a string accumulator to produce and return a string result that includes the user-entered sales figures formatted to look similar to this when it is printed:

{$12.95, $1,234.56, $100.00, $20.50}

Notice the dollar signs, commas, and curly braces. Plan this one on paper before you start writing code. Add code that calls this function and prints the result.

  1. Show the highest number in the list — the sales leader! Do this in two ways. First, use the built-in ‘max’ function. Then, write your own ‘max2’ function that accomplishes the same thing by using a loop to find the highest value.
  2. Show the lowest number in the list — the sales loser. Do this in two ways. First, use the built-in ‘min’ function. Then, write your own ‘min2’ function that accomplishes the same thing by using a loop to find the lowest value.
  3. Show the total sales for the company for the month — the sum of all the numbers in the list. Once again, write a function that uses a loop and an accumulator to compute this sum.
  4. Show the average of all the numbers in the list. (Be sure to carefully check the result!)
  5. Ask the user to enter a threshold (a number). Write a function that takes a list and the threshold as parameters, and returns a new list that contains all values in the original list that are greater than or equal to the threshold — these divisions get awards for high sales! The new list may, of course, be empty.

Program Organization:

The program should be organized as a series of function definitions. The ‘main’ function should contain the user interface as well as code that “calls” the other functions and then shows the results to the user. Only the ‘main’ function should interact with the user. No other function should print anything; rather, each function “returns” a value. Do not use any global variables.

Testing:

As always, be sure to test each result using representative data to make sure it is correct, and include comments showing documented test cases in your program.

Solution:

# format the sales in the format like this
#  {$12.95, $1,234.56, $100.00, $20.50}
def format(sales):
    # format each sale into a string and put them into a new list
    sales = ['$' + '{:,.2f}'.format(sale) for sale in sales]
    # use ', ' to merge the sales into one string
    return '{' + ', '.join(sales) + '}'

def max2(sales):
    # return none for empty list
    if not sales:
        return None
    m = sales[0]
    # compare each sales with the current largest
    for sale in sales[1:]:
        if sale > m: # updae the largest one to the current one
            m = sale
    return m

def min2(sales):
    # return none for empty list
    if not sales:
        return None
    m = sales[0]
    # compare each sales with the current smallest
    for sale in sales[1:]:
        if sale < m: # updae the smallest one to the current one
            m = sale
    return m

def sum2(sales):
    s = 0
    # accumulate each sale into the sum
    for sale in sales:
        s += sale
    return s

def average(sales):
    # calculate the sum first
    s = sum2(sales)
    # if sales is not empty, the average is sum / number
    # otherwise return None as the average
    return s / len(sales) if sales else None

# return a new list that each sale in it >= threshold
def filter (sales, threshold):
    return [sale for sale in sales if sale >= threshold]

def main():

    # ask the user to input a series of numbers
    sales = []
    while True:
        sale = float (input ('input number (negative to stop): '))
        if sale < 0: break
        # put the sale into the list
        sales.append(sale)

    print (format(sales))

    print ('--------------- highest -------------')
    print (max(sales))
    print (max2(sales))

    print ('--------------- lowest -------------')
    print (min(sales))
    print (min2(sales))

    print ('--------------- sum -------------')
    print (sum(sales))
    print (sum2(sales))

    print ('--------------- average -------------')
    print (average(sales))

    print ("")
    # ask the user to input a thereshold
    threshold = float (input ('input a thereshold: '))
    sales = filter (sales, threshold)
    print ("result: " + format(sales))

if __name__ == '__main__':
    main()

As an illustration of an assigment, here’s a previous assignment that indicates the type of thing we have done with a Python language assignment.

Python programming is easy-to-learn because of few keywords, simple structure, and a clearly defined syntax. Easy-to-read is a feature of Python that clearly defines the code and the feature easy-to-maintain states that its code is very easy to debug and maintain.  A broad standard library, a feature of Python programming, shows that the bulk of the library is portable and cross-platform compatible on UNIX, Windows, and Macintosh.  Interactive Mode of Python allows interactive testing and debugging of code and executing Python on a wide variety of hardware platforms. It is extendable support in adding low-level modules to the Python interpreter. We provide well commented code when offer python programming assignment help. We offer quality help with Python programming homework.

Fix partially complete program

Problem:

  1. Write a program named “multiples1.py” that generates all multiples of a specified integer within a specified consecutive range of integers. The main function in the program should prompt the user to enter the upper and lower integers of the range and the integer for which multiples will be found. A function namedshow_multiples should take these three integers as arguments and use a repetition structure to display (on same line separated by a space) the multiples in descending order. The show_multiples function is called inside main. For this program, assume that the user enters range values for which multiples do exist.

SAMPLE RUN

Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
90 75 60 45 30

2. Make a copy of multiples1.py named multiples2.py. Modify the show_multiples function so it both counts and totals the even multiples and the odd multiples. The show_multiples function also prints the counts and sums. See sample run.

SAMPLE RUN

Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
90 75 60 45 30
3 even numbers total to 180
2 odd numbers total to 120

3. Make another copy of multiples1.py named multiples3.py. Modify the show_multiples function so that it creates and returns a list consisting of all of the multiples (even and odd). The show_multiples function should print only “List was created”, not the multiples. Create another function namedshow_list that takes the list as its sole argument. The show_list function should output the size of the list, display all of the list elements, and output the average of the list accurate to two decimal places. See sample run.

SAMPLE RUN

Enter the high integer for the range 100
Enter the low integer for the range 20
Enter the integer for the multiples 15
List was created 
The list has 5 elements.
90 75 60 45 30
Average of multiples is 60.00

This is what I have so far.

def main():

    #get the integers
    high = int(input('Enter the high integer for the range '))
    low = int(input('Enter the low integer for the range '))
    multi = int(input('Enter the integer for the multiples '))

    #call the function
    multiples = show_multiples(low, high, multi)

    #print the multipes
    print(multiples)

#take the arguments into the function
def show_multiples(low, high, multi):

    #set counter
    counter = 0

    #create list
    results = []

    #set loop
    keepgoing = True

    while keepgoing == True:

        #add to counter each pass
        counter += 1

        #math to get multiples
        result = multi * counter

        #high side stop
        if result >= high:

            keepgoing = False
            #cut the list and sort it
            results[low:high]
            results.sort(reverse=True)

        else:
            keepgoing = True

    return (result)

main()

The programmers may add or customize their tools through the modules to make them more efficient.  Python programming is used in major commercial databases for providing interfaces. Python programming is used to create GUI applications that can be ported on many libraries, system calls, and windows systems. Python is scalable in providing a better structure and also support for large programs than shell scripting. Our online Python programming assignment experts also explain some of the good features like its functional and structured programming methods as well as OOP are supported by it and can be used as a scripting language. Python program can be compiled to byte-code for building large applications. Students who need help with Python programming assignment can submit their assignments to us. We also offer online python programming project help to students as well as working professionals. Our python programming project help services are also used a lot by students.

Sum of Digits in a String:

Write a program that asks the user to enter a series or single digit numbers with nothing separating them. The program should display the sum of all the single digit numbers in the strong. For Example, if the user enters 2514, the method should return 12, which is the sum of 2,5,1 and 4.

Vowels and Consonants:

Write a program with a function that accepts a string as an argument and returns the number of vowels that the string contains. The application should have another function that accepts a string as an argument and returns the number of consonants that the string contains. The application should let the user enter a string and should display the number of vowels and the number of consonants it contains.

I have this code, but its not working in python 3.4.1:

original = raw_input('Enter a word:')
word = original.lower()
first = word[0]

if len(original) > 0 and original.isalpha():
    if first in 'aeiou':
        print "vowel"
    else:
        print "consonant"
else:
    print "empty"

Most Frequent Character:

Write a program that lets the user enter a string and display the characters that appears most frequently in the string.

Unique Words:

Write a program that opens a specified text file and then displays a list of all the unique words found in the file. Name the text file for_exercise4.txt

Solution:

multiples1.py

def show_multiples(lower, upper, mul):
    # calculate the highest possible multiplier
    multiplier = int(upper / mul) + 1

    # repeat until reach the lower bound
    while multiplier * mul >= lower:
        if multiplier * mul <= upper:
            print (multiplier * mul, end=" ")
        multiplier = multiplier - 1
    print ("")

def main():
    upper = input('Enter the high integer for the range ')
    upper = int(upper) # convert string to integer
    lower = input('Enter the low integer for the range ')
    lower = int(lower)
    number = input('Enter the integer for the multiples ')
    number = int(number)
    show_multiples(lower, upper, number)

main()

multiples2.py

def show_multiples(lower, upper, mul):
    # count even and odd numbers
    # and calculate their totals separately
    even_count = 0
    even_total = 0
    odd_count = 0
    odd_total = 0

    # calculate the highest possible multiplier
    multiplier = int(upper / mul) + 1

    # repeat until reach the lower bound
    while multiplier * mul >= lower:
        value = multiplier * mul
        if value <= upper:
            print (multiplier * mul, end=" ")
            if value % 2 == 1: # odd number
                odd_count = odd_count + 1
                odd_total = odd_total + value
            else: # even number
                even_count = even_count + 1
                even_total = even_total + value
        multiplier = multiplier - 1
    print ("")
    print ("%d even numbers total to %d" % (even_count, even_total))
    print ("%d odd numbers total to %d" % (odd_count, odd_total))

def main():
    upper = input('Enter the high integer for the range ')
    upper = int(upper) # convert string to integer
    lower = input('Enter the low integer for the range ')
    lower = int(lower)
    number = input('Enter the integer for the multiples ')
    number = int(number)
    show_multiples(lower, upper, number)

main()

multiples3.py

def show_multiples(lower, upper, mul):
    # values in the range is put into this result list
    result = []
    # calculate the highest possible multiplier
    multiplier = int(upper / mul) + 1

    # repeat until reach the lower bound
    while multiplier * mul >= lower:
        if multiplier * mul <= upper:
            result.append(multiplier * mul)
        multiplier = multiplier - 1
    print ("List was created")
    return result

def show_list(lst):
    print ("The list has %d elements." % (len(lst)))
    # display the list
    for number in lst:
        print (number, end=" ")
    print("")

    # in order to calculate average,
    # first calculate the total of numbers
    total = 0
    for number in lst:
        total += number

    # calculate and display average
    avg = total / len(lst) if len(lst) > 0 else 0
    print ("Average of multiples is %.2f" % (avg))

def main():
    upper = input('Enter the high integer for the range ')
    upper = int(upper) # convert string to integer
    lower = input('Enter the low integer for the range ')
    lower = int(lower)
    number = input('Enter the integer for the multiples ')
    number = int(number)
    lst = show_multiples(lower, upper, number)
    show_list(lst)

main()

sumOfDigits.py

# ask the user to enter a series or single digit numbers
# display the sum of all the single digit numbers in the string

def main():
    string = input ('Enter the digit string: ')

    # calculate the total of digits
    total = 0
    for char in string:
        # convert char to int
        total += ord(char) - ord('0')
    print ("Sum: ", total)

main()

vowel.py

# return the number of vowels that the string contains
def num_vowels(string):
    # convert string to lower case letters
    string = string.lower()
    num = 0
    # enumerate all characters in the string
    for char in string:
        if char in 'aeiou':
            num = num + 1
    return num

# return the number of consonants that the string contains
def num_consonants(string):
    string = string.lower()
    num = 0
    # enumerate all characters in the string
    for char in string:
        if char.isalpha() and char not in 'aeiou':
            num = num + 1
    return num

def main():
    string = input('Enter the string: ')
    print ("Number of vowels: ", num_vowels(string))
    print ("Number of consonants: ", num_consonants(string))

main()

Students looking for python programming project help and assignment solution, can upload their assignment on our website. Our highly skilled, qualified and experienced team of experts are available 24*7. Students can also contact us via email or live-chat to avail our help with python programming assignment.

frequentChar.py

# display the characters that appears most frequently in a string
# this program considers cases. For example,
# string 'aA' has one 'a', and one 'A', instead of two 'a'.
#
# if multiple characters have the same most frequency,
# all of them are displayed.
def main():
    string = input('Enter a string: ')
    # use a dictionary to store the frequency
    freq = dict()

    # enemurate the characters in the string
    # increase the frequency
    for char in string:
        freq[char] = freq.get(char, 0) + 1

    # calculate counter
    largest = -1
    for char, k in freq.items():
        if k > largest:
            largest = k

    # display characters that have the largest counter (apperance)
    print("Characters of most frequency: ")
    for char, k in freq.items():
        if k == largest:
            print (char, end=" ")
    print("")

main()

uniqueWords.py

# display a list of all the unique words found in the word
# assume the words in the test file 'for_exercise4.txt' are seperated by
# empty spaces.
# this program ignores cases in the words.

def main():
    # open the file for reading
    fin = open("for_exercise4.txt", "r")
    # read the content of the file
    content = fin.read()
    # close the file
    fin.close()

    # remove non-alpha characters in the content
    content = ''.join(c for c in content if c.isalpha() or c.isspace())

    # seperate the content into words using empty spaces
    words = content.split()

    # convert all words into lower case
    words = [word.lower() for word in words]

    # sort the words
    words.sort()

    # convert the words into a set to unify them
    words = set(words)

    # convert the set back to list and sort the list
    words = list(words)
    words.sort()

    # display the result
    for word in words:
        print(word)

main()

Guaranteed 100% plagiarism free solutions in Python homework. So, if you are looking for a Python online tutor or just Python problem solutions then look no further.

We are the complete service provider getting most of our business from the repeat customers or through successful client referrals for python assignment. The Python programming homework help is the worldwide podium for the students who seek all possible help on Python programming. The solutions that we provide in Python programming assignments for beginners incorporates all the finer points that helps in building the basics of programming acumen. The Python homework problems that we have in our listings is the collection of problems from the question papers from the finest universities all throughout the world.

Question game

Problem:

Requirements:

  1. Dialogue is continued by mouse click.
  2. Use the background file as background
  3. When alien talk, show its picture.
  4. When alien ask questions, show picture in the file related to the question. (background hide in this case)
  5. When the game is over, go back to the beginning of the game.
  6. To answer the question, you can use either keyboard or mouse click. But you need a sentence to describe how to answer.(I prefer mouse click.)
  7. When answer is wrong, show what alien say first, and then show the picture {“youlose”| after mouse click.
  8. Use a rectangle to show dialogue, and name shows on the left top of rectangle.

Note: this is my first year learning python, so don′t use the code that is too complicated.

Story

Title: Can you survive? (click)

Show: In 2333, aliens start to invade earth. They killed millions of people, and controlled many countries. Scientists have developed a new weapon which can defeat aliens. You are a smart university student, but you are captured by aliens. Aliens have a strange hobby. They like asking questions. If your answer is wrong, you will be killed. Your purpose is to survive and wait for rescue.

  1. Narrator: You were put in jail for several days. The guard is bored now, and you are asked to talk with the guard.
    Alien: what{'}s your name?  
    You: xxx.               
    Alien: good! Mr.xxx, I{'}ll ask you some questions now. If you cannot answer correctly, I{'}ll kill you.
    Narrator: you don{'}t even have reaction, the alien has begun.
    Alien: If I give you a weapon, what would you do?
    a) kill you and run   Alien: Good choice! But there is another guard outside. Die
    b) do nothing   
       Alien: Coward! But not bad.
  2. Alien: I am not familiar with this planet. Can you tell me how many countries in the world?
    a) about 180 Alien: You think I don{'}t know how to use Google? Die
    b) about 190
    c) about 200 Alien: You think I don{'}t know how to use Google? Die
        Alien: Good Job!
  3. Alien: I′ll increase difficulty now. What is the probability to draw two A from a poker without shuffling?
    a) 4.19*10^-3
    b) 5.49*10^-3 Die
    c) 4.11*10^-3 Die
  4. Alien: Which one is poisonous?
    a) C6H7KO2   Die
    b) C4H4KNO4S Die
    c) Na5P3O10  Die
    d) C16H12N2O
    Alien: Interesting, you learned chemistry.
  5. Alien: Which one will you get less wet?
    a) Walking in the rain 
    b) Running in the rain Alien: Did I tell you there is somewhere you can hide? die
    Alien: Great! This is the last question. I{'}ll let you go if you can answer correctly.
    You: Really?
    Alien: Sure.
    You: Go ahead.
  6. Alien: Will I let you go?
    a) Yes, you will Alien:  Game over. Die
    b) No, you won{'}t
    Next page: You Win!
    Next page: Sorry, you died because the alien thinks you are too smart!

Solution

from Queue import Queue
from Tkinter import *
import os
from threading import Timer
import time
import sys

FIRST_SCREEN = "firstscreen.gif"
SECOND_SCREEN = "secondscreen.gif"
BACKGROUND_PATH = "background.gif"
GAME_OVER_PATH = "GameOver.gif"
ALIEN_PATH = "Alien.gif"
TEXT_INTERVAL = 1.0
ANSWER_TEXT_INTERVAL = 3.0
TEXT_1 = "Narrator: You were put in jail for several days. The guard is bored now, and you are asked to talk with the guard."
TEXT_2 = "Alien: whats your name?"
TEXT_3 = "Alien:  good! Mr.%s, I'll ask you some questions now. If you cannot answer correctly, I'll kill you."
TEXT_4 = "Narrator: you don't even have reaction, the alien has begun."

def get_relative_path(path):
    dir = os.path.dirname(__file__)
    return os.path.join(dir, path)

class Game():
    def start(self):
        self.root = Tk()
        self.root.title("Alians games")

        self.frame = Frame(self.root)
        self.frame.pack()

        self.canvas = Canvas(self.frame, width=500, height=500, bg='white')
        self.canvas.pack(expand=YES, fill=BOTH)
        self.firstScreen = PhotoImage(file=FIRST_SCREEN)
        self.second_screen = PhotoImage(file=SECOND_SCREEN)
        self.render([MyImage(self.firstScreen, 0, 0)])
        self.canvas.bind("<Button-1>", self.go_second_screen)

        self.game_over_image = PhotoImage(file=GAME_OVER_PATH)
        self.win_image = PhotoImage(file="win.gif")
        self.youlose_image = PhotoImage(file="youlose.gif")

        self.root.mainloop()

    def go_second_screen(self, e):
        self.frame.destroy()
        self.frame = Frame(self.root)
        self.frame.pack()

        self.canvas = Canvas(self.frame, width=500, height=500, bg='white')
        self.canvas.pack(expand=YES, fill=BOTH)
        self.render([MyImage(self.second_screen, 0, 0)])
        self.canvas.bind("<Button-1>", self.start_game)

    def start_game(self, e):
        self.root.geometry("500x600")
        self.frame.destroy()
        self.frame = Frame(self.root)

        #background
        self.canvas = Canvas(self.frame, width=500, height=362, bg='white')
        self.canvas.pack(expand=YES, fill=BOTH)
        self.background_image = PhotoImage(file=BACKGROUND_PATH)
        self.render([MyImage(self.background_image, 0, 0)])

        self.alien_image = PhotoImage(file=ALIEN_PATH)

        #name label
        self.name = StringVar()
        self.name.set("Unknown name")
        self.name_label = Label(self.root, textvariable=self.name)
        self.name_label.place(x=5, y=370)

        #answers
        self.answers_buttons = []
        self.questions_image = []
        for i in range(1,7):
            image_path = str(i) + ".gif"
            self.questions_image.append(PhotoImage(file=image_path))

        #talking text
        self.text = Text(self.root, height=3, width=80)
        self.text.place(x=50, y=400)
        self.write_text(TEXT_1)

        self.frame.pack()

        self.text_queue = Queue()
        self.text_queue.put((self.ask_for_name, []))
        self.text.bind("<Button-1>", self.click_on_text)
        self.canvas.bind("<Button-1>", self.click_on_text)

    def click_on_text(self, e):
        if(not self.text_queue.empty()):
            func_with_params = self.text_queue.get()
            func = func_with_params[0]
            args = func_with_params[1]
            func(*args)

    def render(self, images):
        for i in images:
            self.canvas.create_image(i.x, i.y, image=i.image, anchor=NW)

    def write_text(self, textStr):

        if textStr.startswith("Alien:"):
            self.render([MyImage(self.background_image,0,0), MyImage(self.alien_image, 290,170)])
        else:
            self.render([MyImage(self.background_image,0,0)])

        self.text.delete(1.0, END)
        self.text.insert(INSERT, textStr)

    def ask_for_name(self):
        self.write_text(TEXT_2)
        self.name_text_box = Entry(self.root)
        self.name_text_box.place(x=50, y=450)
        self.submit_name_button = Button(self.root, text="Submit", command=self.submit_name)
        self.submit_name_button.place(x=200, y=450)

    def submit_name(self):
        self.name.set(self.name_text_box.get())
        self.submit_name_button.destroy()
        self.name_text_box.destroy()
        self.write_text(TEXT_3 % self.name.get())
        self.text_queue.put((self.write_text, [TEXT_4]))
        self.text_queue.put((self.ask_question, [1]))

    def ask_question(self, question_number):
        question = QUESTIONS[question_number]
        self.write_text(question.question_text)

        question_image = self.questions_image[question_number - 1]
        self.render([MyImage(question_image, 0, 0)])

        y = 450
        for a in question.answers:
            if not a.is_wrong:
                if question_number == 6:
                    b = Button(self.root, text=a.answer_text, command=lambda: self.win())
                else:
                    t = a.get_alien_text()
                    b = Button(self.root, text=a.answer_text, command=lambda: self.good_answer(t, question_number + 1))
            else:
                b = Button(self.root, text=a.answer_text, command=lambda: self.die(a.get_alien_text()))

            b.place(x=150, y=y)
            self.answers_buttons.append(b)
            y = y + 30

    def die(self, alien_text):
        self.render([MyImage(self.game_over_image,0 ,0)])
        self.text_queue.put((restart_program, []))

    def win(self):
        self.render([MyImage(self.win_image, 0, 0)])
        t = Timer(2, self.show_youlose)
        t.start()

    def show_youlose(self):
        self.render([MyImage(self.youlose_image, 0, 0)])
        t = Timer(2, self.close_program)
        t.start()
        self.after(5)

    def close_program(self):
        self.root.destroy()
        quit()

    def delete_answers_buttons(self):
        for b in self.answers_buttons:
           b.destroy()

        self.root.update()

    def good_answer(self, alien_text, next_question):
        self.delete_answers_buttons()
        i = 0
        for a in alien_text:
            if i == 0:
                self.write_text(a)
            else:
                self.text_queue.put((self.write_text, [a]))
            i = i + 1

        self.text_queue.put((self.ask_question, [next_question]))

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

class Answer:
    def __init__(self, answer_text, alien_text, is_wrong):
        self.answer_text = answer_text
        self.is_wrong = is_wrong
        self.alien_text = alien_text

    def get_alien_text(self):
        return self.alien_text

class Question:
    def __init__(self, question_text, answers):
        self.question_text = question_text
        self.answers = answers

class MyImage:
    def __init__(self, image, x, y):
        self.image = image
        self.x = x
        self.y = y

QUESTIONS = {
    1: Question("Alien: If I give you a weapon, what would you do?", [
        Answer("kill you and run", ["Alien: Good choice! But there is another guard outside. Die"], True),
        Answer("do nothing", ["Alien: Coward! But not bad."], False)
    ]),

    2: Question("Alien: I am not familiar with this planet. Can you tell me how many countrie in the world?", [
        Answer("about 180", ["Alien: You think I don't know how to use Google? Die"],  True),
        Answer("about 190", ["Alien: Good Job!"], False),
        Answer("about 200", ["Alien: You think I don't know how to use Google? Die"],  True)
    ]),

    3: Question("Alien: I'll increase difficulty now. What is the probability to draw two A from a poker without shuffling?", [
        Answer("4.19*10^-3", ["Alien: Good!"],  False),
        Answer("5.49*10^-3 ", ["die"], True),
        Answer("4.11*10^-3 ", ["die"],  True)
    ]),

    4: Question("Alien: Which one is poisonous?", [
        Answer("C6H7KO2", ["die"],  True),
        Answer("C4H4KNO4S ",["die"], True),
        Answer("Na5P3O10 ", ["die"],  True),
        Answer("C16H12N2O", ["Alien: Interesting, you learned chemistry."],  False)
    ]),

     5: Question("Alien: Which one will you get less wet?", [
        Answer("Walking in the rain", ["Alien: Great ! This is the last question. I'll let you go if you can answer correctly.", "You: Really?", "Alien: Sure.", "You: Go ahead."],  False),
        Answer("Running in the rain", ["Alien: Did I tell you there is somewhere you can hide? die"], True)
    ]),

     6: Question("Alien: Will I let you go?", [
        Answer("Yes, you will", ["Alien: Game over. die"],  True),
        Answer("No, you won't", [], False)
    ]),
}

Game().start()

If you need a Python online tutor to tutor you on Python programming assignments like this, pleasefeel free to} Contact us.

Quiz

Problem:

  1. Give the value of the following Python expressions:
    a. 42 / 10
    b. 42 // 10
    c. 42 % 10
    d. 2 + 2 == 5
    e. 2 == "2"
    f. not 2
  2. What should x, y and z be in range(x,y,z) function in order to generate the following list
    [-2, 0, 2, 4, 6, 8].
  3. Write a Python procedure, call it rev(s), that returns string s in reverse. For instance, rev(‘abcd’) should return ‘dcba’
  4. Given a positive number n, say n = 36489, we are interested in numbers obtained by sorting digits in n; in this example, number 98643 and 34689. Write a Python function for this purpose.
  5. Write a Python procedure, call it dup(s), that returns ‘Yes’ if string s has a duplicate character, and ‘No’ otherwise. For instance, dup(‘abca’) should return ‘Yes’, and dup(‘abcd ef’) should return ‘No’.
  6. Suppose div(n) procedure returns a list containing all the divisors of integer n. For instance, div(6) returns [1, 2, 3, 6]. Write a Python procedure, call it prime(n), that uses div(n) and return ‘Yes’ or ‘No’, depending on whether n is prime or not. For instance, prime(8) should return ‘No’ whereas prime(7) should return ‘Yes’.
  7. Write a Python procedure, call it pld(k), that returns a random k-digit palindrome. A palindrome number is a number that remains the same when its digits are revered. For instance, 7, 66, 101, and 4224 are examples of palindrome numbers, whereas 768 is not. So, pld(5) should return a 5-digit palindrome at random, such as 12521.
  8. Write a function, call it Fib(n), that prints out the first n numbers in the Fibonacci sequence, which is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144… (each of the numbers after the first two in the sequence is the sum of the two numbers preceding it)
  9. Write a function PrintThree(s) that prints out a string s, three characters at a time. Remember that len(s) returns the length of a string.
  10. Write a function Leap(y) that returns True if y is a leap year, and False otherwise. A year is a leap year if it is divisible by 4, but not by 100, unless it is also divisible by 400.
  11. Write a function GoState() that prints the numbers from 1 to 100. However, for numbers which are multiples of 3, it should print “Go” instead of the number. For numbers which are multiples of 5, it should print “State” instead of the number. For numbers which are multiples of both 3 and 5 it should print “GoState” instead of the number.
  12. Suppose we use two-digit numbers to encode the English lower-case and uppercase alphabet. So, letter a is encoded as 00, letter b as 01, letter c as 02, …, letter z as 25, letter A as 26, letter B as 27, …, and letter Z as 51. Write a python function, call it
    str2num(s), that returns the above encoding of string s. For example, str2num(‘MyHome’) should return string ‘382433141204’.
  13. Let′s expand the above problem to allow spaces and periods where a space is to be encoded as 52 and a period as 53. Modify your Python program accordingly, call it str2numsp(s). For example, str2numsp(‘I like Python.’) should return string ‘3452110810045241241907141353’.
  14. Write a Python procedure, call it num2str(s), that if s is the output of your program in Problem #1 3 it returns the original text. For example, num2str(‘45070818520818522814141153’) should return ‘This is Cool.’
  15. A positive integer n is called perfect if it is equal to the sum of its integer divisors, except itself. For example, the divisors of integer 6 are 1, 2, 3, and 6, and since 6 = 1 + 2 + 3, then 6 is a perfect integer. So is 28 (verify it). Write a Python function, called it perf(n), that returns ‘Yes’ if n is a perfect integer, and ‘No’ otherwise.

Solution:

Question 1

a. 4.2
b. 4
c. 2
d. False
e. False
f. False

Question 2

x = -2, y = 10, z = 2

Question 3

def rev(s): return s[::-1]

Question 4

def nsort(n):
    v = "".join(sorted(str(n)))
    return int(v[::-1]), int(v)

Question 5

def dup(s):
    for i in range(len(s)):
        if s[i] in s[i + 1:]:
            return "Yes"
return "No"

Question 6

def prime(n):
    return "Yes" if len(div(n)) == 2 else "No"

Question 7

import random

def pld(k):
    lst = [random.randint(1, 9)]
    for i in range(1, k // 2):
        lst.append(random.randint(0, 9))
    if k > 1 and k % 2 == 1:
        lst.append(random.randint(0, 9))
    lst.extend(reversed(lst))
    lst = [str(i) for i in lst]
    return int("".join(lst))

Question 8

def Fib(n):
    a, b = 0, 1
    if n >= 1: print (a)
    if n >= 2: print (b)
    while n >= 3:
        c = a + b
        print (c)
        a, b = b, c
        n -= 1

Question 9

def PrintThree(s):
    l = len(s)
    for i in range(0, l, 3):
        print (s[i:i+3])

Question 10

def Leap(y):
    return (y % 4 == 0 and y % 100 != 0) or y % 400 == 0

Question 11

def GoState():
    for i in range(1, 101):
        if i % 3 == 0 and i % 5 == 0: print ("GoState")
        elif i % 3 == 0: print ("Go")
        elif i % 5 == 0: print ("State")
        else: print (i)

Question 12

def str2num(s):
r = ""
code = 0
    for c in s:
        if 'a' <= c <= 'z':
            code = ord(c) - ord('a')
        if 'A' <= c <= 'Z':
            code = 26 + ord(c) - ord('A')
        r += "%02d" % (code)
    return r

Question 13

def str2numsp(s):
    r = ""
    for c in s:
        code = 0
        if 'a' <= c <= 'z':
            code = ord(c) - ord('a')
        if 'A' <= c <= 'Z':
            code = 26 + ord(c) - ord('A')
        if c == '.':
            code = 53
        if c == ' ':
            code = 52

        r += "%02d" % (code)
    return r

Question 14

def num2str(s):
    r = ""
    for i in range(0, len(s), 2):
        code = int(s[i:i+2])
        if code < 26:
            ch = chr(code + ord('a'))
        elif code < 52:
            ch = chr(code - 26 + ord('A'))
        elif code == 53:
            ch = '.'
        else:
            ch = ' '
        r += ch
    return r

Question 15

def perf(n):
s = 0
for div in range(1, n):
    if n % div == 0:
        s += div
return "Yes" if s == n else "No"

Below is a sample assignment that shows the help with Python language assignment we can provde.

Cars

Problem:

  1. CarsWrite a program that writes a list of cars one item at the time to a file called “Cars.txt”. Go online (i.e. Google it) and find 10 car brands. Create a list and write each item from the list on a new line in the file.
  2. ConversionWrite a program that converts Celsius degrees entered by user to Fahrenheit equivalents. The formula is Ask the user to enter the temperature in Celsius. Store each input and converted value into a list or lists (depends on your approach).Handle exceptions (i.e. validate input) should user enter something other than a number. Keep converting as long as user has more temperatures to enter. Accept only {‘y’} to continue reentering temperatures or {‘n’} to stop. Handle should user enter something other than {‘y’} or {‘n’}. Once user enters {‘n’}, ask user for a file name and write your list or lists to that file. File should contain user entries and their conversions.
    Write one line per user entry to the file.
  3. True Cost To OwnWrite a program that helps a user estimate costs related to owning a car for 1 year. Assume following costs: gasoline, oil changes, car insurance, maintenance/repairs, car loan payment, depreciation value and taxes.Gasoline cost is on a 12-month basis. Allow user to enter the cost for each month.Oil changes vary from driver to driver. Allow user to enter the number of oil changes, and then accept the cost of each one individually.Car insurance needs to be paid every 6 months. Allow user to enter the cost for each 6-month period.Maintenance/repair needs vary from car to car. Allow user to enter the number of maintenance/repair visits, and then accept the cost of each one individually. A user may or may not have any maintenance/repair visits.Car loan has to be paid every month. Allow user to enter the payment cost for each month. A user may or may not have a car loan. User may or may not pay the same amount every month.Each year, a car value depreciates. That cost has to be added to the {“true cost to own.”} Allow user to enter depreciation value.Once a year, a user has to pay taxes in form of registration fee(s) and state inspection. Allow user to enter registration fee(s) and state inspection costs.Assume that the input above is absolute then project {“true cost to own”} for 5 years.

Your program should handle exceptions, validate input, AND write each input as well as the result to a file

Solution:

  1. Cars
    #Cars.py
    #last name, first name
    #lab section
    #assignemnt number
    def printCarsToFile():
        carList = ['Skoda', 'Jaguar',
                   'Mazda', 'Mercedes-Benz',
                   'Honda', 'Toyota',
                   'Audi', 'Porsche',
                   'BMW', 'Volkswagen']
        file = open('Cars.txt', 'w')
        for car in carList:
            file.write(car + '\n')
        file.close()
  2. Conversion
    #Conversion.py
    #last name, first name
    #lab section
    #assignemnt number
    def Conversion():
        #list to save the data, every entry will be tuple of (Celsius, Fahrenheit)
        list = []
        #this is the boolean value to use, and know 
        loop = True
        while(loop):
            userInput = input("Pls enter temperature in Celsius: ")
            try:
                C = int(userInput)
                f = 9.0/5*C + 32
                print("Celsius {0:5d} ==> Fahrenheit {1:.2f}".format(C,f))
                list.append((C, f));
            except ValueError:
                print('That is not an int! Pls try again')
                continue
            while(True):
                moreInput = input("Do you want to enter more data (Y/N): ")
                if moreInput in ('Y', 'y'):
                    print("Ok lets do one more calculation")
                    break
                elif moreInput in ('N', 'n'):
                    print("End of calculation")
                    loop = False
                    break
                else:
                    print("Pls enter y or n only")
        userInput = input("Enter the file name to save the data: ")
        if (userInput == ''):
            print("You did not enter valid name, using 'output.txt' insted")
            userInput = 'output.txt'
        file = open(userInput, 'w')
        file.write("Celsius | Fahrenheit\n")
        for (C,f) in list:
            file.write("{0:5d}   |   {1:5.2f}\n".format(C,f))
        print("Thank you for using our program, see you again")
        file.close()
    #Conversion()
  3. True Cost To Own
    #TryCostToOwn.py
    #last name, first name
    #lab section
    #assignemnt number
    def gasCoasts():
        gasoline = []
        for i in range(1, 13):
            while(True):
                gascost = input("Pls enter gas coast for month {0}: ".format(i))
                try:
                    gcost = float(gascost)
                    gasoline.append(gcost)
                    break
                except ValueError:
                    print("You did not enter a valid number, pls try again")
        return gasoline
    def oilCoasts():
        while (True):
            try:
                numOfOilChanges = input("Pls enter the number of Oil changes: ")
                number = int(numOfOilChanges)
                break
            except ValueError:
                print("You did not enter a valid number, pls try again")
        oilChanges = []
        for i in range(0, number):
            while(True):
                oilChangeCost = input("Pls enter oil change coast for visit {0}: ".format(i+1))
                try:
                    ocost = float(oilChangeCost)
                    oilChanges.append(ocost)
                    break
                except ValueError:
                    print("You did not enter a valid number, pls try again")
        return oilChanges
    def carInsuranceCoasts():
        carInsurance = []
        for i in range(0, 2):
            while(True):
                insuranceCoast = input("Pls enter car Insurance coasts from {0} month to {1} month: ".format(6*i, 6*(i+1)))
                try:
                    icost = float(insuranceCoast)
                    carInsurance.append(icost)
                    break
                except ValueError:
                    print("You did not enter a valid number, pls try again")
        return carInsurance
    
    def maintananceCoasts():
        maintenanceCoast = []
        while (True):
            try:
                numOfMR = input("Pls enter the number of Maintenance/Repair: ")
                number = int(numOfMR)
                break
            except ValueError:
                print("You did not enter a valid number, pls try again")
        for i in range(0, number):
            while(True):
                maintenance = input("Pls enter Maintenance/Repair cost for visit {0}: ".format((i+1)))
                try:
                    mcost = float(maintenance)
                    maintenanceCoast.append(mcost)
                    break
                except ValueError:
                    print("You did not enter a valid number, pls try again")
        return maintenanceCoast
    
    def loanCoasts():
        loanCoast = []
        while (True):
            doYouHaveLoan = input("Pls enter do you have a loan coasts (Y/N): ")
            if doYouHaveLoan in ('Y', 'y'):
                for i in range(1, 13):
                    while(True):
                        gascost = input("Pls enter loan coast for month {0}: ".format(i))
                        try:
                            lcost = float(gascost)
                            loanCoast.append(lcost)
                            break
                        except ValueError:
                            print("You did not enter a valid number, pls try again")
                #when we finish we need to break
                break
            elif doYouHaveLoan in ('N', 'n'):
                break
            else:
                print("You need to enter y or n, pls try again")
        return loanCoast
    def depreciateCoasts():
        depreciate = 0
        while (True):
            try:
                depreciatecoast = input("Pls enter the value for depreciate: ")
                depreciate = float(depreciatecoast)
                break
            except ValueError:
                print("You did not enter a valid number, pls try again")
        return depreciate
    def taxCoasts():
        taxCoast = []
        while (True):
            try:
                registrationfee = input("Pls enter the value for registration fee: ")
                registration = float(registrationfee)
                break
            except ValueError:
                print("You did not enter a valid number, pls try again")
        taxCoast.append(registration)
        while (True):
            try:
                stateinspection = input("Pls enter the value for stateinspection: ")
                inspection = float(stateinspection)
                break
            except ValueError:
                print("You did not enter a valid number, pls try again")
        taxCoast.append(inspection)
        return taxCoast
    
    def TrueCostToOwn():
        file = open('carCoasts.txt', 'w')
        print("{0:10s}|{1:10s}|{2:10s}|{3:10s}|{4:10s}|{5:10s}|{6:10s}\n".format("Year", "gasoline", "oil", "insurance", "meintenanc", "loan", "depreciate", "tax"))
        file.write("{0:10s}|{1:10s}|{2:10s}|{3:10s}|{4:10s}|{5:10s}|{6:10s}\n".format("Year", "gasoline", "oil", "insurance", "meintenanc", "loan", "depreciate", "tax"))
        # lets calculate gasoline coasts, and gasTotal for one Year
        gasoline = gasCoasts()
        gasTotal = 0
        for g in gasoline:
            gasTotal = gasTotal + g;
    
        # lets calculate oil coasts, and oilTotal for one Year
        oil = oilCoasts()
        oilTotal = 0
        for oi in oil:
            oilTotal = oilTotal + oi;
    
        # lets calculate insurance coasts, and insuranceTotal for one Year
        insurance = carInsuranceCoasts()
        insuranceTotal = 0
        for i in insurance:
            insuranceTotal = insuranceTotal + i
    
        # lets calculate maintanance coasts, and maintananceTotal for one Year
        maintanance = maintananceCoasts()
        maintananceTotal = 0
        for m in maintanance:
            maintananceTotal = maintananceTotal + m
    
        # lets calculate loan coasts, and loanTotal for one Year
        loan = loanCoasts()
        loanTotal = 0
        for l in loan:
            loanTotal = loanTotal + l
    
        #depreciate coasts
        depreciate = depreciateCoasts()
    
        # taxcoasts
        tax = taxCoasts()
        taxTotal = tax[0] + tax[1]
        for i in range(1, 6):
            print("{0:10d}|{1:10.2f}|{2:10.2f}|{3:10.2f}|{4:10.2f}|{5:10.2f}|{6:10.2f}\n".format(i, i*gasTotal, i*oilTotal, i*insuranceTotal, i*maintananceTotal, i*loanTotal, i*depreciate, i*taxTotal))
            file.write("{0:10d}|{1:10.2f}|{2:10.2f}|{3:10.2f}|{4:10.2f}|{5:10.2f}|{6:10.2f}\n".format(i, i*gasTotal, i*oilTotal, i*insuranceTotal, i*maintananceTotal, i*loanTotal, i*depreciate, i*taxTotal))
        totalForYear = gasTotal + oilTotal + insuranceTotal + maintananceTotal + loanTotal + depreciate + taxTotal
        print("Total for 5 years: {0}\n".format(5 * totalForYear))
        file.write("Total for 5 years: {0}\n".format(5 * totalForYear))
        file.close()
    
    TrueCostToOwn()

Why you should write your assignment with ProgrammingHomeworkHelp.com

We have made learning easier by providing help to students at the comfort of their homes and at their convenience. Long gone are the days when students had to travel to some scheduled place or wait for a specific day to get coding python assignment help. Students from all walks of life can now get python assignment help with just a few clicks of the mouse.

Most students are always overworked since they have to do so many tasks both at school and when they are back at home. It becomes very difficult to complete all these tasks successfully without any compromise because of lack of time and exhaustion. We know how important assignments are in the life of a student and they shouldn’t be taken for granted. That is why we encourage you to get python assignment helper service from us. You will not be worried about your academics because our experts will be handling all your assignments.

Your professor will not go easy on you because you have a busy schedule. Instead you will be expected to submit impressive solutions for all your assignments if you want to earn top grades. The best way to ensure that the quality of your assignments and grades are nothing less than the best is by getting our homework solver python service. We have set high standards for all the content we write. Never have we compromised on quality and delivered solutions that breach the confidence our clients have in us. Students who pay for python homework on our site can be rest assured of a stress free college life. They do not have to be frustrated or worry about anything because their assignments are being handled by the best experts.

If you are new to getting help with python assignment online then you are probably wondering whether we are well-versed with the referencing techniques and guidelines that your professor wants to be used in your assignment. We always receive this kind of question from new clients. Yes, we are familiar with all the formatting styles employed by renowned universities across the globe. Our experts can do APA, MLA, Chicago, Harvard, Vancouver etc. We will exceed your expectations when you receive your content. We follow every requirement you submit to us to the very last detail. To prove to you how eminent our site is, we have samples of the assignments we have done for students on our website. You can access them at any time if you are in doubt of the quality of our work. The samples can also come in handy when you want to refer or prepare for an upcoming test.

No task in Python is too difficult for us to handle. Our professional assignment writers are programming gurus and can handle a task in any topic in Python. So do not stress yourself with questions like “Where can I pay someone to do my assignment?” We are available in the USA, Canada, Australia, UK, Malaysia and many more countries. Even the students in Singapore can access our special Singapore python service. Contact us at any time and get live python help. Our experts will tutor you on the topics which you find difficult to understand in class. We care about your academic excellence and don’t want you to fail just because you missed a session on Python. You can get a second chance of learning what you missed in class from our experts. You can type and post any question on our python live chat platform and our experts will get back to you with precise and accurate solutions.

 

Do not hesitate to inquire about us when you are stuck with your assignments. Our procedure of getting help is so self-explanatory and will not take much of your time.  Just visit our homepage and send us the assignment plus the guideline, make payment and then sit back and relax as we do the hard part for you. You do not have to make an appointment or meet our experts at some place. We handle everything online far away from monotony and distractions.

What you stand to gain if you hire ProgrammingHomeworkHelp.com to assist you with your Python Tasks

We are very unique and our site bears a lot of benefits. Here are some of the fruits you will reap when you receive help from us:

  • Stress free academic life – Degree programs in programming take so much time and requires so much commitment. You will have to spend hours in the library carrying out research and practicing for your tests. All these academic activities can be stressing and inhibit the social life of a student. With our help, you will have time to relax and focus on other activities. We will suffer the anxiety and panic of meeting deadlines on your behalf. This free time can also help you furnish other areas of programming you are not good at.
  • Plagiarism free content guarantee – We carry out in-depth research on all the content we write and do not copy paste from other sources. We only deliver 100% original content. We use a plagiarism detecting software to ensure this.
  • Punctual delivery of content – We will deliver your content on time as promised without any delay. We are not like some other online writing providers who take assignments from students and fail to meet the deadline. The service we provide students is ethical in nature. We will first ensure that we are able to meet all your requirements and due date before taking on your assignment. We are not only after completing your task, we also make sure that the content we submit to you is the best and will earn you top grades. If we feel that we will be forced to compromise on quality to be able to deliver your assignment on time then we will not take it. A quality service is what has made us stand out from the crowd and we will never lower our standards
  • Fair rates and amazing discounts – Well written documents at a fair price is what most students are looking for. No other site offer the best rates than us. We came up with the rates with our students in mind. We know how students work hard to get money. We never charge hefty fees, our rates are custom-made to suit the budget of the student. You will exceptional solutions at a very fair price. We value our clients and reward them with discounts. If you use our service repeatedly then you will get a discount. Our payment methods are also very secure and flexible.
  • Free rework on your content – Our experts are very proficient and rarely make mistakes. It is very unlikely that students come back to us for rework. However, in any case this happens, we will offer you with free unlimited revisions. Nonetheless, this will depend on the instructions you had submitted to us along with your assignment. This service will not be free if we find that you have made changes to the guidelines you had asked us to follow. We will consider your rework request as a new order and charge you a fee.
  • Best quality guarantee – as mentioned earlier, we do a recheck on every content we write to ensure they meet top standards. The content we deliver is free from all types of errors. We proofread all content and correct all code errors before submitting the solutions to the client. All the content that we write are unique to and customized as per the requirement of the client. In case your assignment is theory in nature, we use grammarly software to correct all spelling errors. We know that it is the quality of the work we do that will make you avail our services again in future.

What more can a student ask for.  Send us an email at info@ProgrammingHomeworkHelp.com now or engage our customer support executives on a discussion via our online python help chat facility. We have all the answers you are looking for. We are sure that our experts have handled more intricate topics than the one troubling you now.  Your days of searching “do my python homework” or “do my python assignment” on the internet are over.  Your search ends here because we are reliable and can be trusted.

We have a strong base of clients who can testify on the positive effect our service has had on their lives. You too can improve your grades and be the best in your class. That will only be possible if you avail our Python programming assignment help. Your satisfaction is our priority. That is why we will do everything to ensure you pass on your tasks. So what are you waiting for? Contact us immediately when you have deficient knowledge in Python programming. If you are not an adept Python programmer then this is the best place for you to sharpen your skills. Our tutors will walk you through all the concepts step-by-step until you have grasped them. You will not be lagging behind in your Python coursework if you avail our services.