DEV Community

Discussion on: #Python question

Collapse
 
loki profile image
Loki Le DEV • Edited

Read your code line by line and try to understand each line and each symbol.
You need to learn about types also:

  • input() returns a str
  • int () is a function, it takes a parameter, a str 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 called num, if you typed 10 and enter, num contain the string '10'.

  • num = int() When you do this, you will change the value of num. Also int () needs a parameter! This is why you have an error. No parameter is not a valid value to pass to this function.

Solution:

# I cut it in small steps so you can understand each one.
num_str = input()  # read a string typed by the user
num = int(num_str) # convert the string to a number
result = round(num, 2) # perform rounding to 2 decimals

You can combine everything in one line but it's less readable:

num_rounded = round(int(input()), 2)

Bonus

I believe type annotations are actually a good help for newcomers to really understand what is going on:

num : str = input()
num : int = int(num)
result : int = round(num, 2)
Collapse
 
godwin_france profile image
Saharan-sub

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.

Collapse
 
godwin_france profile image
Saharan-sub

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)