Basic decrement loop - PYTHON - python

Newbie to python and hit a snag in my latest program. Simply put, I'm trying to code up a decrement loop for a user input variable if possible. Essentially I have a global constant set to value e.g. 13, each time the program loops it prompts the user to input a value then that user value is shaved off 13 until it reaches 0. Problem is that it does shave it off but when it reiterates it resets the value to 13 and only removes the current iterate value entered. So if you enter 2 each iteration it just takes it down to 11... But I'm aiming for a result using 2 as an example again, 11, 8, 5, etc etc or using 3 as an example 10, 7, 4.... Any help guys will be much appreciated, cheers :)
a = 13
def main():
runLoop()
def runLoop():
while other_input_var > 0: # guys this is my main score accumulator
# variable and works fine just the one below
b=int(input('Please enter a number to remove from 13: '))
if b != 0:
shave(a, b)
def shave(a, b):
a -= b
print 'score is %d ' % a
if a == 0:
print "Win"
main()

In my humble opinion with such a small snippet the addtional functions end up over complicating things. However good to see you are getting the concept. I have not tested this but this should do the same thing you are looking for. Notice line 5 I insure that the number entered does not exceed the current value of a. This should help if they/you accidentally type something higher. Next step would be to put error handling if you haven't tried that yet see Python Error Handling . hope this helps!
def main():
a = 13
while a:
b = int(input("Please enter a number to remove from " + str(a) + " : "))
if b > 0 and b <= a:
a -= b
print "Score is ", str(a)
print "Win"
main()

Not an answer to your question, but rather a demonstration of string formatting. This is the old style, using the % "string interpolation operator".
a = 100
while a:
shave = int(raw_input("Input a number to subtract from %i:" % a))
if ( shave > 0 ) and ( shave <= a ):
a -= shave
else:
print ("Number needs to be positive and less than %i." % a)
A session with this program:
Input a number to subtract from 100:50
Input a number to subtract from 50:100
Number needs to be positive and less than 50.
Input a number to subtract from 50:30
Input a number to subtract from 20:20
The %i in the original string is a placeholder for an integer (i for integer) which is filled in later by the % operator on the string.
There's also %f for floating-point numbers, %s for strings, and so on. You can do nifty things like specify how many decimal points numbers should print with - %.3f for three decimal places - and so on.
Another example:
>>> "My name is %s and I'm %.2f metres tall." % ('Li-aung',1.83211)
"My name is Li-aung and I'm 1.83 metres tall."
This is a lot easier to read than:
"My name is " + name + " and I'm " + str(round(age,2)) + " metres tall"
Read up more about string formatting the old way or the new way.

Related

Number guessing game will not print the right phrase

I am extremely new to python and this is one of the first things I have tried. There are 3 criteria that I want this game to meet. First is to use the number 0-10 and guess the number 3 which it does correctly. Next is 0-25 when 11 is chosen. This also works correctly.
However this last part has been giving me trouble. When picking from 0-50, it should guess 1 which it does. It should also print the "I'm out of guesses" line when another input is placed as it cannot go higher than one now. What am I doing wrong here?
import random
import math
smaller = int(input("Enter the smaller number: "))
larger = int(input("Enter the larger number: "))
maxTry = math.log(larger - smaller)
count = 0
guess = int((smaller+larger)/2)
while count != maxTry:
count += 1
guess = int((smaller+larger)/2)
print("Your number is ", guess)
help = input("Enter =, <, or >: ")
if help == ">":
smaller = guess +1
elif help == "<":
larger = guess -1
elif help == "=":
print("Hooray, I've got it in", count, "tries")
break
elif count == maxTry:
print("I'm out of guesses, and you cheated")
break
Your maxTry is a log so it is not an integer, therefore it can never be equal to count.
You can either use an int for maxTry (cast it to int maxTry = int(math.log(larger - smaller))) or compute it with something different than log that will return an int.
Alternatively, your condition could be count > maxTry instead of equal. It would actually be a bit better conceptually.
Note: you should not use capital letters in variable names in python but all lowercase with _ max_try. It is only a convention though so won't affect your program directly. You can find more info on conventions in the PEP8 documentation

Infinite loop in python from user input

I am writing Python code counting up to the number the user provides, but I get into an infinite loop when running the code. Please note I tried commenting out lines 3 and 4 and replaced "userChoice" with a number, let's say for example 5, and it works fine.
import time
print "So what number do you want me to count up to?"
userChoice = raw_input("> ")
i = 0
numbers = []
while i < userChoice:
print "At the top i is %d" % i
numbers.append(i)
i = i + 1
print "Numbers now: ", numbers
print "At the bottom i is %d" % i
time.sleep(1)
print "The numbers: "
for num in numbers:
print num
time.sleep(1)
raw_input returns a string, not int. You can fix the issue by converting user response to int:
userChoice = int(raw_input("> "))
In Python 2.x objects of different types are compared by the type name so that explains the original behavior since 'int' < 'string':
CPython implementation detail: Objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address.
You are comparing a number with a string in:
while i < userChoice:
The string will always be greater than the number. At least in Python 2 where these are comparable.
You need to turn userChoice into a number:
userChoice = int(raw_input("> "))

Invalid Syntax: adding 10 to input

I've been doing some python(using spyder) and being completely new to all of this, I'm pretty confused. My friend typed this code:
elif x== '3' :
number = input('Enter an integer \n')
try:
the sum = int(float(number)+(float(10))
print(number + 'plus 10 equals'+ the sum)
And it works for her, but not me, when I type the exact same thing, and same indents and all. There is a cross on the side(code analysis) that appears on the line that starts with 'the sum'. Apparently, there's invalid syntax. Thanks.
Let's look at this line by line..
elif x== '3' :
Should be:
if x == '3':
You should start if statements with if instead of elif. Also, make sure x has a value earlier in your code.
If you're brand new, I would wait just a little longer to add try: statements. But I'll include it in the final answer.
the sum = int(float(number)+(float(10))
Should be:
the_sum = float(number) + 10
Use a float if you expect number to have a decimal. Based on the info you provided, there isn't a need to convert the float back to an int which is what you're doing when you call int(float(...
Note that a space in a variable name is not valid syntax. Adding an underscore makes the_sum valid.
print(number + 'plus 10 equals'+ the sum)
Python2 and Python3 have different options for formatting output. More info here. I'll use Python2, so your code should be:
print ('%f plus 10 equals %f' % (number, the_sum))
%f means format a variable as a float. The first %f will be replaced with number and the second with the_sum.
All together you have:
if x == '3':
number = input('Enter an integer \n')
try:
the_sum = float(number) + 10
print ('%f plus 10 equals %f' % (number, the_sum))
except:
pass
Bonus: Does your script break when you enter a character? How could you use the try: statement to improve?

Python list index is out of range error

I've been tasked with making a Quiz app for a school project. It's meant to ask the user how many questions they want, and they then enter all of the Q&A's. Once finished, someone will then take the test.
The problem is, I'm getting an IndexError from the results function. This function is supposed to compare the test answers with the user's answers and print out a score.
def results(testAnswers, userAnswers):
score = 0
for i in range(0, len(answers)):
if testAnswers[i].lower().strip() == userAnswers[i].lower().strip():
score += 1
print("\nResults: You got " + str(score) + " out of " + str(len(answers)) + "!")
Does anyone know how I can fix this problem?
Your problem is here:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
if user_answers[n] != answer_list[n]:
n += 1
Lets say times is 10, and n is 9, it executes, and n+=1 makes it 10. Most likely, you have 10 elements in the array (note 10 is an example), and now user_answers[10 raises an exception, as the valid varles are 0..9
To fix this issue, use elif:
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
elif user_answers[n] != answer_list[n]:
n += 1
Alternate approach is to get rid of the else clause altogether,
while n < times:
if user_answers[n] == answer_list[n]:
score += 1
n += 1
Note that there are quite a few places you could optimize the code, but I am just going to leave the answer here, and let you figure other things out yourself.
Perhaps copying your code into this site went wrong, but regardless the code is not correctly formatted here which makes it very difficult to read.
regardless, its clear that you are indexing into a list to a point that doesn't exist. to help track down this error, add this line after you start your while loop:
print 'n %s, times %s, user_answers %s, answer_list %s' % (n, times, user_answers, answer_list)
then run the program and paste the output of the program into your question (but first please correct the indenting)
Due to an unknown reason, the testAnswers and userAnswers weren't in equal length. The lesson here is to always make sure they are the same length.
A simple if-statment can prevent the entire error.
if len(answers) != len(userAnswers):
return

How to compare inputted numbers without storing them in list

Note: This is not my homework. Python is not taught in my college so i am doing it my myself from MITOCW.
So far i have covered while loop, input & print
Q) Write a program that asks the to input 10 integers, and then prints the largest odd number that was entered. If no odd number was entered it should print a message to the effect
How can i compare those 10 number without storing them in some list or something else? Coz i haven't covered that as if yet.
print "Enter 10 numbers: "
countingnumber=10
while countingnumber<=10:
number=raw_input():
if number % 2 == 0:
print "This is odd"
countingnumber=countingnumber+1
else:
print "This is even. Enter the odd number again"
i think the program will look something like this. But this has some unknown error & How can i compare all the numbers to get the largest odd number without storing those 10 numbers in the list.
print "Enter 10 numbers: "
countingNumber = 1
maxNumber = 0
while countingNumber<=10:
number=int(raw_input())
if (number % 2 == 0):
countingNumber = countingNumber+1
if (maxNumber < number):
maxNumber = number
else:
print "This is even. Enter the odd number again"
print "The max odd number is:", maxNumber
you can just define a maxnum variable and save the max in it! also you must use int(raw_input()) instead raw_input()
print "Enter 10 numbers: "
maxnum=0
for i in range(10):
number=int(raw_input())
if number%2 == 0:
print "This is odd"
if number>maxnum:
maxnum=number
else:
print "This is even. Enter the odd number again"
print "max odd is :{0}".format(maxnum)
DEMO:
Enter 10 numbers:
2
This is odd
4
This is odd
6
This is odd
8
This is odd
12
This is odd
14
This is odd
16
This is odd
100
This is odd
2
This is odd
4
This is odd
max odd is :100
Whenever I do input, I like to make sure I don't leave room for human error giving me bugs.
Because I put in extra checks I break code into a lot of separate function. This also gives code the quality of being non-coupled. ie) You can reuse it in other programs!!
def input_number():
while true:
input = raw_input("Enter Value: ")
if not input.isdigit():
print("Please enter numbers only!")
else:
return int(input)
Designing the input function in this fashion gives the code no opportunity to crash. We can now use it in a function to get odd numbers!
def input_odd_number():
while true:
input = input_number()
if input % 2 == 0:
print("Please enter odd numbers only!")
else:
return input
Now we can finally move onto the main code. We know we need ten numbers so lets make a for loop. We also now we need to hold onto the largest odd number, so lets make a variable to hold that value
def largest_odd(count = 10): // its always nice to make variables dynamic. The default is 10, but you can change it when calling!
max_odd = input_odd_number() // get the first odd number
for i in range(count - 1): // we already found the first one, so we need 1 less
new_odd = input_odd_number()
if new_odd > max_odd:
max_odd = new_odd
print("The largest odd value in '{}' inputs was: {}".format(count, max_odd)
In your solution are multiple flaws.
A syntax error: The colon in number=raw_input():.
raw_input returns a string and you have to cast it to an int.
Your while loop just runs one time, because you start with 10 and compare 10 <= 10. On the next iteration it will be 11 <= 10 and finishes.
Also you have mixed odd an even. even_number % 2 gives 0 and odd_number % 2 gives 1.
To get the biggest value you only need a additional variable to store it (See biggest_number in my solution). Just test if this variable is smaller then the entered.
You ask again if the number is odd, but you should take every number and test only against odd numbers.
A working solution is:
print "Enter 10 numbers"
count = 0
max_numbers = 10
biggest_number = None
while count < max_numbers:
number=int(raw_input("Enter number {0}/{1}: ".format(count + 1, max_numbers)))
if number % 2 == 1:
if biggest_number is None or number > biggest_number:
biggest_number = number
count += 1
if biggest_number is None:
print "You don't entered a odd number"
else:
print "The biggest odd number is {0}".format(biggest_number)
If you wonder what the format is doing after the string take a look in the docs. In short: It replaces {0} with the first statement in format, {1} with the second and so on.
here is the correct code for that:
print "Enter 10 numbers: "
countingnumber=1
MAX=-1
while countingnumber<=10:
number=int(raw_input())
if number%2==1:
if number>MAX:
MAX=number
if MAX==-1:
print "There Weren't Any Odd Numbers"
else:
print MAX
here are some notes about your errors:
1- you should cast the raw input into integer using int() function and the column after calling a function is not needed and therefor a syntax error
2- your while loop only iterates once because you initial counting number is 10 and after one iteration it would be bigger than 10 and the while body will be skipped.
3-an even number is a number that has no reminder when divided by 2 but you wrote it exactly opposite.
4- you don't need to print anything in the while loop, you should either print the biggest odd number or print "There Weren't Any Odd Numbers".
5- an additional variable is needed for saving the maximum odd number which is MAX.
Last note: in the code provided above you can combine the two ifs in the while loop in to one loop using 'and' but since you said you are a beginner I wrote it that way.

Categories