Why did i have to convert the variables? - python

def main():
account_value = input("Enter your account value: ")
AV = account_value
years = input("Enter how many years you want to save: ")
IR = input("enter the interest rate per year: ")
for i in range(int(years)):
aftervalue = int(AV) + (float(IR)*int(AV))
print(aftervalue)
Why did i have to convert them in the expression in the loop?
Why werent they already treated as ints and a float?

In Python 3, input() returns a string. If you want to use it in arithmetic operations, you have to convert it to int or float first.
You don't need to do it in the loop, it's best to do it just once when you assign the variables.
If you ran your script in Python 2, you wouldn't need to do the conversions. Its input() function evaluates the input as a Python expression, you have to use raw_input() to get the original input as a string.

Related

Why isn't my 'Else' expression showing in this scenario when i try to run my code? [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
What's the canonical way to check for type in Python?
(15 answers)
How can I read inputs as numbers?
(10 answers)
Closed last year.
I am a beginner when it comes to coding. I am trying to run a program on python that takes in kilometers(user input) and returns it in miles(output). I know how to do the task but I wanted to challenge myself by using if statements to check if the user has entered a number:
Kilometers = input("Please insert number of Kilometers: ")
if type(Kilometers) == int or float:
print("This is equivalent to", float(Kilometers)/1.609344, "Mile(s)")
else:
print("This is not a number")
I understand that whatever the user inputs will be saved as a string. However, whenever I run the code, the program always tries to convert the input into miles.
I have specified in the if statement that the type has to equal a float or an int, so shouldn't the output always be "This is not a number" until I change the first line to:
Kilometers = float(input("Please insert number of Kilometers: "))
or
Kilometers = int(input("Please insert number of Kilometers: "))
When programming if statements in Python, each condition must be fully rewritten. For example, you would write if type(Kilometers) == int or type(Kilometers) == float rather than if type(Kilometers) == int or float. Another important thing in your code is that if someone inputs 5.5, you would expect a float value, but Python interprets that to be a string. In order to circumvent this, you can use a try/except clause like this:
Kilometers = input("Please insert number of Kilometers: ")
try:
Kilometers = float(Kilometers)
print("This is equivalent to", Kilometers/1.609344, "Mile(s)")
except ValueError:
print("This is not a number")
What this is doing is trying to set Kilometers as a float type, and if the user inputs a string that cannot be interpreted as a float, it will cause a ValueError, and then the code inside except will run. You can find more on try/except clauses here: Python Try Except - W3Schools
One more thing I noticed is that you should name your variables according to the standard naming conventions, so Kilometers should be kilometers. You can find more on the naming conventions here: PEP 8

How do I convert a string from an input into an integer? (Python 3.9) [duplicate]

This question already has answers here:
Short way to convert string to int [duplicate]
(3 answers)
Closed 1 year ago.
As you know, a user input in Python by default is a string. I tried converting them using the int() function after, however, it still stays as a string.
Code example:
number = input("Input a number: ")
int(number)
print(type(number))
This would give an output of: <class 'str'>
, even though I tried converting them to an integer.
You need to assign the value, because int() doesn't apply on place.
number = int(number)
Python int() function
You also need to assign the converted variable to your number:
number = input("Input a number: ")
number = int(number)
print(type(number))
Or directly like this:
number = int(input("Input a number: "))
print(type(number))

Is there something wrong with this line of code? [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I want to take from the user an input integer, and turning to a string in my code.
My line of code for that is:
num1 = input(int(str("Enter a number: ")))
But the console says: ValueError: invalid literal for int() with base 10: 'Enter a number: '
If this line isn't correct can you show me a way how can I turn an integer that is given by the user to a string in my code?
You have the functions in the wrong order: First you need to turn the input into a Python object, so input() has to be the innermost function (to be applied first). Also, input() will cast the input as a string by default, so you don't need str().
So the line should read:
num1 = input("Enter a number: ")

Error in a basic python code [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 7 years ago.
so I just started Python today. Tried a basic program, but I'm getting an error "can't convert int object to str implicity"
userName = input('Please enter your name: ' )
age = input('Please enter your age: ')
factor = 2
finalAge = age + factor **ERRORS OUT ON THIS LINE**
multAge = age * factor
divAge = age / factor
print('In', factor, 'years you will be', finalAge, 'years old', userName )
print('Your age multiplied by', factor, 'is', multAge )
print('Your age divided by', factor, 'is', divAge )
When I do enter int(age)+factor, instead of age, it works perfectly. But the author says that python auto detects the variable type when you key it in. So in this case when I enter age=20, then age should become integer automatically correct?
Looking forward to any help!!
From the doc
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
As you can see, the input() function in python 3+ returns a string by converting whatever input you are given, much like raw_input() in python 2.x.
So, age is clearly a string.
You can't add a string with an integer, hence the error.
can't convert int object to str implicity
int(age) converts age to an integer, so it works in your case.
What you can do:
Use:
age = int(input('Please enter your age: '))
To cast your input to an integer explicitly.
Your problem is that input returns a string (since in general, input from the command line is text). You can cast this to an int to remove the error, as you have done.
Python only automatically detects the type of your variables in your program if they don't already have a type - it does not automatically convert typed variables to different types.
Python does not know what operation you're trying to make, provided the '+' operator can be used both to concatenate strings and adding numbers.
So, it can't know if you're trying to do
finalAge = int(age) + factor #finalAge is an integer
or
finalAge = age + str(factor) #finalAge is a string
You need to explicitly convert your variables so it won't be ambiguous.
In your case, int(age) returns an integer, which is the proper way to get what you want.

Math with direct input

I just started my first day at uni and there is one of the exercises I am already struggling with. This is the problem: Make code that inputs two given mumbers and output one minus the other
I did this:
number1 = int(raw_input("Type your first number: "))
number2 = int(raw_input("Type your second number: "))
result = number1 - number2
print result
But it was wrong because the input is direct so when the program tested my code it said:
I have always done code that first asks for the information so I have no idea if this is even possible in python or how you do it. Any suggestions are appreciated, thanks.
you need to use :
number1, number2 = map(int, raw_input().split())
result = number1 - number2
print result
In the sample input both the numbers are separated by space, and there is no prompt for the user such as "Type your first number: ", So all yo need to do is take input using raw_input(), then splitting the input on " "(space) by using .split() and then converting each string after splitting to int using the map function.

Categories

Resources