How Do I Solve: [ValueError: invalid literal for int() with base 10:] - valueerror

command= " "
while True:
command = int(input("how old are you? "))
if command <= 12:
print("you're ticket is free.")
elif command <= 15:
print("you're ticket is $20.")
elif command > 15:
print("you're ticket is $50.")
elif command == "exit":
break
As I write exit it gives a ValueError,
ValueError: invalid literal for int() with base 10:'exit'

You should check if the command is exit before trying to convert the command to int:
while True:
command = input("how old are you? ")
if command == "exit":
break
command = int(command)
if command <= 12:
print("you're ticket is free.")
elif command <= 15:
print("you're ticket is $20.")
elif command > 15:
print("you're ticket is $50.")

Related

micropython: loading data from a file in function causing an endless loop

I am working on a lopy4 from pycom and I have encountered an od problem while loading config data from a txt file:
def loadFromConfigFile():
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()
loadFromConfigFile()
When I use this function my programme gets stuck here:
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
while not lora.has_joined():
time.sleep(loraJoinTime)
print('Not yet joined...')
print("joined!")
setClock()
The sleep function doesn't work and the print function spams "Not yet joined..." in the terminal window.
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()
When I don't wrap this code into a function everything works. When I write the function after the hardcoded loop everything works as well.
Thanks, to nekomatics comment I solved the issue. I simply wasn't aware of the global keyword in python. To stay with the same logic as before, the code should look like this.
def loadFromConfigFile():
global uuidExpected
global app_eui
global syncClockTime
global loraJoinTime
global bleScanInterval
global mainLoopWaitTime
global hbInterval
f= open('config.txt')
for line in f:
if "uuidExpected" in line:
uuidExpected=line[13:len(line)-1].strip()
elif "app_eui" in line:
app_eui = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "app_key" in line:
app_key = ubinascii.unhexlify((line[8:len(line)-1]).strip())
elif "syncClockTime" in line:
syncClockTime=float(line[14:len(line)-1].strip())
elif "loraJoinTime" in line:
loraJoinTime=float(line[13:len(line)-1].strip())
elif "bleScanInterval" in line:
bleScanInterval=int(line[16:len(line)-1].strip())
elif "mainLoopWaitTime" in line:
mainLoopWaitTime=int(line[17:len(line)-1].strip())
elif "hbInterval" in line:
hbInterval=int(line[11:len(line)-1].strip())
f.close()

Errors that I don't understand

I am trying to write a code from the following tutorial:
https://www.youtube.com/watch?v=9mAmZIRfJBs&t=197s
In my opinion I completely wrote it the same way, but it still gives an error. Can someone explain to me why Spyder(Python 3.7) does this.
This is my code:
I tried using another input function so raw_input instead of input. I also tried changing my working directory and saving the document
This is my code:
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = raw_input(prompt='Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = raw_input(prompt='Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = raw_input(prompt='Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
and this is the error
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
Traceback (most recent call last):
File "C:\Users\johan\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 3267, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-93-2d7193d6cafb>", line 1, in <module>
runfile('C:/Users/johan/Desktop/Unie jaar 2/untitled2.py', wdir='C:/Users/johan/Desktop/Unie jaar 2')
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 704, in runfile
execfile(filename, namespace)
File "C:\Users\johan\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/johan/Desktop/Unie jaar 2/untitled2.py", line 35
selection = raw_input(prompt='Please select an option: ')
^
IndentationError: unindent does not match any outer indentation level
The code should give a list of restaurant is 1 is put in. You are able to add a restaurant to the list if 2 is put in. 3 is like to but then you remove. 4 picks a random restaurant from the list. 5 does nothing.
It's imperative that you indent correctly in Python, as such;
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 29 14:47:27 2019
#author: johan
"""
import random
restaurantsList = ['boloco', 'clover', 'sweetgreens']
def pickRestaurant():
print(restaurantsList[random.randint(0,2)])
def addRestaurant(name):
restaurantsList.append(name)
def removeRestaurant(name):
restaurantsList.remove(name)
def listRestaurant():
for restaurant in restaurantsList:
print(restaurant)
while True:
print('''
[1] - List restaurant
[2] - Add restaurant
[3] - Remove restaurant
[4] - Pick restaurant
[5] - Exit
''')
selection = input('Please select an option: ')
if selection == '1':
print('')
listRestaurant()
elif selection == '2':
inName = input('Type name of the restaurant that you want to add: ')
addRestaurant(inName)
elif selection == '3':
inName = input('Type name of the restaurant that you want to remove: ')
removeRestaurant(inName)
elif selection == '4':
pickRestaurant()
elif selection == '5':
break
Python is indentation sensitive, and when creating a function or any statements you need to indent any code inside that function or you will get the error you have above.
Additional note: You're using print() which is python2 and raw_input which is python3, so I've assumed Python3 and changed the raw_input() for input().
You have 4 spaces before print statement within while loop, but all other lines in that loop have 3 spaces indent only, starting from selection = raw_input...
You should add a space at the start for every line starting from selection = raw_input... and below.

Unexpected output avoiding try/except

I wrote this peace of code that is supposed to check whether the device is a RPI and output the temperature.
import os
def CheckIfPi():
try:
res = os.popen('vcgencmd measure_temp').readline()
return float((res.replace("temp=","").replace("'C\n","")))
except:
return 0
def ReturnTemperature():
if CheckIfPi() > 0:
print("The temperature of the Pi is: ", CheckIfPi())
else:
print("This is not a Pi.")
ReturnTemperature()
The output I get:
/bin/sh: 1: vcgencmd: not found
This is not a Pi.
The output i didnt expect to get was /bin/sh: 1: vcgencmd: not found

Error: pandoc document conversion failed with error 127

|................................................................ | 98%
|.................................................................| 100%
output file: test.knit.md
/usr/lib/rstudio-server/bin/pandoc/pandoc +RTS -K512m -RTS test.utf8.md --to html --from markdown+autolink_bare_uris+ascii_identifiers+tex_math_single_backslash --output test.html --smart --email-obfuscation none --self-contained --standalone --section-divs --table-of-contents --toc-depth 3 --template /usr/lib64/R/library/rmarkdown/rmd/h/default.html --variable 'theme:cerulean' --include-in-header /tmp/Rtmp4CjD4R/rmarkdown-str6f6421e357bc.html --mathjax --variable 'mathjax-url:https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML' --highlight-style haddock
Error: pandoc document conversion failed with error 127
Occasionally, I run the codes and it completed 100% and created a md format file.
> traceback()
10: eval(expr, envir, enclos)
9: FUN(X[[i]], ...)
8: lapply(aesthetics, eval, envir = data, enclos = plot$plot_env)
7: f(..., self = self)
6: l$compute_aesthetics(d, plot)
5: f(l = layers[[i]], d = data[[i]])
4: by_layer(function(l, d) l$compute_aesthetics(d, plot))
3: ggplot_build(x)
2: print.ggplot(x)
1: function (x, ...)
UseMethod("print")(x)
There is no ggplot function run inside the RMarkdown but there is ggplot error when I tried to traceback(). However there is an error Error:127, any solution?
Googling the error message indicates that ‘status 127’ means that commands are not being found.

Print When Expression Jasper reports

Is the following Print When Expression invaild:
29 <= $F{selfawarenesscore} <= 45
I get the following error in JasperReports Server
com.jaspersoft.jasperserver.api.JSExceptionWrapper:
Errors were encountered when compiling report expressions class file:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
calculator_subreport2_EmotionalSelfAwareness40QI41_1370531739954_546871: 233:
unexpected token: <= # line 233, column 83. 1 error
I want to print a text field when $F{selfawarenesscore} is the above mentioned range.
Any help is appreciated.
Try:
$F{selfawarenessscore} >= 29 && $F{selfawarenessscore} <= 45