New to Python and instantly confused [duplicate] - python

This question already has answers here:
Basic Python If Statements Using "or"
(4 answers)
Behaviour of raw_input()
(3 answers)
If-else if statement not working properly
(2 answers)
Closed 5 years ago.
I'm taking a python course on codecademy at the moment and decided to try run a simple program on my computer from the terminal.
I created a basic program based on simple if, elif, else statements, really simple code as I'm trying to reinforce the basics that I'm learning, the goal is to form a response, if you have more than 49 credits, you get a congratulatory response and so forth...
firstName = raw_input("Enter your first name: ")
lastName = raw_input("Enter your last name: ")
excellenceCredits = raw_input("Enter the amount of excellence credits
you have so far: ")
if excellenceCredits > 49 and len(firstName) >= 10:
print "Well done " + firstName + " " + lastName + " on the
excellence endorsement, feel proud! You also have an impressive long
name!"
elif excellenceCredits > 49 and len(firstName) < 10:
print "Well done " + firstName + " " + lastName + " on the
excellence endorsement, feel proud!"
elif excellenceCredits < 50 and excellenceCredits > 40:
print "So close " + firstName + ", better luck next time, I bet
the " + lastName + "s are so proud of you!"
else:
print "Keep working hard, you never know what's around the corner..."
The problem is whenever I run the program from the terminal and enter an excellenceCredits value less than 50, it still prints the wrong response, this is probably really simple, but I just can't see whats wrong with the code.

raw_input parses the user's input as a str type, not an int.
Try:
int(raw_input("Enter the amount of excellence credits you have so far: "))
to get closer to your desired behavior.

It looks like you're comparing integers (49, 50, etc.) to the string value of excellenceCredits. This answer has more details.
To compare your raw_input as an integer, convert it by passing it to the built-in function int:
excellenceCredits = int(raw_input("Enter the amount..."))

You are going on a good way, just need to take care when the raw_input you need is of int datatype.
You need to do the following when its datatype is int.
excellenceCredits = int(raw_input("Enter the amount of excellence credits
you have so far: "))
Python 2.x
There are two functions to get user input, called input and raw_input. The difference is, raw_input doesn't evaluate the data and returns as it in string form. But, input will evaluate whatever you entered and the result of evaluation will be returned.
raw_input gives you a string you must convert to an integer or float before making any numeric comparison.
Python 3.x
Python 3.x's input and Python 2.x's raw_input are similar and raw_input is not available in Python 3.x.

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

Problem with checking if input is integer (very beginner) [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 2 years ago.
I'm just starting to learn Python (it's my first language). I'm trying to make a simple program that checks if the number the user inputs is an integer.
My code is:
number = input('Insert number: ')
if isinstance(number, int):
print('INT')
else:
print('NOT')
I have no idea why, but every number gets it to print 'NOT'. If I just make a statement 'number = 1' in the code, it prints 'INT', but if I input '1' in the console when the program asks for input, it prints 'NOT' no matter what. Why is that?
(I'm using Python 3.8 with PyCharm)
When you input something, the type is always a str. If you try:
number = input('Insert number: ')
if isinstance(number, str):
print('INT')
else:
print('NOT')
you will always get:
INT
If all you want is to detect whether the input is an integer, you can use str.isdigit():
number = input('Insert number: ')
if number.isdigit():
print('INT')
else:
print('NOT')

Python giving incorrect output when adding 2 values [duplicate]

This question already has answers here:
How do you input integers using input in Python [duplicate]
(3 answers)
Closed 3 years ago.
I am trying to make a calculator program in Python as a bit of a challenge. I am a beginner to python and I am probably making some really obvious mistake. In my calculator I ask the user to define the values and to select the operation they want to use. With the addition operation the calculator gives a strange output. For an example I am telling the calculator to add '7 + 7'. Instead of giving me the correct answer of 14, it gives me 77. Here is my code so far. Hope somebody can help. Cheers
#Sets the values for calculator to use
val1 = input ("Enter the first value: ")
val2 = input ("Enter the second value: ")
#Asks what operation to use
print ("1. Add")
print ("2. Subtract")
print ("3. Divide")
print ("4. Multiply")
op = input ("What operation should I use:")
#Addition
if op == '1':
print(val1, " + ", val2, " = ", (val1 + val2))
The user input is of string type. That's why 7 + 7 becomes 77. You need to convert them to integer using int() (or float using float()) type to perform arithmetic
val1 = int(input ("Enter the first value: "))
val2 = int(input ("Enter the second value: "))
As pointed out by #Bailey Parker, in case the user input isn't a number, you can consider using try/except as mentioned here
When the + operator's two operands are strings, it will concatenate them together, creating a longer string. You'll need to turn your strings into integers to do math with them.

Python error. cant convert int object to "str" imlicitly (Totally confused beginner here) [duplicate]

This question already has answers here:
Making a string out of a string and an integer in Python [duplicate]
(5 answers)
Closed 4 years ago.
So i decided to make a small string of code that converts your age into lion years (Basically multiplicating your age by 5).
The problem i have is i cant get it to take the age as an integer and input, that or i cant make it print the "lionage" integer below.
Code and error sign below:
name = input ("please type your name in: ")
age = int(input ("please type your age in: "))
age = int(age)
five = int(str(5))
lionage = int(age*five)
print ("Hello " + name + "! Your age is " + age + " but in lion years it's " + str(lionage) + " years")
Error: can't convert 'int' object to str implicitly
I may be wrong on what I got wrong in the code.
(By the way, please prioritize giving me an answer of why its going wrong and how I can fix it simplifying the code to make it smaller. (i want to learn that myself, thanks :) )
Python can print number, string, ... pretty much anything as long as types are not mixed up. In your case, age is a number and the rest of the line you want to print is a string. You need to convert your number to a string by adding str(age) instead of just age.
Age is a integer and you trying to concat with an string. In python, you cannot do that directly.
print ("Your age is " + age)) # <- wrong answer
you must convert age to string before concating
print ("Your age is " + str(age)) # <- Correct answer
Around all variables add str().
For example:
a = 21
print("Your age is " + str(a))
This would output "Hello World" (without speech marks).

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.

Categories

Resources