I want to use the round() function.
step 1: take a number from the user
step 2: use the round() func on the input
end
I do ot know why i keep getting "ValueError: invalid literal for int() with base 10"
This is what I have been doing:
print('Enter a number to be rounded : ')
num = input ()
num = int () #converting str from the input() to int
print (round (num,2))
Top comments (3)
Read your code line by line and try to understand each line and each symbol.
You need to learn about types also:
input()
returns astr
int ()
is a function, it takes a parameter, astr
and converts it to an number (an integer).Here is what happens in your code:
num = input()
: you assign the result of input() to a variable callednum
, if you typed10
and enter, num contain the string'10'
.num = int()
When you do this, you will change the value ofnum
. Alsoint ()
needs a parameter! This is why you have an error. No parameter is not a valid value to pass to this function.Solution:
You can combine everything in one line but it's less readable:
Bonus
I believe type annotations are actually a good help for newcomers to really understand what is going on:
Hi, played with it further using your example
"""
print ("This application rounds your number to 2 decima places")
print("enter number: ")
num_str = input ()
print (type (num_str), "This is the input type")
num = float(num_str)
print (type (num), "This is the str converted to float")
print ("number entered is:" , num_str)
print ("after applying the round func to 2 decimal gives: ", round(num,2))
"""
one liner below
print ("This application rounds your number to 2 decima places. Enter number: ")
num = round(float(input()),2)
print(num)
Hi Loik, thanks for this easy to follow breakdown.
I tried the first two steps but was getting the feedback in the attachment, not sure what is wrong now.