Why do semicolons not suppress output in doctests? - python

Why do semicolons not suppress output in doctests? A workaround is to assign the result, but I am curious as to why this does not work.
"""
>>> 1+1; # Semicolons typically suppress output, but this fails
>>> x = 1+1 # Workaround: assign result to suppress output.
"""
Failed example:
1+1;
Expected nothing
Got:
2

Unlike other languages like C/C++, semicolons are optional terminators for statements in Python, as you can see in the Repl below:
Python 3.6.5 |Anaconda custom (64-bit)| (default, Mar 29 2018, 13:32:41) [MSC v
1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 1 + 1;
2
>>> 1 + 1
2
However, you may observe a different behavior in say IPython:
In [120]: 1 + 1;
In [121]: 1 + 1
Out[121]: 2
The docs for IPython suggest using semicolons to suppress output. However, this behavior is only specific to IPython and does not in any way extend to Python or its standard libraries(like doctest).

You're thinking of MATLAB or IPython or something. Python semicolons don't normally suppress anything. doctest simulates a normal interactive Python session, not an IPython session, so the semicolon does nothing.

The semicolon has no effect at all.
Doctest reads the expected result from the line following the Python statement (i.e. the part after >>>). In your example, there is no result, so doctest expects no result. That's why it reports "Expected nothing". However, 1+1 returns 2.
The second expression, x = 1+1, has no result, so the test is successful (although nothing really is tested).
Try this for example:
"""
>>> 1+1 # without semicolon
2
>>> 1+1; # with semicolon
2
>>> x = 1+1 # not so useful test
"""

Related

Just started using Python 3 and no matter what I do I can't seem to get exponentials to work. All I get is a blank line when I save and run

As the title says, I've tried all kinds of things. Essentially I'm trying to write a function that accepts an integer as an argument and returns its square.
This is an example of what I've tried on my own:
number1 = "2"
def square_number(number1):
return("number1" ** 2)
This didn't work but I've tried a copy past deal from the internet to check:
number1 = 5
square1 = pow(number1, 2)
This also didn't work. All I see is this:
======================== RESTART: /Users/NK/Documents/Python training/Learning functions.py ========================
>>>
just a blank line.
You are not instructing python to print anything to the screen.
In the first case, you are simply defining a function. More on this later *
In the copy-pasted code, you are squaring number1, but then do nothing with the result. If you want to show it, you need to instruct it:
print(square1)
*
Back to your trial in your trial, there are a few errors.
First, you should put a number in the variable number1. Currently, because you've put 2 inside quotes "2", your variable is a string, not a number. Instead, say number1 = 2 (no quotes).
Second, in your function, you are using quotes around number1. Then this is also a string, so you're not referencing your variable, but you are squaring the string "number1" . This will not work and will throw an error.
Currently nothing is happening because you have only defined what the function should do. You haven't used the function yet.
Note that the parameter of the function can have any name, so you can define it as:
def square_number(a): return a ** 2
Here you've just define what the function should do when called. It is independedn to anything outside of it, like number1.
Then you can call your function, with a parameter:
sq3 = square_number(3)
sq4 = square_number(4)
sq_n1 = square_number(number1)
and then you can print the results, which here I've put in variables
print(sq3, sq4, sq_n1)
Again, note, no quotes, I'm referring to the variables.
I would suggest you start first by:
Reading about python coding convention, for the readability of your code.
Learn how to run the interpreter in your terminal.
Learn how to execute code in a .py file.
Usually, you will write your code in a .py file. But it is a good practice to always try to run every line of your code first at the terminal to know what it will change.
Terminal example
Part of your script squares a number, so you go to your terminal and experiment with the different ways of how can you do squaring in python.
ziadh#Ziads-MacBook-Air ~ % python3
Python 3.10.4 (v3.10.4:9d38120e33, Mar 23 2022, 17:29:05) [Clang 13.0.0 (clang-1300.0.29.30)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> # first method using pow
>>> num_one: int = 3
>>> pow(num_one, 2)
9
>>> pow(4, 2)
16
>>> # second method using **
>>> 4**2
16
Now you are an expert in squaring numbers in python, you go to your .py file and write the following.
num_one: int = 3
num_one_squared: int = pow(num_one, 2)
print(num_one_squared)
# you can also do
num_two: int = 4
num_two_squared: int = num_two**2
print(num_two_squared)

why the result is different between running python interpreter and python code?

I made a simple code on python interpreter and run it.
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 16:02:32) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy as np
>>> x=np.array([0,1])
>>> w=np.array([0.5,0.5])
>>> b=-0.7
>>> np.sum(w*x)+b
-0.19999999999999996
the result -0.19999999999999996 is weird. I think.... it is caused by IEEE 754 rule. But when I try to run almost same code by file, result is a lot different.
import numpy as np
x = np.array([0,1])
w = np.array([0.5,0.5])
b = -0.7
print(np.sum(w * x) + b)
the result is "-0.2". IEEE 754 rule does not affect the result.
what is the difference between file based running and interpreter based running?
The difference is due to how the interpreter displays output.
The print function will try to use an object's __str__ method, but the interpreter will use an object's __repr__.
If, in the interpreter you wrote:
...
z = np.sum(w*x)+b
print(z)
(which is what you're doing in your code) you'd see -0.2.
Similarly, if in your code you wrote:
print(repr(np.sum(w * x) + b))
(which is what you're doing in the interpreter) you'd see -0.19999999999999996
I think the difference lies in the fact that you use print() for your file based code, which converts the number, while in the interpreter's case, you don't use print(), but rather ask the interpreter to show the result.

Sublime text python build different result

I have example that shows different result on terminal and on sublime text build console.
Terminal example:
Python 2.7.10 (default, Jul 30 2016, 19:40:32)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 1000
>>> b = 1000
>>>
>>> print a == b
True
>>> print a is b
False
Sublime text console with python build:
a = 1000
b = 1000
print a == b
print a is b
------
RESULT
------
True
True
[Finished in 0.1s]
First case is correct, but problem here is that sublime gives me wrong result.
Why it shows different result?
I use python 2.7 on both cases.
I tried this in my terminal:
a=1000
b=1000
a==b
True
a is b
True
the Python is operator has funny, sometimes undefined functionality when dealing with integers. I suspect the mismatch above is due to Python trying to do an optimization in the Sublime case (and my terminal) and thus the objects are actually the same whereas the other case it's saving them as two separate variables.
You should NOT use the is operator to do integer comparison, but rather ==.
Another good reason == is suggested for comparison (while no longer integer comparison) is the following case:
a=1000
b=1000.0
a==b
True
a is b
False

integer division gives different result in CPython 2.7 and Spyder

I have encountered a quite weird case in Python.
In Spyder:
>>> 274/365
0.7506849315068493
>>> sys.version
'2.7.6 (default, Dec 20 2013, 14:08:04) [MSC v.1700 64 bit (AMD64)]'
>>>
However in command line it returns 0.
>>> 274/365
0
>>> 274/365 * 1.0
0.0
>>> 274/365.0
0.7506849315068493
Same version of Python.
Could anyone tell what is wrong here? Do I need to put some other options ahead of the program? This is really nauseous since my code gave weird results if I call it through command line..
Spyder executes from __future__ import division in its console.
This is discussed at https://code.google.com/p/spyderlib/issues/detail?id=1646 - it looks like this will be deactivated by default to avoid confusion.
You either use different versions of Python (in Spyder 3.* and on command line 2.*) or in your Spyder there is automatic import for your console including
from __future__ import division
On command line for Python 2.7
>>> 4/3
1
>>> from __future__ import division
>>> 4/3
1.3333333333333333

Beginner of Python: <Syntaxerror: invalid syntax> when trying to import program

This is my first day learning programming. I'm following Python Programming: An introduction to computer science 2nd ed. by John Zelle, and so far things have been going smoothly.
The only trouble is that when I try and import a saved program I get a syntaxerror. I write the program and save it before executing, but then when I try to import it I get the error. I tried opening a fresh instance of the shell but no cigar. I'm using OSX Lion 10.8 and Python 2.7.3. Any help is appreciated. This is what the problem looks like:
>>> #File: chaos.py
>>> #A simple program illustrating chaotic behavior.
>>> def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
>>> main()
This program illustrates a chaotic function
Enter a number between 0 and 1: .25
0.73125
0.76644140625
0.698135010439
0.82189581879
0.570894019197
0.955398748364
0.166186721954
0.540417912062
0.9686289303
0.118509010176
>>> import chaos
Traceback (most recent call last):
File "<pyshell#47>", line 1, in <module>
import chaos
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
My guess is that you are copying the contents of the terminal to the file, verbatim. And there are a lot of thing that should not be there, that includes the version prompt.
The file should have just something like:
#File: chaos.py
#A simple program illustrating chaotic behavior.
def main():
print "This program illustrates a chaotic function"
x=input("Enter a number between 0 and 1: ")
for i in range(10):
x = 3.9 * x * (1-x)
print x
No >>>, no ..., no tabulators and certainly do not copy the version information:
Python 2.7.3 (default, Dec 22 2012, 21:27:36)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
File "chaos.py", line 1
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
^
SyntaxError: invalid syntax
It looks like the first line of your chaos.py script has a line which is not python:
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
It should be removed or commented-out by starting the line with a # sign.
Some tips to keep in mind:
In Python, whitespace is important -- they indicate indentation
level. Do not mix spaces and tabs lest Python raise IndentationErrors.
In texts or web pages, you may see transcripts of interactive
sessions which include >>> or ... indicating the Python prompt or
indentation level. If you transfer the code to a script, you must
remove those.

Categories