First baby steps into Python and I'm stuck. I want to print the absolute value of an integer that is input by the user. If the integer that is input is a negative value, I want it to return a positive value. I'm converting the string to an integer fine, I'm storing the input 'number' fine, but if I input a negative number it's not doing the eval of the if statement and converting to a positive number by * -1 as you see below. I'm at a loss, should I be defining another variable somewhere here?
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
I performed the tests on my machine and the operation went correctly. Is it returning an error for you?
As a suggestion, you can also use the abs() function instead of multiplying by -1 to return the absolute value of a number.
Example :
abs(-5) ---> 5
abs(5) ---> 5
try this:
num = int(input("Please enter a number:"))
if num <= 0:
num = abs(num)
Python has a lot of built-in functions that help do simple tasks like this.
The abs() function returns the absolute value of any float/int/etc. you put into it.
You can also do this all in one line if you wish, you would use the same abs() function. This time around it can be in a try-except block which will handle any bad input like "18asdfnsjkdf" for example.
try:
num = abs(int(input("Enter a number:")))
except ValueError:
pass
Your code works, add a print statement and be careful of indentation issues:
number = int(input('Please enter a number: '))
if number <= 0:
number = number * -1
print(number)
Output is:
Please enter a number: -5
5
Related
I'm trying to work out the average of numbers that the user will input. If the user inputs nothing (as in, no value at all) I want to then calculate the average of all numbers that have been input by the user upto that point. Summing those inputs and finding the average is working well, but I'm getting value errors when trying to break the loop when the user inputs nothing. For the if statement I've tried
if number == ''
First attempt that didn't work, also tried if number == int("")
if len(number) == 0
This only works for strings
if Value Error throws up same error
Full code below
sum = 0
while True :
number = int(input('Please enter the number: '))
sum += number
if number == '' :
break
print(sum//number)
Error I'm getting is
number = int(input('Please enter the number: '))
ValueError: invalid literal for int() with base 10:>
Any help much appreciated!
EDIT: Now getting closer thanks to the suggestions in that I can get past the problems of no value input but my calculation of average isn't working out.
Trying this code calculates fine but I'm adding the first input twice before I move to the next input
total = 0
amount = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
total = number + number
amount += 1
except:
break
total += number
print(total/amount)
Now I just want to figure out how I can start the addition from the second input instead of the first.
sum = 0
while True :
number = input('Please enter the number: '))
if number == '' :
break
sum += int(number)
print(sum//number)
try like this
the issue is using int() python try to convert input value to int. So, when its not integer value, python cant convert it. so it raise error. Also you can use Try catch with error and do the break.
You will always get input as a string, and if the input is not a int then you cant convert it to an int. Try:
sum = 0
while True :
number = input('Please enter the number: ')
if number == '' :
break
sum += int(number)
print(sum//number)
All of the answers dont work since the print statement referse to a string.
sum = 0
while True :
user_input = input('Please enter the number: ')
try:
number = int(user_input)
except:
break
sum += number
print(sum//number)
including a user_input will use the last int as devisor.
My answer also makes sure the script does not crash when a string is entered.
The user has to always input something (enter is a character too) for it to end or you will have to give him a time limit.
You can convert character into int after you see it isn't a character or
use try & except.
sum = 0
i = 0
while True :
try:
number = int(input('Please enter the number: '))
except ValueError:
break
i += 1
sum += number
try:
print(sum/number)
except NameError:
print("User didn't input any number")
If you try to convert a character into int it will show ValueError.
So if this Error occurs you can break from the loop.
Also, you are trying to get the average value.
So if a user inputs nothing you get NameError so you can print an Error message.
5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below.
largest = None
smallest = None
while True:
try:
num = input("Enter a number: ")
if num == "done" : break
print(num)
if num > largest:
largest=num
if num < smallest:
smallest=num
except:
print("Invalid input")
print("Maximum is", largest)
print("Minimum is", smallest)
desired output: my output:
Invalid input 2 ← Mismatch
Maximum is 10 4
Minimum is 2 5
maximum is 5(it prints the last input)
minimum is None
I'm a total beginner at programming and python so if the error is obvious pls break it down as much as you could..thank you so much.
The program will never reach print("Invalid input") since there is no error that could be thrown above. If you were to cast num to an integer with num = int(num) after you've checked if num == "done", then the program would catch invalid inputs like "bob"
input() returns a string, so you need to cast the input to integer with int() before comparing it as a number. Also remove your unnecessary print(num).
So change:
print(num)
to:
num = int(num)
The problem is that you are using strings, not numbers. 10 is a number, it is stored as numeric data and you can do things like compare size, add, subtract, etc. Specifically it is an integer, a number with no decimal places (computers store numbers in a lot of different ways). '10' is a string, a set of characters. Those characters happen to represent a number, but the computer doesn't know that. As far as it can tell it is just text.
What you can do to convert a string to an integer is simply num = int(num). If the number can be converted to an integer, it will be. If it can't, you will get an error. That is why the instructions tell you to use a try/catch block. It will catch this error.
Your question already explains what you want to do
If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message
The explanation of why is that you need int(num) after you check for done, to try converting a string to an integer, and catch exception that happens for non integer inputs
I suggest you remove the try except, type anything but a number and observe the behavior
I have an assignment as follows
Write a program that repeatedly asks the user to enter a number, either float or integer until a value -88 is entered. The program should then output the average of the numbers entered with two decimal places. Please note that -88 should not be counted as it is the value entered to terminate the loop
I have gotten the program to ask a number repeatedly and terminate the loop with -99 but I'm struggling to get it to accept integer numbers (1.1 etc) and calculate the average of the numbers entered.
the question is actually quite straightforward, i'm posting my solution. However, please show us your work as well so that we could help you better. Generally, fro beginners, you could use the Python built-in data types and functions to perform the task. And you should probably google more about list in python.
def ave_all_num():
conti = True
total = []
while conti:
n = input('Input value\n')
try:
n = float(n)
except:
raise ValueError('Enter values {} is not integer or float'.format(n))
if n == -88:
break
total.append(n)
return round(sum(total)/len(total),2)
rslt = ave_all_num()
Try the following python code. =)
flag = True
lst=[]
while(flag):
num = float(raw_input("Enter a number. "))
lst+=[num]
if(num==-88.0): flag = False
print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)
enter code hereThank you for the prompt replies. Apologies. This is the code i was working on:
`#Assignment2, Question 3
numbers=[]
while True:
num=int(input("Enter any number:"))
if num==float:
continue
if num==-88:
break
return print(" the average of the numbers entered are:",sum(numbers)/len(numbers)`
I need to make a program that the user will enter in any number and then try guess the sum of those digits.
How do i sum up the digits and then compare then to his guess?
I tried this:
userNum = raw_input("Please enter a number:\n")
userGuess = raw_input("The digits sum is:\n")
if sum(userNum, userGuess):
print"Your answer is True"
else:
print "Your answer is False"
and it didnt work
You have 2 problems here :
raw_input() doesn't return an integer, it returns a string. You can't add strings and get an int. You need to find a way to convert your strings to integers, THEN add them.
You are using sum() while using + whould be enough.
Try again, and come back with your results. Don't forget to include error messages and what you think happened.
Assuming you are new to Python and you've read the basics you would use control flow statements to compare the sum and the guess.
Not sure if this is 100% correct, feel free to edit, but it works. Coded it according to his(assuming) beginner level. This is assuming you've studied methods, while loops, raw_input, and control flow statements. Yes there are easier ways as mentioned in the comments but i doubt he's studied map Here's the code;
def sum_digits(n):
s = 0
while n:
s += n % 10
n /= 10
return s
sum_digits(mynumber)
mynumber = int(raw_input("Enter a number, "))
userguess = int(raw_input("Guess the digit sum: "))
if sum_digits(mynumber) == userguess:
print "Correct"
else:
print "Wrong"
Credit to this answer for the method.
Digit sum method in Python
the python code is :
def digit_sum(n):
string = str(n)
total = 0
for value in string:
total += int(value)
return total
and the code doesnot use the API:
def digit_sum1(n):
total=0
m=0
while n:
m=n%10
total+=m
n=(n-m)/10
return total
Firstly you neet to use something such as int(raw_input("Please enter a number:\n")) so the input returns an integer.
Rather than using sum, you can just use + to get the sum of two integers. This will work now that your input is an integer.
Basically I would use a generator function for this
It will iterate over the string you get via raw_input('...') and create a list of the single integers
This list can then be summed up using sum
The generator would look like this:
sum([ int(num) for num in str(raw_input('Please enter a number:\n')) ])
Generators create lists (hence the list-brackets) of the elements prior to the for statement, so you could also take the double using:
[ 2 * int(num) for num in str(raw_input('Please enter a number:\n')) ]
[ int(num) for num in str(123) ] would result in [1,2,3]
but,
[ 2 * int(num) for num in str(123) ] would result in [2,4,6]
Write a program that will prompt the user for two integers, each of which is greater
than 0. The program will display and count the number of divisors that the two integers have in
common.
Additional requirements:
if the integer is less than 1 tell the user there is a problem and then prompt them for the
integer again.
This is what I have written so far, but I am stuck here I dont know how to incorporate both numbers. Essentially I do not know where to go from here or if 'here' is even correct???
Please help...[This is my first time with python]
integer1 = input("Enter an integer: ")
integer2 = input("Enter an integer: ")
print integer1, ": " ,
i = 1
while i <= integer1 and integer2 :
if integer1 or integer2 < 1 :
print input("Enter an integer: ")
if integer1%i == 0 and integer2%i == 0 :
print i ,
i = i + 1
Try to do one step after the other. And try to break down your task into simple steps. In your example it could be something like:
Get first number
Get second number
Calculate
This you can break down futher
Get first number:
Get Number from User
Loop while Number is not ok
...
This way you can see that the validation should not be inside the while loop.
Another tip: test each step separately. This way you will find that if integer1 or integer2 < 1 or while i <= integer1 and integer2 will not work the way you think they do.
This is not how logical operators work in Python or programming in general.
while i <= integer1 and integer2 :
In Python integer2 is a separate logical statement that is always true.
Try instead:
while i <= integer1 and i <= integer2
You'll want to move the code that
validates your input outside of the
loop.
Your print i doesn't need a
comma.
The syntax in your flow
control needs a bit of work, for
example if integer1 or integer2 <
1: should be if ((integer1 < 1) or
(integer2 < 1)):.
First we should do a simple way to get both integers; noting there could be multiple errors. (Even better would be raw_input and checking the number resolves to an int).
integer1 = -1
integer2 = -1
while(integer1 < 1):
integer1 = input("Enter integer 1: ")
while(integer2 < 1):
integer2 = input("Enter integer 2: ")
factor_list1 = [] # store factor list of first number
double_factor_count = 0
# generate the factor list of the first number
for i in range(1, integer1+1): # range(1,5+1) is the list [1,2,3,4,5]
if integer1 % i == 0:
factor_list1.append(i)
for j in range(1, integer2+1):
if integer2 % j == 0 and j in factor_list1:
print j,
double_factor_count += 1
print "\n double count:", double_factor_count
Possibly you want to change it to range(2, integer1) if you want to skip 1 and the integer typed in as numbers.
Note your original code wasn't indented (so didn't appear as code in the forums, and that and and or combine expressions (e.g., things that are True or False). So you meant if integer1 < 1 or integer2 < 1:.
Your code is actually very close, but you have a few problems:
You're not validating integer1 and integer2 correctly (though I suspect you know that, since you're just printing the replacement value).
Your loop test is broken. What you've written means "i is less than integer1, and also integer2 isn't zero".
You can also improve your code in a couple of ways:
Ensuring that your input is not only >= 1, but also an integer.
Using a for loop instead of a while loop, using Python's excellent iterables support.
Here's how to make sure that what the user typed was an integer:
integer1 = 0
while not integer1:
try:
# raw_input() ensures the user can't type arbitrary code
# int() throws a ValueError if what they typed wasn't an integer
integer1 = int(raw_input("Enter the first integer: "))
if integer1 < 1:
print "You must enter an integer greater than 0!"
integer1 = 0 # so that our while statement loops again
except ValueError:
# the user typed something other than an integer
print "You must enter an integer!"
The while, try, and if statements here ensure that the user will be forced to enter a valid integer before your code continues. Here's an example of what the user sees:
Enter the first integer: 6.6
You must enter an integer!
Enter the first integer: -5
You must enter an integer greater than 0!
Enter the first integer: sys.exit(0)
You must enter an integer!
Enter the first integer: 12
Enter the second integer:
And this is how I'd recommend setting up your loop:
# min() returns the smallest of its arguments
# xrange() iterates over a sequence of integers (here, starting with 1 and
# stopping at min(integer1, integer2))
for i in xrange(1, min(integer1, integer2) + 1):
# magic goes here!
Documentation links:
int()
min()
raw_input() and input()
xrange()
Your problem is with your if statements.
Rather than saying: while i <= integer1 and integer2, you need to say while i <= integer1 and i <= integer2
The same applies for your other if statement. if integer1 or integer2 < 1 : should be if integer1 < 1 or integer2 < 1 :