How to fix unexpected EOF while parsing in python 3.6? - python-3.x

Im getting the EOF at the end of the program when i try to run it. i dont really know how to fix it. at first i was getting "if" as an invalid syntax but i think i was able to fix that. thanks for the help
while True:
try:
print("Do you want to enter a number?")
print("y - yes")
print("n - no")
choice = int(input("Enter here: "))
if choice == y:
print("")
count = number
for indice in range(1,number + 1, 1):
print(number + indice)
print("")
print("All done")

You're missing a except to match try.
Note that there are other issues with your code that will break it, even once you've added except. For example,
if choice == y:
...
This should be 'y' instead of y. As it is, y is expected to be a variable, but you're looking to match on the user input 'y' or 'n'.
Also, if you want a string input, then:
choice = int(input("Enter here: "))
will throw an error if you enter, say, 'y':
invalid literal for int() with base 10: 'y'
Try taking things one line at a time and making sure you understand what's supposed to happen at each point, and test it. Then put them together.

Related

Found error "not all arguments converted during string formatting" in Python

I found an error that says
File "", line 6, in
TypeError: not all arguments converted during string formatting"
while I'm trying to implement a while True loop in Python. I am trying to identify even and odd numbers with Python. Any suggestion for my problem?
Here's my code:
print("Identification Odd/Even number")
while True:
input = input ('Enter The Number ')
if input %2==0:
print("Even")
elif input %1==1:
print("Odd")
next_step = input ('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break
else:
print('You have input the wrong format')
The first thing you should not do is, that mixing variable names with function names. The line input = input('Enter number here: ') means that in the first pass the function input() will no longer be the function you want it to be, instead it will be string you got back from the first loop-pass.
Also you want to go on with some calculations. input (the function) will return a string, not an integer.
In order to get an integer from a string you should do a cast user_input = int(input('Enter number here: ')).
user_input is a integer and you can go on with you modulos operations.
So all in all I suggest based on your code:
change the variable name input to something else
do a cast after retrieving the user first user-input
for checking if a given number is odd or even there are only two cases to cover, which you can express with if-else-case.
input % 1 == 1 will always be False because there is no integer that is not divisible by 1.
If you want to continue to ask the user if he wants to go on, you probably want the user to give an answer you specified.
This will need another while-loop.
Why?
If the user gives an arbitrary answer, you want to continue to ask as long as the user gives an apropriate answer.
This is an answer you explicitly asked for.
To do that I have done something like this:
next_step = None
allowed_answers = ['No', 'Yes']
while next_step not in allowed_answer:
next_step = input('Want to go on? (Yes/No)')
If you want to give feedback to the user, something like this solved this riddle for me:
allowed_answers = ['No', 'Yes']
while True:
next_step = input('Want to go on? (Yes/No)')
if next_step not in allowed_ansers:
print('You have input the wrong format')
else:
break
All in all I would do something like this:
allowed_answers = ['No', 'Yes']
while True:
user_input = int(input('Enter The Number:'))
if user_input % 2 == 0:
print("Even")
else:
print("Odd")
next_step = None
while next_step not in allowed_answer:
next_step = input('Do you want indetify again? (Yes/No)')
if next_step == 'No' :
break

Name not defined error while using eval((input)) for an if statement

I'm studying Zed shaw's learn python 3 the hard way book and there's a part in the code i'm trying to improve.
My aim was to have an if statement with the condition that the input the user gives is of int type.
def gold_room():
print("This room is full of gold. How much do you take?")
choice = eval(input("> "))
if type(choice) is int:
how_much = choice
else:
print("Man, learn to type a number.")
if how_much < 50:
print("Nice, you're not greedy, you win!")
exit(0)
else:
print("You greedy bastard!")
gold_room()
It works if the input is indeed an integer but if I type in a string i get the error:
NameError: name 'string' is not defined
I tried to use int() but then if the input is a string I get an error.
Is there a way to do this?
Use choice = int(input("> ")). The int function will convert the string that the input function gives you into an integer. But if it can't, it will raise an exception (ValueError), that you may want to try-except.
Using #Lenormju 's answer I wrote this and it worked like a charm.
def gold_room():
print("This room is full of gold. How much do you take?")
# used try to check whether the code below raises any errors
try:
choice = int(input("> "))
how_much = choice
# except has code which would be executed if there is an error
except:
dead("Man, learn to type a number.")
# else has code which would be executed if no errors are raised
else:
if how_much < 50:
print("Nice, you're not greedy, you win!")
exit(0)
else:
dead("You greedy bastard!")
Thank you to everyone who took the time out to respond

Really basic python3 user input type

I want to ask a user for a number(among other things) and if they input anything other than an int, it should tell them to try again.
I'm still getting use to python syntax, what's the best way to do this?
excerpt below of what I tried:
try:
num = int(i)
except ValueError:
while type(num) != int:
num = input("Please input an actual number or q to quit: ")
while True:
num = input("Input a number. ")
if num.isdigit()==False:
print("Try again.")
else:
break
This should work unless if there's a negative value entered in which case you need to make a check if the first character is a - sign.

finding largest and smallest number in python

I am very new to programming, please advise me if my code is correct.
I am trying to write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number.
largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == 'done':
break
try:
fnum = float(num)
except:
print("Invalid input")
continue
lst = []
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))
Your code is almost correct, there are just a couple things you need to change:
lst = []
while True:
user_input = input('Enter a number: ')
if user_input == 'done':
break
try:
lst.append(int(user_input))
except ValueError:
print('Invalid input')
if lst:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
Also, since you said you're new to programming, I'll explain what I did, and why.
First, there's no need to set largest and smallest to None at the beginning. I actually never even put those values in variables because we only need them to print them out.
All your code is then identical up to the try/except block. Here, I try to convert the user input into an integer and append it to the list all at once. If any of this fails, print Invalid input. My except section is a little different: it says except ValueError. This means "only run the following code if a ValueError occurs". It is always a good idea to be specific when catching errors because except by itself will catch all errors, including ones we don't expect and will want to see if something goes wrong.
We do not want to use a continue here because continue means "skip the rest of the code and continue to the next loop iteration". We don't want to skip anything here.
Now let's talk about this block of code:
numbers = int(input('How many numbers: '))
for n in range(numbers):
lst.append(num)
From your explanation, there is no need to get more input from the user, so none of this code is needed. It is also always a good idea to put int(input()) in a try/except block because if the user inputs something other than a number, int(input()) will error out.
And lastly, the print statement:
print('max: %d\nmin: %d' % (max(lst), min(lst)))
In python, you can use the "string formatting operator", the percent (%) sign to put data into strings. You can use %d to fill in numbers, %s to fill in strings. Here is the full list of characters to put after the percent if you scroll down a bit. It also does a good job of explaining it, but here are some examples:
print('number %d' % 11)
x = 'world'
print('Hello, %s!' % x)
user_list = []
while True:
user_input = int(input())
if user_input < 0:
break
user_list.append(user_input)
print(min(user_list), max(user_list))

Why does this code not let me just check for an invalid input

This is not the whole code but the code I am experimenting with to get a solution for the whole code. I also need an answer for dealing with invalid string inputs.
def menu_payment():
burger_count= (input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
if (burger_count !=int) or (burger_count<=0):
print("You must eneter a positive whole number for your order. Please try again.")
menu_payment()
Try doing this:
def menu_payment():
burger_count = input("How many burgers would you like:")
try:
burger_count = int(burger_count)
valid_number = 1
except:
print(burger_count, " is not a valid number")
valid_number = 0
if valid_number == 1 and burger_count > 0:
print ("I will get your burgers right away")
else:
print("Please put a valid number and no negetives")
The issue with checking for a valid string is coming from your if statement. I would suggest first, checking if the value is an int, then check the value for it. That is the easiest and least confusing way to fix that issue.
Input will always convert the user input to string. Therefore, entering "1" is the string of "1", not the integer.
You could try wrapping your input with an int function like:
burger_count = int(input("Please input the number of Racquet Burgers (Cheese Burgers) you would like: "))
However, this would throw a ValueError if anything other than an integer is entered.
Also, I don't think checking the variable type works like that. You can do something like:
if type(burger_count) is not int:
<do something>
Probably super inefficient (pre coffee scripting is bad) but here's how I would handle this:
def menu_payment():
while True:
try:
burger_count = int(input("burgers: "))
except ValueError:
print("You must eneter a number for your order. Please try again.")
continue
else:
if burger_count <= 0:
print("You must eneter a number for your order. Please try again.")
continue
else:
return burger_count

Resources