Learning Python

B

Byte

I know this is probably a stupid question, but I'm learning Python, and
am trying to get the if function to work with letters/words. Basicly,
I'm trying to write a script that when run, says

Please enter your name:

Then, if the user types myself as the name , the output is OK. Thats
all I want it to do (remember, Im just new). The code Ive tryed is:


x = input(raw_input("Please enter your name: "))
if x==myself: print 'OK'

It kinda works - I can get to the please enter your name bit but then
it simply reprints your input as output. Someone please HELP!

p.s. Im using Ubuntu Linux 5.10 "Breezy Badger". Dont know if you need
that info, but just in case.
 
F

Florian Nykrin

Hi Byte!

Your code should look like this:

x = raw_input('Please enter your name: ')
if x == 'myself': print 'OK'

Because myself should be a string and not a variable name, you have to
put it in quotes.

Regards, Florian.
 
X

Xavier Morel

Byte said:
x = input(raw_input("Please enter your name: "))
if x==myself: print 'OK'

It kinda works - I can get to the please enter your name bit but then
it simply reprints your input as output. Someone please HELP!
>

-->
C:\>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.Help on built-in function input in module __builtin__:

input(...)
input([prompt]) -> value

Equivalent to eval(raw_input(prompt)).
Help on built-in function raw_input in module __builtin__:

raw_input(...)
raw_input([prompt]) -> string

Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise
EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
<--

Where the hell did you get the idea of stacking input on a raw_input in
the first place?
 
B

Byte

Florian Nykrin, that works! Thanks!

p.s. Xavier Morel, you seem to be using Windows, not Linux, and I got
the idea of stacking input on a raw_input from the official Python
Tutorial.
 
?

=?iso-8859-1?q?Luis_M._Gonz=E1lez?=

Use "input" to enter numbers, and "raw_input" to enter strings.
For example:

x = input('Enter your age: ')
y = raw_input('Enter your name: ')
 
F

Fredrik Lundh

Byte said:
p.s. Xavier Morel, you seem to be using Windows, not Linux, and I got
the idea of stacking input on a raw_input from the official Python
Tutorial.

link, please.

</F>
 
F

Fredrik Lundh

Byte said:
p.s. Xavier Morel, you seem to be using Windows, not Linux

what makes you think that basic Python functions work in radically
different ways on different platforms ?

</F>
 
B

Byte

what makes you think that basic Python functions work in radically
different ways on different platforms ?

Assumption. Im also new to programing, so could do something stupid
like think a Windows path is a command/input/etc. (really, ive done
things like that before.)

Now, im running this on a terminal, but am acctually writing my scripts
in a text editor. How can I get a script to do a sum with the editor?
e.g. it asks for a sum, then does it etc.
 
A

Alex Martelli

Byte said:

I think you're confusing the tutorial's use of:

int(raw_input(...

which means "get a string from the user and turn it into an integer" (a
very common idiom), with your use of:

input(raw_input(...

which means "get a string from the user and use it as a prompt to get
any value from the user" (a very peculiar usage).

The difference between `int' and `input' is rather enormous.


Alex
 
B

Byte

Yes, sorry, didnt realise diffrence between int and input. Since i'm
such an idiot at this, any links to sites for people who need an
unessicerily gentle learning curve?
 
X

Xavier Morel

Byte said:
p.s. Xavier Morel, you seem to be using Windows, not Linux
I don't see how this may even remotely be relevant, Python is cross
platform and (mostly) works the same regardless of the OS
> I got
> the idea of stacking input on a raw_input from the official Python
> Tutorial.
>
Reference please, I never saw that anywhere in the tutorial
 
X

Xavier Morel

Byte said:
Assumption. Im also new to programing, so could do something stupid
like think a Windows path is a command/input/etc. (really, ive done
things like that before.)
Don't assume anything when you have no reason to, and especially don't
assume that a cross-platform programming language behaves differently
from a platform to another, especially on built-in basic functions
Now, im running this on a terminal, but am acctually writing my scripts
in a text editor. How can I get a script to do a sum with the editor?
e.g. it asks for a sum, then does it etc.
parse the expression, extract the operands and the operation, apply the
operation to the operands (are you trying to code a calculator?)
 
B

Byte

parse the expression, extract the operands and the operation, apply the
operation to the operands

How? Give me some example code, but please keep it simple.
are you trying to code a calculator?

Not intending to, just trying to learn Python. Suppose what i'm trying
to code is a but like a CLI calculator, but i'm just writing it for my
own educational beifits.
 
X

Xavier Morel

Byte said:
operation to the operands

How? Give me some example code, but please keep it simple.


Not intending to, just trying to learn Python. Suppose what i'm trying
to code is a but like a CLI calculator, but i'm just writing it for my
own educational beifits.

Side note: have you read Dive into Python (http://diveintopython.org/)
yet? If you haven't -- and are done reading the whole python tutorial --
you should, it's a very good and practical read.

Now about the calculator, let's do a simple RPN notation (they're much
simpler to compute than the "regular" notation, see
http://en.wikipedia.org/wiki/RPN for some informations about RPN)

First, we need an input

-->
expression = raw_input("> ")
<--

Now we need to handle this input. An RPN expression is a space-separated
list of tokens, these tokens being either operands (numbers) or
operations. This means that we merely need to split our expression at
the spaces

-->
expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default
split delimiter
<--

Now we have a list of tokens.

RPN calculations involve a stack, to keep the current operands. Python's
`list` has everything you need to emulate a stack

-->
expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default
split delimiter
stack = list()
<--

Now, we have to handle each token.
Either a token is a number (an operand), in which case we have to
convert it to an integer (it's currently stored as a string), or it's an
operation, in which case we have to apply the operation on the last two
tokens of the computation stack and store the result back on the stack.

This means that we have to store addition, substraction, multiplication
and division. Luckily, there is the python module `operator` that stores
an accessor to these operations (add, sub, mul, div). We could store
them in a dictionary with an operation token as index: we feed the
operation token to the dict, it outputs the operation function.

-->
import operator

operations = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default
split delimiter
stack = list()
<--

Good, now all we need to know is to feed each token to the `operations`
dict, let's try with the first token of the RPN expression "1 2 + 4 * 3 +"

Traceback (most recent call last):
File "<pyshell#12>", line 1, in -toplevel-
operations['1']
KeyError: '1'

Well, there is no "1" key in our dictionary, so we get an error. Kind of
obvious.
The Python dictionaries also have a "get" method that takes a key and a
value, and they return the value (default) if the key doesn't exist, how
would that one fare?

Ok, it's return the operation function if it knows the token we feed it,
and "None" if it doesn't.
Now all we have to do is check if it returns None, and if it does we
know it's an operand and not an operation.

First we need to loop on the list of tokens:

-->
import operator

operations = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default
split delimiter
stack = list()

for token in tokens:
operation = operations.get(token, None)
if operation: # If operation is not "None", therefore if the token
was an operation token
pass # do nothing for now
else: # if operation is "None" == if the token is an operand token
pass # do nothing either
<--

Ok, what are we supposed to do if the token is an operand? Convert the
operand (token) to an integer (the token is a string), and then add it
to our computational stack.
The last part is done via the `append` methods of Python's list.

If the token is an operation, we have to apply the operation to the last
two operands of the stack, and push the result back on the stack
To get the last operation of a Python list, we use the `pop`method, it
defaults to returning the last value of a list.

-->
import operator

operations = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
}

expression = raw_input("> ")
tokens = expression.split() # split a string using spaces as default
split delimiter
stack = list()

for token in tokens:
operation = operations.get(token, None)
if operation: # If operation is not "None", therefore if the token
was an operation token
result = operation(stack.pop(), stack.pop()) # apply the
operation on the last two items of the stack
stack.append(result) # put the result back on the stack
else: # if operation is "None" == if the token is an operand token
stack.append(int(token)) # Convert the token to an integer and
push it on the stack
<--

Ok, let's test that shall we?
What happens if we feed it "1 2 + 4 * 3 +", this should return 15 =
(1+2)*4+3.
The result is the only item that should be left on our stack

--> "+": operator.add,
"-": operator.sub,
"*": operator.mul,
"/": operator.div
} operation = operations.get(token, None)
if operation: # If operation is not "None", therefore if the token was
an operation token
result = operation(stack.pop(), stack.pop()) # apply the operation on
the last two items of the stack
stack.append(result) # put the result back on the stack
else: # if operation is "None" == if the token is an operand token
stack.append(int(token)) # Convert the token to an integer and push it
on the stack

<--
Gread. Now let's try it again with the expression "1 4 -". This should
return -3.

-->[3]
<--
Duh, the result is wrong.

This is because when we do operation(stack.pop(), stack.pop()), we use
the last value of the stack as the first operand of our operation (here,
our expression resolves to "operator.sub(4, 1)" which is equivalent to
"4-1", which is wrong).
Let's get out operands in the good order by replacing that line with

-->
operand2 = stack.pop()
operand1 = stack.pop()
result = operation(operand1, operand2)
<--

And now it works, we have a basic RPN calculator.

Homework: truth is that this calculator kind of sucks: it's very easy to
break it.

Try using "-" as your input expression. Or "1 +", or "1 56 + +". What
happens?
Try to modify the calculator to avoid these errors, or handle them
gracefully.

Likewise, entering the expression "5 0 /" results in a Division By Zero
error. Try to handle it to display a friendly message instead of having
the calculator blow.

You have to rewrite everything every time you want to compute a new
expression. Modify the calculator to always ask for new expression until
a specific command is entered (such as "exit")

The calculator breaks (again) if you use a token that is neither an
integer nor an operation (e.g. "1 foo +", or even "foo")
Modify it to handle that kind of false input without exploding in your
hands.

The output is ugly (a list of only one item), try to improve it.

Computing the expression "5 3 /" (5/3) returns "1". Why? How can you
improve it?

Additionally, you currently cannot use floating point numbers (e.g. "1.5
1.3 +") in your expressions (guess what the calculator does?), see if
you could modify the calculator to handle floating point numbers.

Last, but not the least, try to create a Polish Notation calculator
(prefix notation, it's like RPN but the operation is in front of the
operand) and a "maths notation" calculator.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,274
Latest member
JessMcMast

Latest Threads

Top