Trying to mix while and raw_input commands - python-2.7

I'm very new to python IDLE, I have been tasked with making a game that asks you to guess a random number, here is what I have but whatever I type in it returns "you were too high" a little help would be very appreciated thanks.
import random
i = random.randint(0,100)
print (i)
e = raw_input ("Guess what number I'm thinking of between 0 and 100!")
while e != i:
if i > e:
print "You were too low."
elif i < e:
print "You were too high."
e = raw_input ("Guess what number I'm thinking of between 0 and 100!")
if e == i:
print "yay"

You need to typecast your return call using raw_input, you're comparing ASCII values to integers, example 1 as an ascii character would be 0x31 (49), which compared to 1 is obviously higher. Every value you input is going to output as higher, simple do this to fix your issue.
e = (int(raw_input("Guess what number I'm thinking of between 0 and 100!")))

Related

Testing integer error in while loop

I have ran into some problems while trying to combine while loop and ValueError.
Initially I wanted my program to add numbers together. When the sum of numbers has exceeded X, I would like my program to continue to else statement. At first I didn't focus on the fact that input could also be (for example) string.
number = 1
while number < 10:
add = int(raw_input("Enter a number to add: "))
number += add
print number
else:
print "Number is greater than 10"
I tried combining the first code with try/except and ValueError to accept integers as the only inputs. Second code will not continue to else statement when sum of numbers exceeds X. Could someone please explain why this is not working?
number = 1
while number < 10:
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
except ValueError:
print "Please enter a number"
else:
print "Number is greater than 10"
Thank You.
there's an extra while True: loop resulting in an infinte loop.
Remove it and your code will work fine.
Another example where while(condition) (with condition not True) leads to mistakes: you have to ensure that the loop will be entered once, sometimes by initalizing your condition artificially. I would write that instead
number = 1
while True:
try:
add = int(raw_input("Enter a number: "))
number += add
print number
if number>10:
break
except ValueError:
print "Please enter a number"
print "Number is greater than 10"

Writing a perpetual program with Python to check validity of integers

I am a beginner in Python and I was trying to write a small program that asks the user to enter an integer that is greater than 0. The function should keep on asking the user for the number until it is valid.
I tried something like below, however I am getting the wrong results. Can you please help me understand my error?
num = input('please enter a number: ' )
n = int(num)
while n < 0:
num = input('please enter a number: ' )
if n >= 0:
print('Valid number')
else:
print('Invalid number')
Is it possible to start the code without an input function? (like to start with num = int())
Thank You for Your Time
There's an error with the logic behind your code.
You firstly ask the user for a number and if he inputs a number which is greater than or equal to 0, the while-loop will never start (in your script: while n < 0:), which, I assume is fine, because the goal of your program is, as you said, to make "the user to enter an integer that is greater than 0".
If the user inputs a number that is smaller than or equal to 0, the while-loop will start, but will never break because inside of it, the value of variable n never changes, only does the value of num.
This is an appropriate script considering that you want to make the user input a number greater than 0, and that you want to give feedback regarding their input.
n = None
while n <= 0:
n = int(input('please enter a number: '))
if n <= 0:
print('Invalid number')
else:
pass # the loop will break at this point
# because n <= 0 is False
print('Valid number')
The code has the user stuck in a loop until they write a number that's greater than 0.
Another solution would be to, inside the loop, check whether int(num) is greater than 0 and if it is, print 'Valid number' and do break to stop the loop; if it's not, print 'Invalid number' (though then the loop doesn't need to be defined by while n < 0:; rather by while True:.
Also, what do you mean by this:
Is it possible to start the code without an input function? (like to start with num = int())
Please clarify this part.
If your problem is the code not terminating, writing Invalid number all the time it's because you are not updating the value of n. You assigned it just once. The solution to your problem is as follows:
n = -1
while n < 0:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
By the way you get rid of starting the code without an input function.
Edit:
As you just said - you want to keep the input reading despite passing an negative integer into the command line. This should help you accomplish this:
while True:
n = int(input('please enter a number: '))
if n >= 0:
print('Valid number')
else:
print('Invalid number')
This loop will go forever until you exit the program lets say with ctrl + C. while True: is as you see an forever ongoing loop, because the True argument will never be false.

While loop being skipped

I can't seem to get my while loop code to run inside my code. I bet it is very obvious but I cannot seem to find the answer for it. This program is supposed to let you choose how many numbers you want to have randomly chosen and the numbers it can be between. It seems that the while loop doesn't want to work. It skips the while loop and goes to the sleep(10). Thank you for the help!
import random
import time
from time import sleep
x = raw_input("Enter first number you want to be the minimum: ")
y = raw_input("Enter second number you want to be the maximum: ")
a = raw_input("Enter ammount of random numbers you want: ")
p = 1
while p >= a:
print "Your number is " + str(int(random.randint(x - 1,y + 1)))
p = p + 1
sleep(10)
raw_input returns a string. This means you are comparing a string to an integer for your while condition. A quick test shows integers are always "less than" strings.
>>> 10000 > '1'
False
>>> 10000 < '1'
True
Luckily, this behavior is changed in python3 where it throws a TypeError.

In python, how to convert specific values in a list to different values based on special conditions

I am trying to write a program that converts a percentage received in a class into a GPA format then eventually find the overall GPA. I want it to first prompt the user to input the amount of classes, then input the percentages. I am running into some trouble getting the program to convert the percentage into the GPA format (90 or greater equals 4, 80 to 89 equals 3, ect...). This is what I have so far
class_number = int(raw_input("How many classes do you have? "))
total_grade = list((raw_input("Enter Percentage: ")) for i in range(class_number))
a = total_grade
def alter(x):
if x >= 90:
return 4
elif x >= 80:
return 3
a = map(alter,a)
print a
The problem is that this only seems to output 4s no matter the original percentage.
Any help would be greatly appreciated! Thanks!
That's because x is actually a string. I think a string will always be greater than a number. You need to convert each item in total_grade to an int:
total_grade = list(int(raw_input("Enter Percentage: ")) for i in range(class_number))
Also, you can just use a list comprehension:
total_grade = [int(raw_input("Enter Percentage: ")) for i in range(class_number)]

Why is python skipping a line?

I'm pretty new to Python (just started teaching myself a week ago), so my debugging skills are weak right now. I tried to make a program that would ask a user-submitted number of randomly-generated multiplication questions, with factors between 0 and 12, like a multiplication table test.
import math
import random
#establish a number of questions
questions = int(input("\n How many questions do you want? "))
#introduce score
score = 1
for question in range(questions):
x = random.randrange(0,13)
y = random.randrange(0,13)
#make the numbers strings, so they can be printed with strings
abc = str(x)
cba = str(y)
print("What is " + abc + "*" + cba +"?")
z = int(input("Answer here: "))
print z
a = x*y
#make the answer a string, so it can be printed if you get one wrong
answer = str(a)
if z > a or z < a:
print ("wrong, the answer is " + answer)
print("\n")
#this is the line that's being skipped
score = score - 1/questions
else:
print "Correct!"
print ("\n")
finalscore = score*100
finalestscore = str(finalscore)
print (finalestscore + "%")
The idea was that every time the user gets a question wrong, score (set to 1) goes down by 1/question,so when multiplied by 100 it gives a percentage of questions wrong. However, no matter the number of questions or the number gotten wrong, score remains 1, so finalestscore remains 100. Line 26 used to be:
if math.abs(z)-math.abs(a) != 0:
but 2.7.3 apparently doesn't acknowledge that math has an abs function.
Such a simple accumulator pattern doesn't seem like it would be an issue, even for an older version of Python. Help?
Try score = score - 1.0/questions
The problem is that you're doing integer division, which truncates to the nearest integer, so 1/questions will always give 0.
The problem is that you are using integers for all of your calculations. In particular, when you calculate 1/questions, it truncates (rounds down) to an integer because both values in the calculation are integers.
To avoid this, you could instead use 1.0/questions to make the calculations use floating point numbers instead (and not truncate)