Empty Input line raises an error in Python 3.3 - python-3.3

I'm new at Python and trying some exercises I found on-line. The one I'm busy with requires an text input first, folowed by an ineteger input.
I get stuck on the integer input which raises an error.
I've started by modifying the code slightly to test myself when I first got the error.
Eventually changed it backed to be exactly like the example/exercise had it, but both resulted in the same error, on the same line.
The error raised was:
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
I've checked around a bit and found it get's triggered when the input is empty, but according to what I've read the the rest of the code should handle that.
numOfGuests = int(input())
if numOfGuests:
I expected the code to ask for the input again if nothing was entered, but get the error instead.
Much appreciated.

Update:
I've managed to figure out a work-around, and even though it isn't a answer to my question, I'll take it.
For anyone that's interested, here's what I did:
I changed:
numOfGuests=int(input())
to:
numOfGuests=input()
Only once something was entered did I convert it:
numOfGuests=int(numOfGuests)
so the final block is:
numOfGuests=''
while not numOfGuests:
print('How many guests will you have?')
numOfGuests = input()
numOfGuests=int(numOfGuests)
Any ideas to improve it, or some insight, would be appreciated.

I know this question is 10 months old but I just want to share the reason why you are having an error ValueError.
Traceback (most recent call last):
File ************************ line 7, in <module>
numOfGuests = int(input())
ValueError: invalid literal for int() with base 10: ''
Is because the input() function reads any value and convert it into a string type. Even if you try to input empty or blank.
Sample code:
any_input = input("Input something: ")
print(f"Your input is: [{any_input}]")
Ouput:
Input something:
Your input is: []
Then the blank or empty string will be passed inside the int() function. The int() function will try convert string into an integer with a base of 10. As we all know, there is no blank or empty numbers. That is why it is giving you a ValueError.
To avoid this, we need to use try-except/EAFP in your code:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
except:
# Handle Value Error
And put inside a While-loop to repeat until input is valid.
Sample code:
while True:
try:
# Try to convert input to integer
numOfGuests = int(input("How many guests will you have? "))
# If input is valid go to next line
break # End loop
except:
# Handle Value Error
print("Invalid input!")
print(f"The number of guest/s is: {numOfGuests}")
Ouput:
How many guest will you have? 3
The number of guest/s is: 3

Related

Problem with int(input) and except ValueError [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
I try to validate user input if is integer not in a function.
while True:
try:
number = int(input('Enter the number: '))
except ValueError:
print('Try again. Input phone number, must containing digits. ')
break
print (number)
If I enter number it works prints the number (however Pycharm tells me that variable number in last line might ve undefined) however when it crash instead asking for enter again:
Enter the number: s
Try again. Input phone number, must containing digits.
Traceback (most recent call last):
line 9, in <module>
print (number)
NameError: name 'number' is not defined
In a function it seems easier to make but in this case I'm lost.
break means you leave the loop, even if you've had the ValueError, despite number not being assigned yet.
Instead of putting the break outside the try, have you considered putting it inside, so it only triggers if number gets assigned successfully?
while True:
try:
number = int(input('Enter the number: '))
break
except ValueError:
print('Try again. Input phone number, must containing digits. ')
print(number)

List Addition in python

I am trying to create a function that will add two list such that if list1 is [9,1,2] and list2 is [8,5,3] then the two lists added together would produce a list yielding. ]1,7,6,5] since 912+853= 1765.
The following is the code I have written:
def list_addition(list1,list2):
otlist1=''
otlist2=''
for items1 in list1:
otlist1+= items1
for items2 in otlist2:
otlist2+= items2
strinum = int(otlist1)+ int(otlist2)
return strinum
print(list_addition(['3','6','7'], ['4','9','0']))
I keep getting this error:
Traceback (most recent call last):
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 13, in <module>
list_addition(['3','6','7'], ['4','9','0'])
File "C:/Users/Chuck/PycharmProjects/arrayaddition/Arrays.py", line 10, in list_addition
strinum = int(otlist1)+ int(otlist2)
ValueError: invalid literal for int() with base 10: ''
I obviously know my code even if it did work as written wouldn't be complete as I would still need to put in the final codes to convert the integer variable 'strinum' back to a list, but I can't get there if my code is failing to properly add the two converted lists. When I break down the code and write the two for loops separately, convert them to integers and add them everything works perfectly fine. So the code below was good:
list1=['7','9','6']
otlist1=''
for items1 in list1:
otlist1+= items1
print(otlist1)
ist1=['5','7','0']
otlist2=''
for items1 in ist1:
otlist2+= items1
print(otlist2)
print(int(otlist1) + int(otlist2))
But for some reason when I try to put the two for loops inside a single function I get the error. I am a complete newbie to programming and I want to know what I am not understanding about function syntax. Any help will be greatly appreciated.

Getting time of day from user for silly simple app

I am begginer in Python and I wanted to try to make myslef a simple piece of code that would take my input of time when I came to work and tell me when I get to go home.
Problem is the input formatting and then adding those 8 hours of work into it and having an output.
I can make it work with integers but that is not good enough. I would like to see HH:MM format in I/O
I searched all around the web but what I found are mostly articles and advice about time in general (date and more importantly, the datetime.now) whereas I need it to understand I want to input time when I came to work and time when I get to leave the work, regardless of day and so on.
# When do I get to go home program
# first we need ot define a variable to use it to store the time when I came
# to work
# That is atw (arrived to work)
# gh is "go home"
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
#atw = datetime.strptime(input('enter time you arrived to work in HHMM format: '), "%H%M")
h,m = map (int, time.split(":"))
#gh = atw (hour = h, minute = m)
print (("I came to work #", atw ,"%H%M"))
gh = atw + 0800
print ("You can go home # ", gh)
All sort of error messages, from syntax to problems with format of my input and adding of those 8 hours of work to the final number (gh variable)
Is there some awesome being that could walk me trough how do I actually make python to understand that I am adding time to variable that should be formatted as time (HH:MM) input which is coming form user?
Ok, let's do this step by step, because as you said, there All sort of error messages, from syntax to...
from datetime import time
atw = input ("When I came to work in format of HH:MM \n")
These first two lines work without problem, that's fine.
h,m = map (int, time.split(":"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.time' has no attribute 'split'
Oh, an error, let's read what the error message says: type object 'datetime.time' has no attribute 'split'. Well, that's correct, because we don't want to split time, but the time that we gave to input and that has the name atw, so let's use that:
h,m = map (int, atw.split(":"))
print (("I came to work #", atw ,"%H%M"))
No error, but a weird output:
('I came to work #', '08:17', '%H%M')
You probably didn't want a tuple as output (the parentheses) and wanted to format that output, as I can see from the format string "%H%M". Fortunately python (>=3.6) has a nice solution for that called f-strings:
print (f"I came to work #{atw}")
Hmmm, wait, what about the formatting, that just outputs what we inputed... So make use of h and m:
print (f"I came to work #{h:02d}:{m:02d}")
Do a google search what that :02d means and what other options there are ;)
Next line:
gh = atw + 0800
File "<stdin>", line 1
gh = atw + 0800
^
SyntaxError: invalid token
Hmmm, you want to add 8 hours to get the endtime, but all you get is an syntax error... That's because 0800 is no valid python construct, you probably ment just 8? Let's try this...
gh = atw + 8
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Another error, but why? You are using atw, which is a string, albeit you already split that in two ints h and m, with h representing the hours:
gh = h + 8
print ("You can go home # ", gh)
Ahh, damn that print again. Look above and use f-strings:
print (f"You can go home #{gh}:{m}")
And now try to see if you get a solution using strptime as #mkrieger1 suggested in the comments.
And pleeeeease do a python tutorial :)

Finding a List Position Represented by a Variable

Basically I have a variable equal to a number and want to find the number in the position represented by the variable. This is what I
numbertocheck =1
loopcriteria = 1
while loopcriteria == 1:
if numbertocheck in ticketnumber:
entryhour.append[numbertocheck] = currenttime.hour
entryminute.append[numbertocheck] = currenttime.minute
print("Thank you. Your ticket number is", numbertocheck)
print("There are now", available_spaces, "spaces available.")
loopcriteria = 2
I get this error (in pyCharm):
Traceback (most recent call last): File
"/Users/user1/Library/Preferences/PyCharmCE2017.3/scratches/scratch_2.py",
line 32, in entryhour.append[numbertocheck] =
currenttime.hour TypeError: 'builtin_function_or_method' object does
not support item assignment
How do I do what I'm trying to do?
Though you haven't provided the complete code, I think you only have problem with using append. You cannot use [] just after an append. To insert into a particular position, you need insert
Putting the relevant lines you need to replace below...
entryhour.insert(numbertocheck,currenttime.hour)
entryminute.insert(numbertocheck,currenttime.minute)
# available_spaces-=1 # guessing you need this too here?
P.S. your loop doesn't seem to make sense, I hope you debug it yourself if it doesn't work the way you want.

How can i check to see if somethings already written to a txt and give an error if so python

I am doing a school project and I have to make a voting system that uses a voting code. I need help with the code that opens up the 2 files, checks to see if the code is there and gives a value error if it is.
while True:
Code = input("Enter your 6 digit code: ")
try:
Code = int(Code)
if "0" in str(Code): break
if len(str(Code)) != 6 : raise ValueError
else: break
readt = open("Trump.txt" , "r")
readh = open("Clinton.txt" , "r")
readhh = readh.read()
readtt = readt.read()
if Code in str(readtt) or Code in str(readhh): raise ValueError
else: break
readt.close()
readh.close()
except ValueError:
print("Invalid")
Here are a couple pointers to fix your program:
The if len ... else part seems to leave the while loop either through raise or break. The code that does open is never executed.
Also you call open a lot of times. This will become problematic because leaking file descriptors is a problem. Use the with open(...) statement for this. This way, you cannot leave the file open by accident. Your close statements are behind another if ... else construction that will leave the loop in every case.
Your variable names are a bit opaque, perhaps you want to invent some more telling ones.
Why are there two files? Shouldn't there be only one file that contains all the used codes?
Assuming that you presented all the information in your question this is the solution for your problem:
def code_checker():
codes = []
with open('Trump.txt', 'r') as f1:
for line in f1:
codes.append(line.rstrip())
with open('Clinton.txt', 'r') as f2:
for line in f2:
codes.append(line.rstrip())
code = input('Enter your 6 digit code:\n')
while True:
if '0' in code or len(code) != 6:
print('Invalid code\n')
code = input()
continue
elif code in codes:
raise ValueError
code_checker()

Resources