Can't get value to be assigned to variable - python

import random
print('-\n')
begin=int(raw_input('-\n')
end=int(raw_input('-\n')
rep=int(raw_input('-\n')
def dop():
print random.randinterga
ivfhoierh
while count < rep:
print do
count = count + 1
print('Thanks for using this program!\n')
raw_input('press enter to continue')
Okay, so I really have no idea what iv've done wrong but I keep getting a syntax error and IDLE highlights 'end'.
Edit: C

This is how I would do this:
import random
print 'I will print out random integers from a range you specify.'
begin = int(raw_input('Please enter the starting range: '))
end = int(raw_input('Please enter the end range: '))
rep = int(raw_input('Please enter the repeat value: '))
def get_random():
return random.randint(begin, end)
for _ in range(rep):
print get_random()
Attention to detail is so important.
Problems addressed:
Mismatched parentheses
Inconsistent assignments
Inconsistent use of print
Personal preference over returning, then printing
Renamed function do() for clarity
raw_input() doesn't need \n new lines
randint() gets upset generating ValueError: non-integer arg 1 for randrange() on float values; cast the raw_input() accordingly
(Minor) Corrected spelling in output
Replaced while loop with for loop, removing unneeded variable count and assignments
Hope this helps!

I guess you are using Python 2, judging by raw_input.
Correct your code to:
import random
print 'Hi, I will print out random intergers from a range you specify.\n'
#No need for parenthesis
begin=float(raw_input('Please enter the starting range. \n'))
end=float(raw_input('Please enter the end range. \n'))
rep=float(raw_input('Please enter how many times you cant to repeat the function. \n'))
# ERROR you forgot an extra parenthesis on the end of each of the last 3 lines.
def do():
print random.randint(begin, end)
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
print 'Thanks for using this program!\n' #No need for parenthesis
raw_input('press enter to continue')
Also this:
count = 0
while count < rep:
do() # <- Parenthesis, and no need to print.
count = count + 1
Can be replaced by this:
for count in range(rep):
do()

Related

Keep asking for numbers and find the average when user enters -1

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)

A program that uses while loop to find average of numbers inputted, and uses a break statement to exit the loop

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!")

Running into issues with looping the calculation of # of digits in a number

My assignment requires me to take in an input, determine how many digits are in said input, then spit it back out. we are not allowed to use string conversion in order to determine the length of the input. I've managed to get that to work properly. My issue is that I'm supposed to have it repeat in a loop until a sentinel is reached. Here's my code so far.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = 1
final = 0
num = int(input("Enter a number: "))
while num != 0:
num = num //10
count += 1
print("There are", count, "digits in", num)
I'm also seeming to have trouble with having my input integer print properly, but it might just be my ignorance there. I've cut out what my attempts at looping it were, as they all seemed to just break the code even more. Any help is welcome, even criticism! Thank you in advance!
Firstly, that is a strange way to get the digits in the number. There's no need to modify the actual number. Just cast the int back to a string and get the length (don't just keep the original string, it could have spaces or something in it which would throw off the count). That is the number of digits.
Secondly, you can do all the work in the loop. There's no need for setup variables, incrementing, a second loop, or anything like that. The key insight is the loop should run forever until you break out of it, so you can just use "while True:" for the loop, and break if the user inputs "0".
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
def find_digits(num):
count = 0
while num != 0:
num = num //10
count += 1
return count
count += 1
# loop forever
while True:
# hang onto the original input
text_input = input("Enter a number: ")
# cast to int - this will throw an exception if the input isn't int-able
# you may want to catch that
num = int(text_input)
# the number of digits is the length of the int as a string
num_digits = find_digits(num)
if num == 0:
print("Goodbye.")
# "break" manually ends the loop
break
# if we got to this point, they didn't input 0 and the input was a number, so
# print our response
print(f"There are {num_digits} digits in {num}.")
The problem with printing the input integer correctly is, that you first save it in the num variable and then constantly change it in your while loop. So the original input is lost of course and in the end it always prints the 0, that ends up in num after the while loop finishes.
You can easily fix it, by saving the input value to another variable, that you don't touch in the loop.
print("This program determines the number of digits in a number.")
print("Enter a number, or 0 to quit.")
count = 0
num = int(input("Enter a number: "))
numcopy = num
while numcopy != 0:
numcopy = numcopy // 10
count += 1
print("There are", count, "digits in", num)
Counting is better done with Python builtin functions.
len(str(num))
will give you number of digits in your number.

How to print a list of numbers and their average?

For my assignment, I have to create a program that lets the user enter several numbers. I also want to create a list with all the numbers and their average.
But how do I create a code for the list of numbers?
I should exit with a number such as 0 or -999.
One line has invalid syntax.
print (number_list[i], end = " ")
Here is my code.
number_list = []
sum = 0.0
user_number = eval(input("Please enter a number (-999 quits): "))
# Loop until the user is ready to quit
while (user_number != -999):
number_list.append(user_number)
sum = sum + user_number
user_number = eval(input("Please enter a number (-999 quits): "))
# Make sure the user entered something
if (len(number_list) != 0):
# Compute average
average = sum / len(number_list)
# Do output
print ("Using the numbers:")
for i in range(len(number_list)):
# Note the end = " " at the end will keep the output on
# the same line
print (number_list[i], end = " ")
# Note the \n at the start of this line is needed because
# the previous print statement ended with a comma. This
# \n will move the cursor to the next line
print ("\nThe average is:", average)
else:
print ("No values were entered")
Because of Python's indentation rules, any compound statement needs to have at least one statement indented after it.
Let's focus on this section of your code:
for i in range(len(number_list)):
print (number_list[i], end = " ")
print ("\nThe average is:", average)
else:
print ("No values were entered")
A for loop is a compound statement as it needs stuff indented after it. You need to indent them accordingly. Something like:
for i in range(len(eggs)):
print(eggs[i])
The pythonic way to loop over stuff is just to use the value instead of getting the index and then finding it. Python's for loop is more like a foreach loop than an actual for loop. A remake would look like:
for spam in eggs:
print(spam)
Also, you have a check for if there aren't any numbers. Use a normal if statement for that, not one in the loop. The else behind a loop will run when the main part (while or for) finishes without a break.
This:
for spam in eggs:
print(spam)
else:
print("Nothing")
Is not the same as this:
if eggs:
for spam in eggs:
print(spam)
else:
print("Nothing")
Here's the fixed section :D
# If statement to check if list is truthy (nonempty)
if number_list:
# Note the for loop's target 'number'
for number in number_list:
# Note indentation.
print(number, end=" ")
print("\nThe average is:", average)
else:
print("No values were entered")
EDIT: You also have indentation errors after the while loop above this section. I'll leave that to you to fix :)

reverse the 3 digit number in python

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])

Categories