At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
What are you stuck with?
@carlsmith I've followed the rules, so first I tried to determine whether a number is an odd number. Now I'm trying to find out whether the odd number I've found is a prime. Here's what I've done so far: import math candidate=29 if (candidate/2)*2 == candidate: print candidate, 'is even' else: print candidate, 'is odd' for i in range(2,candidate): if candidate % i == 0: print candidate, 'is not a prime' else: print candidate, 'is a prime'
Gimme a minute, I'll get back to you.
Sorry, I had to go check what a prime number was, I'd forgotten :) Firstly, you don't need to import math for this one. Where you're struggling is in that you are printing that the number 'is not prime' every time the expression candidate % i == 0 evaluates to True and that candidate 'is a prime' every time the expression is False. You need to collect your answers up until you compete this process, then check them to see whether candidate % i == 0 is always or only sometimes True or False.
You may want to consider using a list and the append method. >>>a =  # an empty list >>>a.append(25) >>>a.append(50) >>>print a [25, 50] >>> for each in a: >>> print a 25 50 >>>
so should I use true false statements ? like if candidate % i == 0: value=True ... wait I'm even more confused. what do you mean by completing the pricess ?
I guess that could be - but P1 is give in Lecture 2, which means this problem should be solved pretty much using basic commands such as if/else/while/print/range .. I'm sure there's simple solutions, but those solutions would be far too complex to understand right now. what the professor says is to first define a number (or maybe a list of numbers), then decide if the number is an odd. then check if its a prime number using math and mod. the next step is to print the 1000th number in the list but I'm going to first try and figure out how to do it myself :) so the part wheere I'm checking whether its a prime is the complicated one (shouldn't be but..)
Do what you were doing, but don't print the result each time you test i. You are assigning each of the numbers in the range(2, 29) to i, then testing it. Just because a number doesn't divide evenly by i, doesn't mean it is prime, because you will assign other values to i that might work. You need to gather up the results of each test, not print them, just gather them into a list or something, then check each item in the list to see if they are all the same, to see that no value for i allowed for the expression candidate % i == 0 to be True.
You can do this without a list, but it'll mean reworking your script quite a bit.
The trick is to make sure that you only print 'number is prime' or 'number isn't prime' once. Not each time you test with a given value for i. You have to test all possible values for i, before you know what to print.
modulus is always available, you don't need to import math. It's sqrt() that people often import from math.
so just to make sure. what I need to do is to take a number (the candidate), and divide it by all the prime numbers smaller than this number. then see if any of the results comes up without a reminder (like 4 divided by 2) then the number is not a prime. else, it is ?
Not quite, you need to take a range of numbers and assign the first one to a variable, then check whether candidate divided by that value equals zero. Then assign the next value in the range to the variable and repeat. You have done this already, you're on the right track. You just need to remember that you are trying to confirm that the candidate can not be cleanly divided by any number in the range. You can not confirm that candidate is a prime until, you tested dividing it by each number in the range. If there are NO numbers in the range that candidate can be cleanly divided by, it is prime. If you find that candidate % i == 0 evaluates to True, for any value, then candidate is not prime. You can often know that candidate is not prime half way through testing all possible values for i, but you can never know that candidate is prime until you've tested every possible value for i.
ahh, so I need to set the range first and loop it. otherwise it won't work with just one number. right ? so my problem is right now .. forgetting to set a range of numbers first.
because all it did up until now is partially test the 'candidate' number. like you said.
Maybe try creating a simple function which tests if its prime. Here's an example (made it in 2min ): import math def isprime(x): if x==1: return False if x==2 or x==3: return True if (x/2)*2==x: return False for i in range(3,math.sqrt(x)+3,2): if x%i==0: return False return True for i in range(1,1000): if isprime(i) is True: print i,'is prime'
I tried to avoid sqrt (this time) because he didn't talk about it at all. how about this : import math candidate=9 if (candidate/2)*2 == candidate: print candidate, 'is even' else: print candidate, 'is odd' for i in range(2,candidate): while candidate % i == 0: print candidate, 'is not a prime' else: print candidate, 'is a prime'
also tried to avoid def (which i partially understand but again he hasn't talked about it yet) that's lecture 4
if (candidate/2)*2 == candidate: print candidate, 'is even' else: print candidate, 'is odd' for i in range(2,candidate): while candidate % i == 0: print candidate, 'is not a prime' OK, THIS works, but it's go bugs I don't understand: if put the number 97 (which is a prime) it will say : 97 is odd. 97 is a prime. However if I put the number 95 (which is not expected to be prime), it would loop. why? else: print candidate, 'is a prime'
http://pastebin.com/t0S1Qg03 try this and let me know what you think
There's a typo, ignore the word 'no' on line 10
http://pastebin.com/ECTipSni That's the link without the typo :) Sorry, I'm a bit back and forth, I'm at home and I've got kinds bombing about the place.
this is good. I'm going to try and understand it .. that's the main idea. don't wanna copy :) the next part is to print the 1000th number, which means I would have to count until a certain number and try many ? is there a command to count how many results I get ?
you can do something like tally = 0 for each in range(a, b): if some_condition == True: print 'this one's correct' tally += 1 # shorthand for tally = tally + 1 print tally
By the way. I really really appriciate your help !!! Thanks for this time you're investing to explain and figure things out !
You're welcome, but I just noticed that the code I posted was buggy anyway, so perhaps I don't deserve that thanks. I'll sort it out and post a new link. I was trying to help you out, but it's really busy where I am. I'll post a solution in a little while.
I guess buggy's good - it would give me a chance to understand why it is.
http://pastebin.com/KU0CXFx3 That should work properly. If you don't want to spoil the fun of doing it yourself, just rewrite it in your own style. Maybe learn the basics of lists and do it that way. Have fun and best of luck with it.
http://code.google.com/p/swfk/downloads/list this will help me but it seems like most of y'all already know most of these things, lol. i just downloaded it, and browsed through it, it reminds of Karel, move, turn left, ect... commands, thanks carlsmith, and ranlab too, for asking questions that has lead me to some more help, knowledge...
confused ? import math num = 0 do = True while num < 2: num = input('Enter a number greater than one: ') if num % 2 == 0: print 'number is even and not a prime.' do = False else: print 'number is odd. checking for prime' if do == True: for i in range(2, num): if num % i == 0: print 'not a prime' do = False if do == True: print 'prime' else: print 'not a prime' if do == True: print num, 'is prime.' tally = 0 for tally in range(1, num): if do == True: print num, 'is the', tally, 'prime' tally += 1 # shorthand for tally = tally + 1 else: print num, 'is not a prime'
https://gist.github.com/944126 Try reading through this, I've just rewritten it from scratch, it is about as explanatory as I could write it. If you're still struggling, I'd suggest just moving on a bit and coming back to this later.
candidate=1 #Already know that 2 is prime primeCount=1 while (primeCount<=1000): isPrime="true" i=2 halfCand=(candidate/2) while (isPrime=="true") and (i<=halfCand): if ((candidate%i)==0): isPrime="false" else: i+=1 if isPrime=="true": print(candidate, "is a prime.") primeCount+=1 #else: #print(candidate, " is not a prime.") candidate+=2 print("The 1000th prime number is ",(candidate-2))
Why not just use isPrime = True rather than isPrime = 'true' You don't need to use a string in this situation, you can just use the boolean values, True and False. Notice the capitalisation and the lack of 'quotes'.
how do you code it that way? i just tried by taking the quotation marks out, and got an error: Traceback (most recent call last): File "
", line 7, in
NameError: name 'true' is not defined
by the way, i just happened to find that. i couldn't have written that. i don't know what i'm doing. i just finally figured out how to do the first one: #console (for example using the raw_input operation), and the ability to store values in a #variable, so that the program can access that value as needed. #Problem 1. #Write a program that does the following in order: #1. Asks the user to enter his/her last name. #2. Asks the user to enter his/her first name. #3. Prints out the user’s first and last names in that order. # Using raw_input print "Enter your last name: " lastname = raw_input() print "Enter your first name: " firstname = raw_input() print "Hi", firstname,lastname, "welcome to Python Programming." That raw_input is powerful! i see that it is, i guess you would call it a function, because of the ( ) but, it's interesting how you can use it to hold something, and or also print it at the same time. Like for example: name=raw_input("What is your name? ") print "Hello, " + name + "!"
true is not defined because you forgot to Capitalise it, you must use True and False, they are values in there own right. raw_input is a function, you're right, but it doesn't really 'hold' anything. All functions can take arguments and then return values. The raw_input function takes one, optional argument, which is a string that it will print as a prompt. It always returns whatever the user types in. That's why, if you do a = raw_input('type here') the function will print 'type here', then wait to get something from the user, then return that value, essentially evaluating to that string. So if the user enters 'abc', the above statement is no different than writting a = 'abc' Functions don't really hold anything, they take zero or more parameters, do some logic, then return some value or values. You'll soon start writing your own so you'll see then better how they work. Python just has a bunch of handy ones predefined, called Built-in Functions, that are always available and then libraries full of more specialised ones you can import.
You are getting there though. It is difficult to get at first. Once you've written a few functions and class definitions, the built-in stuff becomes much easier to understand. At the moment, you've just got to kind of try and remember what everything does. Soon it'll all look pretty obvious.
yeah as i typed, said, "hold" i sort of questioned my wording, in my mind, but couldn't have explained it like you just did, thanks...
No worries, I know myself, it is difficult at first to define what you're thinking in plain English. You soon pick up the terms other people use and then it makes it a lot easier to get your head round other peoples explanations. Just part of the learning process.
Yep, beautiful. Capitalizing TRUE works! or i guess i should say, "True", lol
what i don't understand is how do the students get it from the lectures on how to do the problems. I watched the first lecture, and i don't even think he even demonstrated raw_input, at all. The second lecture is more coding, but still don't think he elaborated on it... But i guess they have help from TAs... And also I guess they just have to research it like i did. but i just got lucky, this time. Well it's not all luck... Determination!
One thing to always remember is that Python expressions are evaluated on contact. Think of an expression as the expression of a value, but not the value itself. So 2 + 2 is an expression that evaluates to 4. The Python Interpreter evaluates every expression on contact ~ if it reads one, it immediately treats it as if it were the value itself. You can create some crazy expressions and they will simply be reduced to the value they express as soon as they are read. A variable will be evaluated on contact, a function call will be evaluated on contact, an expression containing function calls and variables will be evaluated on contact. It's worth baring in mind. When you do an if or a while conditional, you're just writing if (some expression): or while (some expression): If the expression evaluates to True, the block will run, else it will not. I know it seems a simple point to go to so much trouble to always bare in mind, but it should help you understand what you're looking at as your code gets more complex. P.S. you generally don't need (parenthesis) around an expression unless you're using them like you would in maths (1 + 2) * 3 A lot of people seem to be using them on here, I dunno where they got that from, but I didn't want my example above to reinforce that habit. Just write an actual expression, like tally = 0 while tally < 50: tally += 1
Yeah, the lectures are not the best place to learn Python. You should aim to find other resources and use the lectures more for CS theory, which is of questionable benefit when you're starting out. Try looking for some books, Learning Python and Programming Python, both by Mark Lutz, are the best ones out there I and many others think, but it can be handy to grab the dumbed down stuff too, it'll help as you will get stuck with Lutz sometimes. His two books are about three thousand pages all together, so it's in depth, but it does expect some real effort on the readers part.
Please excuse all the typos, I have just been jotting stuff down and hitting Post.
Yeah, i've been stocking up on books. thank God for the internet, places where you don't have to spend hundreds of dollars. like i have done in the past for books... Mark Lutz name rings a bell. i know you mentioned O'Reilly before, i have some of them apress, wrox, etc.. various languages...
I know, book prices are insane. Safari Online is worth a look, still a bit pricey, but it can be an affordable, hassle free, legal alternative to spending a grand a year on books that are becoming obsolete by the time they're printed.
well we have to at least give them credit here for having spell checker, :D
:) I've gotta shoot off for a bit, no doubt we'll chat some other time.
right! i'm surrounded by books that cost so much money and now only a person that would by the brooklyn bridge, would give me a good price... but they do sometimes still come in handy, however you can't beat a Internet search...
nice talking to u. now, back to the books...
i was just looking at what i typed, they have a spell checker, but not a grammar and syntax checker, lol well, u know i'm talking about, what i mean...
@carlsmith : thank you, thank you, thank you :) I've actually moved to lecture 3 now but figured out some things. I guess. so I've used a flow chart to make things clear. what do you think about this ? does this make sense ? http://www.gliffy.com/gliffy/#d=2648371&t=py1
wait, wrong link here's the correct one. http://www.gliffy.com/pubdoc/2648371/M.png
Nice work grupiyati, yeah, flowcharts are a good idea. I'll often grab a pen and paper and do a quick, stepped, block diagram when looking at recursive code. Whatever helps you get your head around the concepts in a way that empowers you. Because everything you're doing is an abstraction, because you're not thinking about the actual mechanical reality of the machine you're operating, but operating through the various abstractions of that machine that Python offers ~ and enables through it's lower level magic ~ you have to remember that, fundamentally, you're working in an imaginary world, that interacts with the real world, but only indirectly. When you do, say, a web page, you don't think about Internet protocols or whether this page's binary representation will actually travel, as packets, as light in an Ethernet cable, or electricity on a wire. Who cares? That's some other guys job. You're job is to find a way to take abstractions like
andand use them to solve some problem ~ sell a product, help blind people read, entertain some guy after a hard day at work. Whatever you do, even if it seems silly at first, if it helps you adapt your mind to adopt paradigms that help _you_ get control over these machines and make stuff happen, don't worry what works for the next man. We all, more or less, try and adopt an object oriented paradigm when working with Python, but how you conceptualise that will differ from how do it. I guess that's part of the reason people tend to have such strong views on seemingly trivial things, e.g. whitespace and curly braces, everything's an object etc. etc.. Chat soon, I've got to go into work now. All the best.
thank you ! :) what do you think about this flow chart ? does it make sense or is there anything wrong with it?
The chart looks good to me, but it's quite pixellated in my browser, Chrome. If it helps you, then it's a good thing, don't worry too much about making things as correct as they might be and just enjoy the language and exploring the ways you would do things through it. Think about each element you know, print, raw_input, %, ==, for, if, while, as if they're Lego bricks, or Legos if you're in the States. You can take just a dozen different types of Lego element and, using a bucket full of one type , a couple of another, perhaps one of some other type, you can build amazing contraptions. It's how you combine groups of different types in different ways that is the real skill. Logic and creativity are the keys to success. Each time you learn a new Python element, you'll learn a few of the ways that element can be used, then you should spend some time playing around creatively, interactive mode's good for this, and see how you can combine that new element with the ones you know already, the combos are endless. Play with what you know, learn a little more, play some more. Above all else, enjoy it. If you're not engaged and motivated by what you're doing, you should do something different. You'll never run out of combos.
what i don't understand is, if Python is "all that", why don't they at least have a decent error message telling u that the function raw_input is "old", depreciated.. etc. I tired it in the never version of Python and got a error message, but no real clue why it wasn't working.. wasting my time on nonsense.
using functions def esprimo(num): divisor=num-1 es_primo=1 while divisor>1: restante=num%divisor if restante==0: es_primo=0 break divisor=divisor-1 return es_primo n_primo=1 primo_actual=3 num_actual=3 while n_primo<1000: if esprimo(num_actual)==1: primo_actual=num_actual n_primo=n_primo+1 num_actual=num_actual+1 print "el numero primo 1000 es",primo_actual
Python's error messages do get more readable with practice, but there's a far bit of room for improvement. IPython does some stuff that helps put the trace in context. There are depreciation warnings, as you suggested, but not everything is covered. You can suggest improvements, but they'll only go into Python3, even then, it's only if they're ever implemented ~ could take a while.