MIT 6.189 Homework 1 Programming Exercises

Yes, specifying the ASCII codes for "a", "z", "A", and "Z" directly is perfectly fine, since the numbers are explained with comments. Many programmers will recognize those values, but the comments are helpful, just in case.

Could anyone take a look at my last line and advise how it could be done more efficiently please. It works, but seems to be to clumsy.

fname = raw_input("What is your first name: ")
lname = raw_input("What is your Last name: ")
print ("Enter your date of birth: ")
month = raw_input ("Month?")
day = raw_input ("Day?")
year = raw_input ("Year?")
print (fname + " " + lname + " " + "was born on" + " " + month + " " + " " + day +","+ year.)

@philgil I am using Python 2.7 so there aren’t parentheses in the print statement…If you are using Python 3, then add the parentheses like you have.
Python 2:

print "%s %s was born on %s %s,%s" % (fname, lname, month, day, year)

Python 3:

print ("%s %s was born on %s %s,%s" % (fname, lname, month, day, year))

There is also the .format() method.

print "{} {} was born on {} {}, {}" .format(fname, lname, month, day, year)

There is a lot of information on web about string formatting and string formatting type codes, including dealing with strings, integers, decimals, etc.

Here’s one way to simplify it, since commas concatenate and add a space after the string being concatenated.

print fname, lname, "was born on", month, day + ",", year + "."

However, I’m leaning towards @bkglass’s solution because it is very easy to read.


You can put more than one whitespace (spacebar) character between quotes if you want to. They’re much like other characters. You can also write unwriteable characters like a newline or a tab like this: \n, \t respectively.

Thanks for the replies. I am using python 2.6.6, so I guess the parentheses is not required. ( That is what I did wrong initially. Was the same as Cedar_Mora’s code, but with parenthesis, and it didn’t work properly. I appreciate the feedback.

In this example, (exercise 1.14 (4)) the code will not run in IDLE 2.6.6 unless I use the “double quotations”. I see even in the preview window to the right of this typing it is not acceptable. Any particular reason, or just one the things that you need to know? ( that you cannot use # in a single quote string)

count = 0
for letter in ’Snow!’:
  print ’Letter #’, count, ’is’, letter 
  count += 1

That’s an odd situation. I tried it on my computer and it worked fine, but then tried it on [repl.it][1] and it spat out an error. When I ran it with double quotes it ran fine. I think the interpreter thinks that you meant to start a comment by the #, instead of including it within the string. I guess all interpreters aren’t made equal.

Personally, I generally stick with double quotes “” for strings, then there’s less worry about apostrophes and things like that. Plus, coming from a C++ background, they use double quotes for strings and single quotes for single characters.
[1]: http://repl.it

1 Like

For single quotes, we need to use the apostrophe ’ not the back-tick ` or any special single quote character that is typical of word processors.

Strings delimited by single quotes are handy when they contain double quotes, and strings delimited by double quotes are handy when they contain single quotes. You can also use an escape character to include quotes in strings. Strings can also be delimited by three single quotes or three double quotes. The result is same, in other words, once the string has been created, it does not matter what delimiters or escape characters were originally used to create it.

Examples of valid strings …

s1 = "Hello world"
s2 = "Monty Python's Flying Circus"
s3 = 'The "Hello World" program'
s4 = "The \"Hello World\" Program"
s5 = 'Monty Python\'s Flying Circus'
s6 = '''Monty Python's Flying Circus'''
s7 = """The "Hello World" Program"""

s2, s5, and s6 are all equal, even though different delimiters or escape sequences were used to create them. s3, s4, and s7 are also equal to each other.

Thanks Glenn. Cedar_Mora was able to replicate my problem and pointed me in the right direction. It was single quote that I was using, not a backtick or any other special character. It seems that the # character in my IDLE was causing the problem which was only resolved by using double quotes.

Started out with some of my own amazing code :blush:, but ended up with nearly the same as the example, because I had to keep changing it to make it work. I got it to work the other night, and thought I would have another crack at it tonight because I still don’t “get it”.

Tried from memory to redo it like this

def checkinput(input):
    if input == "rock" or input == "scissors"\
    or input == "paper":
        return True
        print checkinput(input)
    else:
        return False
       
def rps(player_1, player_2):
        
    if rps(player_1)== rps(player_2):
            print ("This is a tie")
    elif (player_1 =="rock" and player_2 == "paper")\
            or (player_1 == "scissors" \
            and player_2 == "rock") \
            or (player_1 == "paper" \
            and player_2 == "scissors"):
                print ("Player_2 Wins")
    else:
        print ("Player_1 Wins")
    #elif:
     #   checkinput == False
      #  print ("This is not a valid object selection")

but keep getting this error.


Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    rps("rock", "rock")
  File "C:\Python26\Phils examples\rps.py", line 12, in rps
    if rps(player_1)== rps(player_2):
TypeError: rps() takes exactly 2 arguments (1 given)

so I tried with different inputs.


Traceback (most recent call last):
  File "<pyshell#19>", line 1, in <module>
    rps("rock", "paper")
  File "C:\Python26\Phils examples\rps.py", line 12, in rps
    if rps(player_1)== rps(player_2):
TypeError: rps() takes exactly 2 arguments (1 given)```

I tried with both the same inputs and with different inputs.

Obviously still don't "get it". Anyone care to help a guy out?
1 Like

The error occurs not when you call the function, like rps("rock", "paper"), but inside the function if rps(player_1) == rps(player_2): What you have there calls the function that you are already inside. If you wanted to compare the two player’s choices, you might compare them directly, like this: if player_1 == player_2

1 Like

Thanks @Cedar_Mora (haha, can’t just say thanks! post has to be at least 20 characters!)

1 Like

I did it… Only took 4.5 hours to get working. No wonder I am so far behind… (anyone want help with the Tetris programming :wink: )

def checkinput(input):
    if input == "rock" or input == "scissors"\
    or input == "paper":
        return True
       # print checkinput(input)
    else:
        return False

def rps(player1,player2):
    if checkinput(player1)and checkinput(player2):
        # print player1,player2   # these are just for trouble shooting.
        # print checkinput(player1),checkinput(player2)
        if player1==player2:
            print("This is a tie")
        elif player1 =="rock" and player2=="scissors"\
             or player1 =="paper" and player2 =="rock"\
             or player1 =="scissors" and player2 =="paper":
            print ("Player 1 wins...")
        else:
            print ("player 2 wins...")
    else:
        print ("not a valid input")
    
print rps("rock","paper")
print rps("rock", "scissors")
print rps("paper","scissors")
print rps ("rock", "boobs")
print rps ("rock", "rock")

Oops, just realised I should have used “return” instead of “print” for the results. Print returns “None” whilst return does not. >

def checkinput(input):
    if input == "rock" or input == "scissors"\
    or input == "paper":
        return True
       # print checkinput(input)
    else:
        return False

def rps(player1,player2):
    if checkinput(player1)and checkinput(player2):
        # print player1,player2
        # print checkinput(player1),checkinput(player2)
        if player1==player2:
            return("This is a tie")
        elif player1 =="rock" and player2=="scissors"\
             or player1 =="paper" and player2 =="rock"\
             or player1 =="scissors" and player2 =="paper":
            return ("Player 1 wins...")
        else:
            return ("player 2 wins...")
    else:
        return ("not a valid input")
    
print rps("rock","paper")
print rps("rock", "scissors")
print rps("paper","scissors")
print rps ("rock", "boobs")
print rps ("rock", "rock")

I tried to do it from scratch again without help, and did this code

def valid_input(input):
if input =="rock" or "paper" or "scissors":
  return True
else:
 return False```

but this didn't work as it has to be 

if input ==“rock” or input == “paper” or input == “scissors”
``
Can someone advise what is the difference please?

Regarding …

if input =="rock" or "paper" or "scissors":

… each subexpression between the or operators is evaluated, then the or operators are applied. Consequently, the above is evaluated as …

if (input =="rock") or ("paper") or ("scissors"):

So, input is only compared to "rock". In a logical expression, a non-empty string is considered to be equivalent to True. Therefore, since "paper" and "scissors" are each equivalent to True, the entire condition is always equivalent to True.

Use …

if input =="rock" or input == "paper" or input == "scissors":

… instead.

1 Like

Thank you Glenn. I appreciate your feedback.