Python Forum
Converting user input to integers (retitled)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Converting user input to integers (retitled)
#1
The homework initially left line 6 as 'if answer == number1 + number2' to show the error of trying to compare strings to integers, (ie. even if the user entered the correct number, it would still be deemed incorrect).

Once we were shown this error, we 'fixed' it by amending line 6 with the int() function as below;

But why do we turn 'answer' into an integer on line 6 and not when it's being input in line 5? We would have to keep turning it into an integer every time we use it if the code stays as below?

I keep getting caught out with this, i'd prefer to set them as soon as they're introduced to avoid any confusion...

import random
number1 = random.randint(1,10)
number2 = random.randint(1,10)
print('What is '+str(number1)+' + '+str(number2)+'?')
answer=input()
if int(answer) == number1 + number2:
    print('CORRECT!')
else:
    print('WRONG! The answer is '+str(number1+number2))
Thanks!
Reply
#2
You absolutely could convert and assign it on the same line via:
answer = int(input())
And you are correct, if you were using it in multiple places you wouldn't want to convert each time.

Not dealt with in your program however is, what do you do with faulty user input?
Currently if you get something that can't be turned into an int you just crash.

try:
    user_input = int(input())
except ValueError:
   # handle faulty input
You might even wrap something like this is a while loop so that you continued to ask for input until the user gave a valid response.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Simulate an answer based on user input [Beginner needs guidance] Bombardini 1 1,280 Nov-12-2022, 03:47 AM
Last Post: deanhystad
  Print user input into triangle djtjhokie 1 2,361 Nov-07-2020, 07:01 PM
Last Post: buran
  Changing Directory based on user input paulmerton4pope 13 7,962 Aug-14-2020, 11:48 AM
Last Post: GOTO10
  how to add the user input from file into list wilson20 8 4,298 May-03-2020, 10:52 PM
Last Post: Larz60+
  Writing a function that changes its answer based on user input SirRavenclaw 2 2,799 Dec-21-2019, 09:46 PM
Last Post: Clunk_Head
  Print the longest str from user input edwdas 5 4,132 Nov-04-2019, 02:02 PM
Last Post: perfringo
  how to add user input to a dictionary to a graph KINGLEBRON 3 3,020 Jul-31-2019, 09:09 PM
Last Post: SheeppOSU
  New to Python - tiny coding assistance on user input function and assign to variable Mountain_Duck 1 2,491 Mar-23-2019, 06:54 PM
Last Post: Yoriz
  Extracting list element with user input valve 1 2,556 Mar-11-2019, 07:37 PM
Last Post: Yoriz
  turtle polygon as specified by user input johneven 7 10,727 Mar-02-2019, 10:11 PM
Last Post: johneven

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020