you can see my code in below. I got error that in that line "print(str(values))"
it says
Unindent doesn't match any outer indentation level.
What is wrong with it?
values = ''
def reverse(numbers):
print('please enter a 3 digit number :')
number = input()
if 100 > number:
print('the number is not 3 digit')
values[0] == number[2]
values[1] == number[1]
values[2] == number[0]
print(str(values))
print(reverse(135))
Check the print line, you've extra space before print command. After that a better way to reverse strings or numbers is using the list comprehention (you should convert your number to string first), you can make something like this:
my_value = '123' # or str(my_value)[::-1]
print my_value[::-1] # This result is 321
Note: Your if block haven't any effect, because you print the message but in the next line you proceed with operation. In this case I think that your operation should be in a else block.
This is a program to reverse a 3 digit number.
l=list(input("please enter a 3 digit no.="))
print(l[2],l[1],l[0])
Related
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')
number = 0
number_list = []
while number != -1:
number = int(input('Enter a number'))
number_list.append(number)
else:
print(sum(number_list)/ len(number_list))
EDIT: Have found a simpler way to get the average of the list but if for example I enter '2' '3' '4' my program calculates the average to be 2 not 3. Unsure of where it's going wrong! Sorry for the confusion
Trying out your code, I did a bit of simplification and also utilized an if statement to break out of the while loop in order to give a timely average. Following is the snippet of code for your evaluation.
number_list = []
def average(mylist):
return sum(mylist)/len(mylist)
while True:
number = int(input('Enter a number: '))
if number == -1:
break
number_list.append(number)
print(average(number_list));
Some points to note.
Instead of associating the else statement with the while loop, I revised the while loop utilizing the Boolean constant "True" and then tested for the value of "-1" in order to break out of the loop.
In the average function, I renamed the list variable to "mylist" so as to not confuse anyone who might analyze the code as list is a word that has significance in Python.
Finally, the return of the average was added to the end of the function. If a return statement is not included in a function, a value of "None" will be returned by a function, which is most likely why you received the error.
Following was a test run from the terminal.
#Dev:~/Python_Programs/Average$ python3 Average.py
Enter a number: 10
Enter a number: 22
Enter a number: 40
Enter a number: -1
24.0
Give that a try and see if it meets the spirit of your project.
converts the resulting list to Type: None
No, it doesn't. You get a ValueError with int() when it cannot parse what is passed.
You can try-except that. And you can just use while True.
Also, your average function doesn't output anything, but if it did, you need to call it with a parameter, not only print the function object...
ex.
from statistics import fmean
def average(data):
return fmean(data)
number_list = []
while True:
x = input('Enter a number')
try:
val = int(x)
if val == -1:
break
number_list.append(val)
except:
break
print(average(number_list))
edit
my program calculates the average to be 2 not 3
Your calculation includes the -1 appended to the list , so you are running 8 / 4 == 2
You don't need to save all the numbers themselves, just save the sum and count.
You should check if the input is a number before trying to convert it to int
total_sum = 0
count = 0
while True:
number = input("Enter a number: ")
if number == '-1':
break
elif not number.isnumeric() and not (number[0] == "-" and number[1:].isnumeric()):
print("Please enter numbers only")
continue
total_sum += int(number)
count += 1
print(total_sum / count)
I would like to write a program that uses a while loop to repeatedly prompt the user for numbers and adds the numbers to a running total. When a blank line is entered, the program should print the average of all the numbers entered. I also would like to use a break statement to exit the while loop.
My Incorrect Work:
y = "\n"
total = 0
k = 0
while True:
x = input("Enter your number here: ")
x = float(x)
total = total + float(x)
k = k + 1
if type(x) != int:
print(total/k)
break
Be aware that the function input() will always outputs a string, so type(input()) != int will always be true.
Try using try-except function, when there is ValueError (example unable to convert blank/letters to float), the exception will be raised and break the loop:
total = 0
k = 0
while True:
x = input("Enter your number here: ")
try:
total += float(x)
k += 1
except ValueError:
if k > 0: #to avoid division by zero
print("Average: ", total/k)
break
Output:
Enter your number here: 3
Enter your number here: 4
Enter your number here: 5
Enter your number here:
Average: 4.0
Bearing in mind the comments already made, here is one such way to perform your task and finishing up when a blank entry is encountered.
total = 0.0
k = 0.0
while True:
x = input("Enter your number here: ")
if (x == " "): # Check for a blank line entry here before attempting to convert to float
print("Average is:", (total/k))
break
x = float(x)
total = total + float(x)
k = k + 1
As noted in the comments, one should check for the blank line entry prior to attempting to convert the entry.
You are immediately casting the value of x that is inputted to a float. So,
if type(x) != int
always is true, meaning the loop breaks after one iteration every time.
Others have already solved your problem in different ways, but I think that explaining our thinking might also be useful.
Currently, your program is not checking correclty the exit condition (empty line is entered instead of a number). When a new line is entered, your program should do one of the two possible scenarios:
when an empty line is entered: print result & exit (break)
else (assume a number is entered): add number to total
No third option is specified, so for now, let's assume that every line will either be an empty line or a number. Will expand it later.
After you decided what to do, the actions should just be easily wrapped in a while True: block - so it should be:
initialize_variables_total_and_count
while True:
read_line
decide_what_to_do:
# in case line was a number
convert_line_to_float
add_float_to_total
increment_count
other_case:
# empty line was entered
calculate_and_print
break
With only two options, you only need to decide once what to do. You can swap around the cases by deciding which condition to check for (and that also results in the other being the "default" behavior for other cases).
It's simpler to check for the line being empty with if line_entered == "":. In this case, any non-empty line is treated like a number, and if it were not one, the float() function will error out and your program crashes.
Checking if a string (the entered line) can be converted to a float is a bit harder. There is just no built-in for that in python, but there is a trick: you can try to convert it to a float, and if that works, it was convertible, and if that errors, it was not. There are other ways too, but this is the simplest - see this question on the topic.
In this case, every number will be added to the total, and every non-number (including the empty line, but also random strings like "asdf") will cause the program to calculate the total and stop.
You can avoid putting both cases into an if-else block by using break or continue. (technicly, you never need to use break or continue, all programs can be written without them. In this case, you could have a boolean variable, named run for example, write while run: and instead of break, do run = False). You can use the fact that both break and continue end the loop early to avoid placing the second case inside an else-block and still have the same behavior (as break and continue already causes skipping the rest of the loop body).
So an example implementation: (testing for == "", not using unstructured control flow)
total = 0
count = 0
run = True
while run:
line = input("Enter your number here: ")
if line == "":
print(total / count)
run = False
else:
total += float(line)
count += 1
I also renamed k to count, x to line and used in-place addition operators.
Another implementation, with break, testing for float with try/except (and re-using that for the entire control flow):
total = 0
count = 0
while True:
line = input("Enter your number here: ")
try:
# order matters here. If the first line errors out, the second won't happen so the count will only be inremented if it was indeed a float
total += float(line)
count += 1
except:
print(f"Average is: {total / count}")
break
Here I removed the run variable, and used a format string to print a bit fancier.
And an example using both continue and break:
total = 0
count = 0
while True:
line = input("Enter your number here: ")
if line != "":
total += float(line)
count += 1
continue
print(f"Average is: {total / count}")
break
You can fancy it a bit with adding more error handling - use three cases:
user entered empty line: print & exit
user entered a number: add to total
user entered something else: ignore line, but tell user what to do
I only provide one example implementation for this, but as you can see, it can be implemented in many ways.
total = 0
count = 0
# good practice to tell the user what to do
print("Average calcuator. Enter numbers one per line to calulate average of, enter empty line to print result & exit!")
while True:
line = input("Enter your number here: ")
if line == "":
print(f"Average is: {total / count}")
break
else:
try:
total += float(line)
count += 1
except ValueError:
print("You should enter a number or an empty line to calculate & exit!")
I'm new in coding or programming so I hope for respect.
How can I create a program that continually accepts input from the user. The input shall be in this format operatornumber like -3
Like
num = 0
while((a := input("Enter operatornumber like -9;")) != "-0"):
if (len(a) >= 2) and (a[0] in "/*-+"):
num = eval(f"{num}{a}")
else:
print("Invalid input, try again.")
print(num)
But how can I make the first input of the user to only use the add (+) or subtract(-) operators but in the next input they can now use the other operators.
Like
Enter operatornumber like -9; +9
Enter operatornumber like -9; -8
Enter operatornumber like -9; -0
1
And how can I combine all the input like
+9-9 is 1?
In the input statement, you're closing the "Enter operator and number like" msg. This is creating more problems after that line, where all green parts are considered as string now. Also, in while statement, "w" should be small letter, python is case sensitive. Try doing this:
Number = input("Enter operator and number like '-9' ")
Operator = ("+","-","/")
while Number == (Operator + Number):
if Number == "-0":
Total = 0
Total += Number
print(f"the result of {num} is {total} ")
You can use double quotes for the text and single quotes for the number, so they don't close each other.
You can get input forever using following code:
while True:
Number = input("Enter operator and number like '-9'")
# Place your next code here.
Here is another answer. We have to take input from user with operator as well, so len(<user_input<) should be >=2. Now, we'll take another variable h in which we'll traverse the string from index 1 to end, which means the operator gets removed and we'll convert it into int. Then we'll put if condition in which we'll check the user_input[0] is +,-,*,/ and then acc to that, we'll update the result. We'll ask the user whether he wants more operations or no, if y, then keep asking, else, break the while loop. Here's my code:
result=0
while True:
a=input("Enter operator and number= ")
if len(a)>=2 and a[0] in ["+","-","*","/"]:
h=int(a[1::])
if a[0]=="+":
result+=h
elif a[0]=="-":
result-=h
elif a[0]=="*":
result*=h
elif a[0]=="/":
result/=h
else:
print("choose only from +-/*")
else:
print("invalid input")
ch=input("Enter more?")
if ch=='n':
break
print(f"The result is {result}")
Check for indentation errors because I've copied and pasted it so it may have indentation errors
I'm currently attempting to create a Bulls and Cows game for a school mock assessment and am having problems with this line of code
def BullsAndCows():
Guess= input("Please enter a 4 digit number, remember no duplicates!")
Guess = str(Guess)
while len(Guess) != 4:
Guess = input("IT has to be FOUR digits!")
Guess = str(Guess)
while Guess[0] == Guess[1] or Guess[0] == Guess[2] or Guess[0] == Guess[3] or Guess[1] == Guess[2] or Guess[1] == Guess[3] or Guess[2] == Guess[3]:
Guess = input("You can't use duplicates silly! Try another number!")
Guess = str(Guess)`
The problem is if i input a 4 digit number with a duplicate i can no longer input a non 4 digit number without it outputting this error
Traceback (most recent call last):
File "python", line 64, in
File "python", line 57, in BullsAndCows
IndexError: string index out of range
Line 57 is the while Guess[0] ==...
Line 64 is just BullsandCows() which is used to call the function.
Anyone know the problem?
Your error is generated when a user enters a string with a length lesser than 4. In which case, guess[3] will be out of bounds.
If you want to check whether your input adheres to come condition, I would recommend a single while terminated by a condition:
import re
guess = ''
while not (guess.isdigit() \
and len(guess) == 4 \
and not re.search(r'(\d).*\1', guess)):
guess = input(...)
As long as the while condition remains False, the loop continues to run.
guess.isdigit() is a string function to check whether a string is numeric or not. For example:
In [889]: '1234'.isdigit()
Out[889]: True
In [890]: '1234abc'.isdigit()
Out[890]: False
len(guess) == 4 will check whether the string is of length 4, if the first condition is True.
Additionally, to prevent duplicates, I would highly recommend using regular expressions. If the first and second condition are True, the re.search function will apply a regex pattern (explained below) to search for duplicates in the string. If there is a duplicate, a match is returned which is evaluated to True. Otherwise, None is returned which is False.
As long as any one of these 3 conditions are False, the entire expression is False (due to how or boolean logic works) and the loop continues to execute.
Regex Details
(\d) # digit (capture group)
.* # match 0 or more chars
\1 # reference 1st capture group
The reason for your error is that once you've passed the 4-digit test once, you never do it anymore even if the input changes. So if you input 1111 first, it passes the first test (while len(Guess) != 4) but not the second test. If you then input 123, you get an error because the input only has 3 digits, and Guess[3] raises an IndexError
You should refactor your code to include all tests on the input in the same place, and only have one while loop. Somehting like this :
def BullsAndCows():
Guess= input("Please enter a 4 digit number, remember no duplicates!")
Guess = str(Guess)
(correct, message) = check_input(Guess)
while not correct:
Guess = input(message)
(correst, message) = check_input(Guess)
def check_input(guess):
if not guess.isdigit():
return (False, "Input a number")
if len(guess) != 4:
return (False, "The number should have 4 digits")
if guess[0] == guess[1] or ...
return (False, "No duplicates")
#other tests if necessary
return (True, "ok")
Edit : as others have pointed out, guess[0] == guess[1] or ... is cumbersome and error-prone. Better to replace it with something more generic and that works equally well if you have 4, 5, ... n digits in the input. AK47's solution (len(set(guess)) != len(guess)) works well for this. Since the syntax is a bit obscure for first-time users, here's how it works:
set(guess) turns the input into a set of its characters. A set can only have distinct elements, so set('123') = set('1233212') = {'1', '2', '3'}.
if len(set(guess)) == len(guess), this means that all the characters in guess are also in the set; therefore all characters are distinct.
You can simplify your method alot by removing the while loops and just using 1 which will keep the program running until the method breaks
You can use the len() function to check to see if the value entered matches 4 digits
You can use the set() constructor to build a set out of your input which will remove duplicates, and then compare the len() of the set to the len() of the original input
def BullsAndCows():
while True:
guess = str(input("Please enter a 4 digit number, remember no duplicates:"))
if len(guess) != 4:
print("It has to be FOUR digits")
continue
if len(set(guess)) != len(guess):
print("You cant enter duplicates silly! Try another number")
continue
print("No duplicates in number: {}".format(guess))
break
BullsAndCows()
>> Please enter a 4 digit number, remember no duplicates:
> 123
>> It has to be FOUR digits
>> Please enter a 4 digit number, remember no duplicates:
> 1111
>> You cant enter duplicates silly! Try another number
>> Please enter a 4 digit number, remember no duplicates:
> 1234
>> No duplicates in number: 1234