Python: Printing something changes the outcome? - python

So I'm new to this programming thing... But this has me stumped. To the point that I'm wondering if the website I'm running Python on is wrong. (repl.it is the website).
So I did one of those guess the number games as a small fun challenge. This is the code that I came up with:
from random import randint
print ("Welcome to guess the number!")
answer = str(randint(0,100))
print (answer)
print ()
def something():
answerTwo = str(randint(0,100))
print (answerTwo)
idea(answerTwo)
def idea(x):
number = str(input("Guess a number between 0 and 100:"))
if number != x:
if (number > x):
print()
print(number + " is too high!")
print()
idea(x)
elif (number < x):
print()
print(number + " is too low!")
print()
idea(x)
else:
print()
print ("That is correct!")
again = input("Would you like to play again?:")
if again == "yes":
something()
else:
print ("Thanks for playing!")
idea(answer)
On the 4th and 8th line I print out the random number chosen so that I can quickly test to make sure everything works. Then I removed the print functions in the final product and tested again. Except when I removed the print functions it stopped working after some amount of time. For example, it'll say 39 is too low but 40 is too high, which is impossible since they're is no number in between them. If you put the print functions back in it works again, but remove them and it'll start acting up eventually.
I apologize if it's something really obvious but I just don't understand how this is possible.
Here is the github thingy for it
https://gist.github.com/anonymous/4a370664ae8ddb29aec5915eb20e686f
Thanks for your time!

There is no integer i such that 39 < i < 40.
There is however a numeric string s such that "39" < s < "40". Observe:
>>> "39" < "4" < "40"
True
In short: It has nothing to do with your print calls, instead, just work on actual numbers and cast your input to a number using int(). print() can handle numbers just fine.

Related

Multiplication guessing game in Python | if wrong guess until it is correct

I am trying to write a program as follows:
Python generates random multiplications (factors are random numbers from 1 to 9) and asks to the users to provide the result
The user can quit the program if they input "q" (stats will be calculated and printed)
If the user provides the wrong answer, they should be able to try again until they give the correct answer
if the user responds with a string (e.g. "dog"), Python should return an error and ask for an integer instead
It seems I was able to perform 1) and 2).
However I am not able to do 3) and 4).
When a user gives the wrong answer, a new random multiplication is generated.
Can please somebody help me out?
Thanks!
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
while True:
counter_attempt += 1
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1
Hi my Idea is to put the solving part in a function:
import random
counter_attempt = -1
counter_win = 0
counter_loss = 0
def ask(num1, num2, attempt, loss, win):
result = str(num1 * num2)
guess = input(f"How much is {num1} * {num2}?: ")
if guess == "q":
print(
f"Thank you for playing, you guessed {win} times, you gave the wrong answer {loss} times, on a total of {attempt} guesses!!!")
return attempt, loss, win, True
try:
int(guess)
except ValueError:
print("Please insert int.")
return ask(num1, num2, attempt, loss, win)
if guess == result:
print("Congratulations, you got it!")
win += 1
return attempt, loss, win, False
elif guess != result:
print("Wrong! Please try again...")
loss += 1
attempt += 1
return ask(num1, num2, attempt, loss, win)
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
counter_attempt, counter_loss, counter_win, escape = ask(num_1, num_2, counter_attempt, counter_loss, counter_win)
if escape:
break
Is that what you asked for?
Note that everything withing your while loop happens every single iteration. Specifically, that includes:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
So you are, indeed, generating new random numbers every time (and then announcing their generation to the user with guess = input(f"How much is {num_1} * {num_2}?: "), which is also within the loop).
Assuming you only intend to generate one pair of random numbers, and only print the "how much is...?" message once, you should avoid placing those within the loop (barring the actual input call, of course: you do wish to repeat that, presumably, otherwise you would only take input from the user once).
I strongly recommend "mentally running the code": just go line-by-line with your finger and a pen and paper at hand to write down the values of variables, and make sure that you understand what happens to each variable & after every instruction at any given moment; you'll see for yourself why this happens and get a feel for it soon enough.
Once that is done, you can run it with a debugger attached to see that it goes as you had imagined.
(I personally think there's merit in doing it "manually" as I've described in the first few times, just to make sure that you do follow the logic.)
EDIT:
As for point #4:
The usual way to achieve this in Python would be the isdigit method of str:
if not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
An alternative method, just to expose you to it, would be with try/except:
try:
int(guess) # Attempt to convert it to an integer.
except ValueError: # If the attempt was unsuccessful...
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration.
And, of course, you could simply iterate through the string and manually ensure each of its characters is a digit. (This over-complicates this significantly, but I think it is helpful to realise that even if Python didn't support neater methods to achieve this result, you could achieve it "manually".)
The preferred way is isdigit, though, as I've said. An important recommendation would be to get yourself comfortable with employing Google-fu when unsure how to do something in a given language: a search like "Python validate str is integer" is sure to have relevant results.
EDIT 2:
Make sure to check if guess == 'q' first, of course, since that is the one case in which a non-integer is acceptable.
For instance:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
elif not guess.isdigit():
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
elif guess == result:
...
EDIT 3:
If you wish to use try/except, what you could do is something like this:
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
break
try:
int(guess)
except ValueError:
print('Invalid input. Please enter an integer value.')
continue # Skip to next iteration
if guess == result:
...
You are generating a new random number every time the user is wrong, because the
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
Is in the while True loop.
Here is the fixed Code:
import random
counter_attempt = 0
counter_win = 0
counter_loss = 0
while True:
num_1 = random.randint(1, 9)
num_2 = random.randint(1, 9)
result = str(num_1 * num_2)
while True:
guess = input(f"How much is {num_1} * {num_2}?: ")
if guess == "q":
print(f"Thank you for playing, you guessed {counter_win} times, you gave the wrong answer {counter_loss} times, on a total of {counter_attempt} guesses!!!")
input()
quit()
elif guess == result:
print("Congratulations, you got it!")
counter_win += 1
break
elif guess != result:
print("Wrong! Please try again...")
counter_loss += 1

Why cant i sum up all of my values (user values) problem with while?

I'm new to the coding world. I have a problem with adding up all of the users' input values, as I don't know how many there will be. Any suggestions?
This is how far I've gotten. Don't mind the foreign language.
import math
while(True):
n=input("PERSONS WEIGHT?")
people=0
answer= input( "Do we continue adding people ? y/n")
if answer == "y" :
continue
elif answer == "n" :
break
else:
print("You typed something wrong , add another value ")
people +=1
limit=300
if a > limit :
print("Cant use the lift")
else:
print("Can use the lift")
You don't need to import math library for simple addition. Since you did not mention that what error are you getting, so I guess that you need a solution for your problem. Your code is too lengthy. I have write a code for you. which has just 6 lines. It will solve your problem.
Here is the code.
sum = 0;
while(True):
n = int(input("Enter Number.? Press -1 for Exit: "))
if n == -1:
break
sum = sum+n
print(sum)
Explanation of the Code:
First, I have declared the variable sum. I have write while loop, inside the while loop, I have prompt the user for entering number. If user will enter -1, this will stop the program. This program will keep on taking user input until unless user type "-1". In the end. It will print total sum.
Output of the Code:
Here's something for you to learn from that I think does all that you want:
people = 0
a = 0
while True:
while True:
try:
n = int(input("PERSONS WEIGHT?"))
break
except ValueError as ex:
print("You didn't type a number. Try again")
people += 1
a += int(n)
while True:
answer = input("Do we continue adding people ? y/n")
if answer in ["y", "n"]:
break
print("You typed something wrong , add another value ")
if answer == 'n':
break
limit = 300
if a > limit:
print("Total weight is %d which exceeds %d so the lift is overloaded" % (a, limit))
else:
print("Total weight is %d which does not exceed %d so the lift can be operated" % (a, limit))
The main idea that was added is that you have to have separate loops for each input, and then an outer loop for being able to enter multiple weights.
It was also important to move people = 0 out of the loop so that it didn't keep getting reset back to 0, and to initialize a in the same way.

answer never = guess no matter the input

My code will always take the first input despite the input. I have tried taking guess and making guess into an int but that leads to both if statements to trigger
x = 1
answer = 4
A=0
guess = 0
while A < 10:
for _ in range (5):
x = random.randint(1,5)
print ("Ralph holds up " + str(x) + " fingers what is the answer")
guess=input()
if guess != answer:
print("WRONG PROGRESS RESET")
A=0
answer = x
if guess == answer:
A += 1
print ("correct")
print ("You have " + str(A) + " out of 10 finished")
answer = x
print ("You win congrats")
First off your code never even import random to use randint. But I'll assume you did import it and you just never pasted it in.
input reads your input as a str, but you want it to read as an int. All you really need to do is wrap the input() call in an int invocation. Additionally, input takes an argument, which prompts that argument in the console.
Also #tobias_k has a good point, but instead of elif guess == answer:, just use else:.
I also changed some variable logic, and I changed A to a much more meaningful identifier, as well as fixing formatting, like a = b is more aesthetically pleasing than a=b.
Oh and indentation. Indentation is important, not only for readability, but in Python, it's required. Python is whitespace significant, meaning scope delimiters are whitespace.
import random
finished_count = 0
while finished_count < 10:
for _ in range(5):
answer = random.randint(1, 5)
guess = int(input("Ralph holds up %d finger%s. What is the answer?\n" % (answer, "" if answer == 1 else "s")))
if guess != answer: # incorrect answer
print("WRONG PROGRESS RESET")
finished_count = 0
else: # correct
finished_count += 1
print("Correct. You have %d out of 10 finished" % finished_count)
print("You win, congrats!")
I just used this code up until I got to 10 and it works fine

Another guessing game in Python, with a little difference

Before writing this question, I looked for something similar in the forum, but did not find any. So here is my version of the guessing game. I want the user to guess a number from 0 to 10 that the computer has "thought". But I want to calculate the difference of the numbers and show whether the user is close or not to figuring out the correct number.
My code is as follows:
import math
import random
intnum = random.randrange(0,11)
print(intnum)
print ("The computer generated a random number from 0 to 10! Can you guess it?")
guess = 0
while guess != intnum:
guess = int(input ("Pick a number!!: "))
num = abs(guess-intnum)
print (num)
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I print the computers number and the difference, to find my bugs easily. There is a logical error that I cannot solve. If the computer generates a number 9, and I guess a number 1, the difference is 9-1=8. But the program, prints "You are less than 2 away", which is incorrect. What am I doing wrong? I would like to use this in a larger version with more numbers but for starters I scaled it down a bit to find the correct logic and syntax.
This block needs rewriting from
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 or num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 or num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
to
if (num==0):
print ("Congrats! The answer is %s" % (guess))
break
elif (num>0 and num<=2):
print ("You are less than 2 away. Keep going!")
elif (num>2 and num<=5):
print ("You are more than 2 away. Try again!")
elif (num>5):
print ("You are more than 5 away!! Try again.")
I understand what you're trying to do with the "or"s in your initial code block, but the computer will think differently, and in this case, "and" is your friend.
The right statement is:
elif (num<=2):
print ("You are less than 2 away. Keep going!")
The condition you are using does not do what you want.
You need to check if a number lies in an interval. To do so, you need to ensure that the number is greater that the lower bound and lower than the upper bound
You need to change the or to and in your conditions

Flowchart in Python

I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)

Categories