Questions?

Please post your Python related questions in this forum. You are also welcome to answer questions, make comments or discuss a topic.

Q: Somebody (I believe Patrick) after the class today asked me if there is a way to separate real and imaginary part of a complex number.
A: Yes, there is a way to separate them. See following example:
>>> z = 4 + 5j
>>> a = z.real
>>> b = z.imag
>>> print a
4.0
>>>print b
5.0

Statement 1 creates a complex number. Statement 2 assigns real part of z to a. Statement 3 assigns imaginary part of z to b. Then we print values of a and b to test our claim.

By Dinesh

I was asked by Schauna to post a link where the list of functions available in a module can be located. We talked about math module today and there are many such modules bundled with python source. You can have a look at them here:
http://docs.python.org/library/

The math module is numbered 10.2 as on 08/27/2009

By Dinesh

Dinesh, I'm not sure what you mean when you tell us to execute The list of all attributes and functions of the module math. Do you want us to actually execute them or to print a list of the functions?

schauna

By swright

I just want you to print the names of the methods/functions available in math module. However, it will be good for you if you try to run them and understand how they work.

By Dinesh

After the first line, something like...

>>>name = raw_input('What is your name?')
>>>What is your name?

What variable should I use to have Python recall the name when saying hello?...As this applies to all the rest of the parts of the assignment as well.

By bmarshall9

A direct answer to this question will solve part b of Assignment2. Therefore, I am providing a rather obvious hint here.
When you say
>>>name = raw_input('What is your name?')

Python will assign whatever the user enters in the variable "name". if in the next line you say
>>>print name
you will see whatever the user typed. This is what you should use to access user's input.

By Dinesh

If we have a string like this:
>>>str = "Moe, Larry, and Shemp had a little lamb, named Mary"
and we want to split it at spaces as well as at punctuation marks. The intended list should look like
myList = ["Moe","Larry","and", "Shemp", "had", "a", "little", "lamb", "named", "Mary"]

if we split on space (" ") we get something like this:
>>>myList2 = str.split(" ")
>>>print MyList2
['Moe,', 'Larry,', 'and', 'Shemp', 'had', 'a', 'little', 'lamb,', 'named', 'Mary
']
notice comma "," after Moe and other words which we do not want.

This can be done by using "regular expressions" which is outside the scope of our course. Interested students are advised to read Chapter 27 page 447-452 of text book.
For this specific example the code is:
>>>str = "Moe, Larry, and Shemp had a little lamb, named Mary"
>>>import re
>>>myList = re.findall(r'w\+',str)
>>>print myList
['Moe', 'Larry', 'and', 'Shemp', 'had', 'a', 'little', 'lamb', 'named', 'Mary']
which is the intended output.

Again, this is advanced level topic and out of the scope of this course.

By Dinesh

When working with the "in" operator with lists, I ran into a question.
Let's say that L1=[1,2,3,[4,5]]
>>>3,[4,5] in L1
this gives (3, True) as the answer.
>>>1,2 in L1
gives (1, True) as answer
>>>4,5 in L1
gives (4, False) as answer

My question is... what is the significance of the number before True or false in the answers? Why does it return this instead of simply true or false?

By johngrese

This is a good question and interesting observation too.
if you want to check membership of an item you use in operator,
for example
>>>L=[1,2,3,[4,5]]
>>>3 in L
True
>>>4 in L
False
>>>[4,5] in L
True
If you want to check for membership of two or more items you do not separate them using comma, you use "and" or "or" like this:
>>>1 in L or 2 in L
True
which means if either of the two is in List return true
>>>1 in L and 2 in L
True
which means if both of them are in the list only then return true
>>>1 in L and 4 in L
False

When you say
>>>1,2,3 in L
(1,2, True)
it will check for membership of all the items but instead of returning a True of False answer it will print all but last argument followed by the answer.
>>>1,2,3,[4,5] in L
(1,2,3, True)
>>>1,2,3,4,5 in L
(1,2,3,4, False)

By Dinesh

We discussed in the class that slicing is not possible with dictionaries because we do not have the concept of indexes here as we had with strings and lists.
>>>str="Hello"
>>>str[0]
'H'
0 is the index of H here and hence it returned "H" that is at 0th index.

However we can not do the same thing with dictionaries.
>>>D1 = {1:"Code1", 2:"Code2", 3:"Code3"}
>>>D1[0]
Error
because then it will look for an item (Key-Value pair) with key 0 which is not there.
That is why we say slicing is not possible here. However, you can use two items/keys/values at the same time like this:

>>>D2={1:D1[1]+D1[2],2:D1[2]+D1[3]}
>>>D2[1]
Code1Code2

which is valid. Can you think of an application where this can be used?

An example would be to transmit data over internet into parts. Your secured data can be broken into parts and delivered over internet in the form of D1 in above example. D2 is what gives you your complete original data. Another example:
>>>Encoded = {"Part1":"Dinesh","Part2":" Agarwal"}
>>>Decipher = {"Password":Encoded["Part1"]+Encoded["Part2"]}
>>>Decipher["Password"]
Dinesh Agarwal

By Dinesh

Bouncing off of the example that Dinesh just gave, I think I have a couple of possible uses for using 2 key value pairs at the same time....dinesh, please let me know if I am off target.

1. For sending information like credit card numbers over the internet. The credit card number could be separated from the person's name, expiration date, security code, etc.... and then re-assembled when the information is received by the vendor.

2. Another possibility would be in situations where a person would need to send their social security number. The social security number could be separated from the person's name, address, birthday, etc. during transmission of information. Then it could all be re-assembled when the info is received by the gov't agency etc.

these two examples are pretty similar in nature, but seem pretty common.

By johngrese

If you want to print multiple values in one print statement you can do this way:
>>>x=10
>>>y=20
>>>z=30
>>>print "Numbers: x=%d, y=%d, z=%d" % (x,y,z)

By Dinesh

We can use % operator to specify a printing format. For example:
>>>print "%0.2f" % 4
>>>4.00
The format specifies the minimum length before decimal point, number of digits after it. In the example above, %0.2f specifies that we need exactly 2 numbers(space for them) after the decimal point, 0 means that we don't need any number before the decimal point. However, this 0 doesn't truncate digits if they are there. It is also clear from the fact that it printed 4 above.

What if we have a format string similar to "%2.2f"?
It means there should be at least space for 2 numbers before decimal point. If you try it on your interactive prompt of python you can not notice it in case of 2. Try "%20.2f" and you will see what we mean here.

>>>print "%20.2f", 2.3
>>> 2.30

Where do we need it?
If you had to write a software for Walmart that prints their invoices, you would want to have your item names and their respective prices properly aligned in their columns. This format string comes handy in that case.

By Dinesh

I may have written this down incorrectly from the board last week, but I have been trying to get it to work, and keep getting errors.
I am trying to print every-other word from question 2 of the assignment using a for loop. Here is what I have:
l=['one','two','three','four','five','six','seven','eight','nine','ten'] #this is a List of the 10 words

for i in l:
if i % 2 == 0:
print l[i]

i have tried moving the [] braces around to different parts of the statement, and writing it a couple of different ways...still haven't had any luck.
I have gotten several different errors, but here is the one that i got from the code above:
Traceback (most recent call last):
File "", line 2, in
if i%2==0:
TypeError: not all arguments converted during string formatting

By johngrese

Found a solution to the problem in the above comment. Here it is:
len() operator allows range() operator to get the indexing values for the 10 words entered, and thus perform the mod(%) operation Everything seems to work nicely this way.

for i in range(len(l)):
if i%2==0:
print l[i]

By johngrese

The error in the above code is because of the type of values being used with % operator.
Think about this: 3%2 = 1, what is "three" % 2?
When we use % operator with strings it works as a format string, similar to a %2.2f in a print statement.

The correct way to get the desired output would be a loop like this:

for i in l:
if l.index(i) % 2 == 0: print i

In this, instead of checking whether that item is odd or not we check if the index of that item is odd or not.

By Dinesh

Hello!
hope everyone is having a good weekend.
I have a question about the sample midterm.
On question 4, (the one about functions)
here is the code---

def func(input):
    input=input.split("")
    input=[int(i) for i in input]
    if len(input) in range(2,9,2):
        print "Program will create "
        if len(input)<=4:
            print "diagonal matrix\n"
            if len(input)==4:
                print " with different values at the diagonal:\n"
                print (input[0],input[1]), "and"(input[2],input[3])
            else: print "with the same values at the diagonal."
        elif len(input)==6:
            print " a triagonal matrix"
        else:  print  " a matrix"
    else: print " There aren't enough values"


i input the code into python, and got an error that says:
input=input.split("")
ValueError: empty separator
Is this the correct code, or did i do something wrong??
Also, I wanted to make sure that I have the indents correct, because this would effect the output of the function....but sorry, I can't seem to make the indents appear on this post :(

By johngrese

First of all, if you want to put code with indentation put it inside pre tag, like this
<"pre"> <-- without quotes
my code line 1
my code line 2
...
<"/pre"> <-- without quotes
After this you need to select "Input Format" (right below the box you are typing this text in) and set it to Full HTML. That way you can display text with indentation.

Coming back to the code, the problem is with the split statement. There should be a space character between those quotes. I just checked the code, I saw that when we call this function (refer Qn 4 of sample midterm, after this function) the string looks like
func("1 2 3 4"), therefore to split this argument string into 4 parts we split it on space. So it should have that space character in split. There is one more error in this code, we need to have an additional comma "," after "and" in line
"print (input[0],input[1]), "and",(input[2],input[3])"

By Dinesh

Good evenin!
I can't seem to find the pattern in question 7b.
I've tried everything I can think of to make the iteration print the correct things, and haven't had any luck.... Also... can't seem to make it print the 'guess' either.
The only way I can think of to make this thing work is to re-write the whole thing.

b.	
guess=0
inp=[10,11,3,5,7,9,11,120]  
i=0
  
   while True:
             if inp[i]>10: guess+=1
             elif inp[i]==10: guess+=2    
             i+=1
             print “Next ”,i
   print guess

              Output:    
              Next 1
              Next 3
              Next 5
              4

By johngrese

You need to find the patterns given in the question. For instance:
1) Only odd values of i gets printed (1,3 and 5)
2) Loop should terminate "break" after i reaches the value 5 or before it reaches 6 for that matter.
3) Value of guess should be 4 when the loop terminates.

With these observations iterate through the code:
iteration 1) guess = 0, i =0 <- initial values. inp[i] that is, inp[0] = 10 that makes if condition false and elif condition true thereby making guess = guess + 2 = 0 + 2 = 2
then it goes to i = i + 1 = 0 + 1 = 1, and finally prints it "Next 1"
iteration 2) guess = 2, i =1 <- initial values. inp[i] that is, inp[1] = 11 that makes if condition true thereby making guess = guess + 1 = 2 + 1= 3
then it goes to i = i + 1 = 1 + 1 = 2, and finally prints it "Next 2", we do not want that so we have to avoid it. for that we need to introduce a new line. Instead of print "Next" , i we will have:
if i % 2 != 0: print "Next " , i

This will make sure only odd values of i get printed

iteration 3) guess = 3, i =2 <- initial values. inp[i] that is, inp[2] = 3 that makes if condition false and elif condition false too, therefore it goes to i = i + 1 = 2 + 1 = 3, and finally prints it "Next 3"

iteration 4) guess = 3, i =3 <- initial values. inp[i] that is, inp[3] = 5 that makes if condition false and elif condition false too, therefore it goes to i = i + 1 = 3 + 1 = 4, and because of the if statement we introduced in iteration 2 nothing gets printed.

iteration 5) guess = 3, i =4 <- initial values. inp[i] that is, inp[4] = 7 that makes if condition false and elif condition false too, therefore it goes to i = i + 1 = 4 + 1 = 5, and finally prints it "Next 5"

iteration 6)guess = 3, i =5 <- initial values. inp[i] that is, inp[5] = 9 that makes if condition false and elif condition false too, therefore it goes to i = i + 1 = 5 + 1 = 6, and because of the if statement we introduced in iteration 2 nothing gets printed.

iteration 7) guess = 3, i =6 <- initial values. inp[i] that is, inp[6] = 11 that makes if condition true and elif condition false , therefore guess = guess + 1 = 3 + 1 =4, then it goes to i = i + 1 = 6 + 1 = 7, and finally prints it "Next 7" but we do not want any value of i > 5 printed. Therefore we need additional condition in the line we replaced earlier:
if (i%2 !=0) and (i<=5):print "Next ",i
At this point guess becomes 4, which is when our loop should print guess and terminate.

So we add this line too:
if guess == 4: break

In short, the final code will look like this:

guess=0
inp=[10,11,3,5,7,9,11,120]  
i=0
  
   while True:
             if inp[i]>10: guess+=1
             elif inp[i]==10: guess+=2    
             i+=1
             # print “Next ”,i <- replaced 
             if (i%2 !=0) and (i<=5):print "Next ",i
             if guess == 4: break: 
   print guess

              Output:    
              Next 1
              Next 3
              Next 5
              4
By Dinesh

How do we visually tell what font size or margin boundaries there are from a presented xml doc?

By krozier3

I will try to mark font sizes for this exam.

By Dinesh