Why is 5 larger? (comparing user inputs in a simple if statement) - python

Beginner question here (sorry). I am practicing conditional statements comparing integer inputs. Oddly enough, when I put in "5" as my first input, I am told it is larger than "10" (my second input). I must be missing something because I've stared much too long and can't figure it out.
Code:
print("Enter first number")
first = input()
print("Enter second number")
second = input()
if first > second:
print("Greatest is", first)
elif second > first:
print("Greatest is", second)
else:
print("Both are the same!")
Below are my inputs and the result:
Enter first number
5
Enter second number
10
Greatest is 5
Thank you for your help in advance.

Assuming this is Python, input() returns a string and "5" is lexicographically larger than "10".
You can use int(...) to convert a string into an integer:
first = int(input())

Related

Write a python program to find sum of first and last digit of a number by using loop

Hello I am new to coding and just learn some basics of codding can anyone help me out with this problem :- I have written a code to find 1st and last term using loop but can't add them the code is given below
n = input("enter your number:-")
#By loop
if (n.isnumeric):
for i in range(len(n)):
if i == 0:
print(f" your first digit of the number is {n[0]}")
elif i== len(n)-1:
print(f" your last digit of the number is {n[-1]}")
else:
print("Please enter a number and try again!")
please can someone modify this code to find the sum of 1st and last digit ?
thank you:)
Actually, you're very CLose to the answer you're seeking, there are just a few errors to be corrected. See the revised version, and check?
Note - this is to follow OP's thinking, and make minimum changes.
Of course, there're many alternative ways to achieve it (and more error checking for invalid inputs, but that's another story/exercise).
n = input("enter your number:-") # ex. 123
#By loop
if (n.isnumeric()): # calling the method: isnumeric()
for i in range(len(n)):
if i == 0:
first = n[0] # assign it to first digit
print(f" your first digit of the number is {n[0]}")
elif i == len(n)-1:
last = n[len(n) -1] # assign it to last digit
print(f" your last digit of the number is {n[-1]}") # convert to integer
print(f' the sum of first and last digits: {int(first)+int(last)} ')
# 4 <- given input 123
You already know how to get the last item in a sequence - i.e., n[-1]
Therefore, using a loop is irrelevant.
What you do need to do however is to check 2 things.
Is the input at least 2 characters long?
Is the input comprised entirely of decimal characters
Which gives:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first = inval[0]
last = inval[-1]
print(f'Sum of first and last digits is {int(first)+int(last)}')
else:
print('Input either too short or non-numeric')
Another interesting approach using map() and some unpacking to process the input:
inval = input('Enter a number with at least 2 digits: ')
if len(inval) > 1 and inval.isdecimal():
first, *_, last = map(int, inval)
print(f'Sum of first and last digits is {first+last}')
else:
print('Input either too short or non-numeric')

Asking until the input is in the list?

Trying to understand while loops but after typing in the input a number that is not in the list, it doesn't keep asking until it is one of the numbers in the list.
number = 12
while number not in [0,1,2,3,4]:
number = input("type a number: ")
print(number)
if number in [0,1,2,3,4]:
print('one of those numbers')
else:
break
print('not one of those numbers')
the above gives this if you type 4343:
type a number: 4343
4343
not one of those numbers
If you step through your code you can see that the "number" variable gets what you typed in, 4343. Then you check to see if number is in the list of 0-4. It's not, so execution proceeds down the "else" branch, which is a break. Break will "break" the execution of your loop, so the next thing printed is "not one of those numbers" and execution stops and you are not asked for another input.
If you were to type a number like "4" what would happen? Well, the same thing I think. That's because your input comes in as a string, not a number, and you are asking if the string "4" is in the list of numbers, and it isn't. You need to parse the input as an int, you can do that by wrapping your input call in the "int" function - int(input("Type a number: ")) and now "number" will be an int, not a string.
number = 12
while number not in [0,1,2,3,4]:
number = int(input("type a number: "))
print(number)
if number in [0,1,2,3,4]:
print('one of those numbers')
break
else:
print('not one of those numbers')
continue
As #inteoryx told that when you give an input it's a default string value. You have to convert it to integer and you used break statement if the number not in the list. break gets you out of the loop you should use continue statement instead. I added break in the if statement that will get you out of the loop if the number is in the list.

Why can't I compare an input to a random number in Python

So I basically wanna compare "Number" and "Guess" in the if statement, but no matter what it says they don't match (I get the else response, not included here). Even if I copy the random number they don't match.
Thanks in advance!
import time
def the_start():
points = 0
attempt = 1
print("Attempt:",attempt)
print("Your goal is to guess a number between 1 and 10 - Points:",points)
time.sleep(2)
attempt = attempt + 1
number = random.randint(0,10)
print(number)
guess = input("What is your guess? :")
time.sleep(2)
if guess == number:
points = points + 1
print("OMG YOU WERE RIGHT! Here, have some fake cheers! *cheer*")
time.sleep(5)
guess is a string. You need to do conversion of the string and handle error conditions. int() will convert a string to an integer, but it will throw an exception if the string is not purely numbers.

Can anyone figure out this code for me?

import random
print "Welcome to the number guesser program. We will pick a number between 1 and 100 and then ask you to pick a number between 1 and 100. If your number is 10 integers away from the number, you win!"
rand_num = random.randint(1, 100)
user_input = raw_input('Put in your guess:').isdigit()
number = int(user_input)
print number
if abs(rand_num - number) <= 10:
print "Winner"
else:
print "Loser"
Whenever I try to run this code, the computer always generates the number 1. And if I put in a number that is 10 (or less) integers away from one it will still display the else statement. I will have my gratitude to whoever can solve my predicament. I am new to python try to keep your answers simple please.
raw_input returns a string you entered as input. isdigit() checks whether a string is a digit or not and returns True or False.
In your code you're assigning the return value of isdigit to user_input So, you get either True or False. Then you convert it to a number, thus getting either one or zero. This is not what you want.
Let user_input be just a result of raw_input. Then check whether it is a valid number with user_input.isdigit(). If it's not a number, print an error message and exit (or re-ask for input), else convert user_input to an integer and go on.
The problem is product by this sentenc:
user_input = raw_input('Put in your guess:').isdigit().
The return value of isdigit() is True or False. When you enter 1 or any digit number, it will return True(True=1,False=0), so you will always get 1, if you enter digit. You can change like this:
import random
print "Welcome to the number guesser program.
We will pick a number between
1 and 100 and then ask you to pick a number
between 1 and 100. If your number is 10 integers
away from the number, you win!"
rand_num = random.randint(1, 100)
user_input= raw_input('Put in your guess:')
is_digit = user_input.isdigit()
if is_digit==True:
number = int(user_input)
print number
if abs(rand_num - number) &lt= 10:
print "Winner"
else:
print "Loser"
else:
print 'Your input is not a digit.'
Look at this line:
user_input = raw_input('Put in your guess:').isdigit()
The function raw_input gives you user input, but then you call isdigit and as consequence in your variable user_input you get result of isdigit. So, it has boolean value.
Then in
number = int(user_input) you cast it to integer type. In python true is 1 and false is 0. That's why you always get 1.

How to add up a variable?

I was wondering how I would sum up the numbers they input for n even though it's an input and not int. I am trying to average out all the numbers they input.
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Start now ")
a+=1
In Python 2.x input() evaluates the input as python code, so in one sense it will return something that you can accept as an integer to start with, but may also cause an error if the user entered something invalid. raw_input() will take the input and return it as a string -> evaluate this as an int and add them together.
http://en.wikibooks.org/wiki/Python_Programming/Input_and_Output
You would be better off using a list to store the numbers. The below code is intended for Python v3.x so if you want to use it in Python v2.x, just replace input with raw_input.
print("Enter as many numbers you want, one at the time, enter stop to quit. ")
num = input("Enter number ").lower()
all_nums = list()
while num != "stop":
try:
all_nums.append(int(num))
except:
if num != "stop":
print("Please enter stop to quit")
num = input("Enter number ").lower()
print("Sum of all entered numbers is", sum(all_nums))
print("Avg of all entered numbers is", sum(all_nums)/len(all_nums))
sum & len are built-in methods on lists & do exactly as their name says. The str.lower() method converts a string to lower-case completely.
Here is one possibility. The point of the try-except block is to make this less breakable. The point of if n != "stop" is to not display the error message if the user entered "stop" (which cannot be cast as an int)
n=print("Enter as many numbers you want, one at the time, enter stop to quit. ")
a=0
while n!="stop":
n=input("Enter a number: ")
try:
a+=int(n)
except:
if n != "stop":
print("I can't make that an integer!")
print("Your sum is", a)

Categories