Input within if statement python3 - python-3.x

This program works fine in python2, but prints error after inputing '1' at the prompt when running it in python3. I'm wondering if there is still a way to accept user input within an if statement or if I'd have to go about this differently. My program below:
#!/usr/bin/python3
select_one = input('Please enter a number from the menu below:
\n1.Convert Celcius to Farenheit \n2. Convert Farenheit to Celcius\n>\t')
if select_one == 1:
c = input('Please enter the temperature\n>\t')
f = c*(9.0/5.0)+32
print(f, 'F', sep='')
elif select_one == 2:
f = input('Please enter the temperature\n>\t')
c = f*(5.0/9.0)-32
print(c, 'C', sep='')
else:
print('Error')

By default the input() takes value as string in python 3.. so you might want to change input as
select_one =int( input('Please enter a number from the menu below: \n1.Convert Celcius to Farenheit \n2. Convert Farenheit to Celcius\n>\t'))

The other answers will get you partway, but a nicer way to handle input in your script would be something like this:
def input_type(prompt, outputType):
while TrueL
try:
return outputType(input(prompt))
except ValueError:
print("Invalid input. Required type is {}".format(outputType.__name__))
You can then replace your first call to input with input_type(<your prompt>, int) and the second two with input_type(<your prompt>, float) without changing the rest of your code.
As a side note - your conversion from fahrenheit to celsius isn't quite right. You might want to test it by converting from celsius to fahrenheit and back again.

You are accidentally relying on the fact that in Python 2, input() would parse the input, not just return it as a string. So "1" (str) becomes 1 (int). But in Python 3, input() does what raw_input() used to do, so the returned value is always a string.
To fix it, change this:
if select_one == 1:
To this:
if select_one == "1":

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

How can I make my python script determine if a number is an integer or a floating point depending on the mode its set to?

I am trying to create a function that would take a user inputted number and determine if the number is an integer or a floating-point depending on what the mode is set to. I am very new to python and learning the language and I am getting an invalid syntax error and I don't know what to do. So far I am making the integer tester first. Here is the code:
def getNumber(IntF, FloatA, Msg, rsp):
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
Rsp = int(input("What number would like to test as an interger?"))
A = rsp
if rsp == "A":
while True:
try:
userInput = int(input("What number would like to test as an interger"))
except ValueError as ve:
print("Not an integer! Try again.")
continue
else:
return userInput
break
The problem with the code you shared is :
The syntax error you mentioned is probably because the except clause has to be at the same indentation level as try, and same for if and else of the same if/else clause. All the code in the function should be indented 1 level too. Python requires all this to identify blocks of code.
You don't need to give 4 arguments to the getNumber() function if you're not using them. This isn't really a problem, but you'll have to pass it some 4 values each time you call it (for example getNumber(1,2,3,4) etc...) to avoid missing argument errors; and these won't matter because you're not doing anything with the given values inside the function - so it's a little wasted effort. I rewrote it in the example below so that you aren't dealing with more variables than you need - it makes the code clearer/simpler.
You also don't need break after a return statement because the return will exit the enitre function block, including the loop.
Try this and see if it makes sense - I've changed a lot of the code :
def getNumber():
while True:
try:
userInput = int(input("What number would like to test as an integer ? "))
return userInput
except ValueError as ve:
print("Not an integer! Try again.")
continue
print("What would you like to do?")
print("Option A = Interger")
print("Option B = Floating Point")
chosen_option = input()
if chosen_option == 'A':
integer_received = getNumber()
print(integer_received, "was an int !")
else:
print("You did not choose 'A' or 'B'")
To determine whether a number is a float or integer, you can use this approach
float is nothing but the integer with floating-point(.).
to determine this we first need to convert it to string and find does it contain a point or not.
number = input("Enter a numbeer\n")
if number.find(".") == -1:
# find will return -1 when the value is not in string
print("it is integer")
else:
print("it is float")

Code for "enter" key press without any input in Python

I am new to Python and am trying to make this interactive guessing game using Python 3. At ANY point in the game, if user just presses "Enter" without any input, it crashes to "ValueError: invalid literal for int() with base 10: ''" What do I add here?
Just to reiterate, I am new to programming. I am trying to code this entirely only using concepts I have learned so far, so everything is fairly basic.
# 'h' is highest value in range. 'a' is randomly generated value in the range. 'u' is user input
import random
h = 10
a = random.randint(1,h)
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
while u != a:
if 0 < u < a:
print("Please guess higher.")
u = int(input())
elif a < u < h:
print("Please guess lower.")
u = int(input())
elif u > h:
u = int(input("Whoa! Out of range, please choose within 1 and %d!" %(h)))
elif u == 0:
print("Thanks for playing. Bye!!")
break
# I was hoping to get the below response when user just presses "enter" key, without input
else:
print("You have to enter a number.")
u = int(input())
if u == a:
print("Well done! You got it right.")
Your issue is that you're automatically converting the result of the input() call to an int, so if the user presses enter without actually entering a number, then your code will try to convert that empty string to an int, hence the error ValueError: invalid literal for int() with base 10: ''. You could add a check to make sure that the user actually enters some input before converting it to an int directly, something like this:
u = input()
while u == '':
u = input('Please enter a number')
u = int(u)
However, this doesn't stop users from entering an invalid number, such as 'a' and causing a similar error, so a better solution to catch both of these issues could be:
u = ''
while type(u) != int:
try:
u = int(input("Please choose a number between 1 and %d. You can exit the game by pressing 0 anytime: " %(h)))
except ValueError:
pass
The try except catches that error that you were seeing earlier where the user enters something that doesn't resemble a number and the while loop repeats until the user enters a valid number
That is happening because u = int(input()) always tries to convert whatever it was given into an integer. An empty string can not be converted to an integer -> you are getting this mistake. Now, python has try/except/else/finally clause exactly for this type of scenario.
What I recon you should do is something like that
while True: #loop forever
try:
u = int(input("Please, enter a number: ")) #this tries to accept your input and convert it to integer
except ValueError: #executes if there is an error in try
print("That isn't a valid integer, please try again")
else:
print("u =",u)
break #break the loop if there was no mistakes in try clause

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.

How to fix unexpected EOF while parsing in python 3.6?

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.

Resources