This is an example on how to use command line in Jupyter notebook to run code only by the file's name and some inputs like this ipython RollDie.py 600
.
I wrote the code myself and took the online example and tried to run both but it keep giving me the same error says ValueError: invalid literal for int() with base 10: '-f'
. The error is in line 9 because of the int(sys.argv[1]))
i tried to convert it to float then int but its the same just saying could not convert string to float: '-f'
.
I searched a lot for solutions for my case but found nothing like this only found a way where i should write a method to read form a file(I'm new to dealing with files in coding btw), but the book in his example it wants to create the file after writing the code and didn't mention anything about this error.
Note: argv[0]
is the string 'RollDie.py'
and argv[1]
should be the input string '600'
so converting argv[1]
to int should be without problems.
The book title is "Python for Programmers".
The Code:
"""Graphing frequencies of die rolls with Seaborn."""
import matplotlib.pyplot as plt
import numpy as np
import random
import seaborn as sns
import sys
# use list comprehension to create a list of rolls of a six-sided die
rolls = [random.randrange(1, 7) for i in range(int(float(sys.argv[1])))] # Range is written that way so we can modify the code with the command line directly and no need to rund the code by yourself(A pro gamer move).
# NumPy unique function returns unique faces and frequency of each face
values, frequencies = np.unique(rolls, return_counts=True)
title = f'Rolling a Six-Sided Die {len(rolls):,} Times'
sns.set_style('whitegrid') # white backround with gray grid lines
axes = sns.barplot(values, frequencies, palette='bright') # create bars
axes.set_title(title) # set graph title
axes.set(xlabel='Die Value', ylabel='Frequency') # label the axes
# scale y-axis by 10% to make room for text above bars
axes.set_ylim(top=max(frequencies) * 1.10)
# display frequency & percentage above each patch (bar)
for bar, frequency in zip(axes.patches, frequencies):
text_x = bar.get_x() + bar.get_width() / 2.0
text_y = bar.get_height()
text = f'{frequency:,}\n{frequency / len(rolls):.3%}'
axes.text(text_x, text_y, text,
fontsize=11, ha='center', va='bottom')
plt.show() # display graph
%save RollDie.py 1
It seems like -f
is the sys.argv[1] when you’re running the code, which is why you’re getting the error (of course, you can’t convert -f
into a float or string). Are you explicitly stating this when you’re running the file? Not sure, something like:
ipython RollDie.py -f 600
If not, it might have to do with some type of not-shown built-in command. Have you tried using python instead of ipython?