Python if else statement - python

My if statement works but else doesn't can anyone help me?
this is my code. Btw if anyone knows how to ask for a retry after one time would be awesome!
import random
print('choose a number between 1 and 10,if you guess right you get 10 points if you guess wrong you lose 15points')
answer = input()
randint = random.randint(0,2)
print('the answer is ',randint)
if [answer == randint]:
print('gratz! you win 10points!')
else:
print('you lose 15points!')

Don't put brackets around your if statement. When you do that, you are creating a new list. Change it to this:
if answer == randint:
You could put parentheses around it if you wanted to, but not []. Your second problem is that random.randint() returns an integer, but input() returns a string (in Python3). You could say if int(answer) == randint: instead, or you could say if answer == str(randint):. Your third problem, as #cricket_007 pointed out is randint(0, 2) will return an integer between 0 and 2, not 1 and 10. Just change that line to randint = random.randint(1, 10).

If you want it to loop after each game, just add these lines around it like so:
import random
loop = true
while loop:
----insert your code here----
This will make it loop endlessly.
Hope this helps!

Related

Why does my inner loop never finish in my number guessing game?

When I try to guess the randomly generated number, the correct guess is never correct, and therefore the inner loop never finishes. I have tried debugging with print statements.
from random import randint
print('Welcome to the Number Guessing Game (Numbers 1 - 1000).')
while True:
tries = 0
random_num = randint(1, 10)
print(random_num)
guess = input('guess my number, human: ')
while random_num is not guess:
guess = input('Try again: ')
print(guess)
tries += 1
print('Correct!' + ' It took you' + str(tries) + ' tries.')
First of all, you have to convert the guess variable to an integer. Input simply returns strings and a string can't be equal to an integer.
The second problem with your programme is that is and is not keywords check, whether two "variables" (in Python, variables are just references to an object) are/aren't pointing to the same object.
This might not be your case even if your guess was correct (even though they can have the same value they are different objects). Sometimes this is not a problem since Python will point both "variables" to the same object for efficiency. But you can't be sure, can you!
Check this: Why does comparing strings in Python using either '==' or 'is' sometimes produce a different result?
Anyways, it's better to use the == and != operator in similar cases and the second problem will disappear.
Type error...
Add more debug code for the answer
print('random_num',random_num, type(random_num))
print('guess', guess, type(guess))
Output
Welcome to the Number Guessing Game (Numbers 1 - 1000).
random_num 2 <class 'int'>
guess my number, human: 2
guess 2 <class 'str'>
Fix:
while random_num is not int(guess):

Is os module doing something here? Input not getting appended to my list

Sorry for the general question I just don't really know what else to ask. So my problem is that nothing appends to my "num_list". I was thinking maybe it has to do with the clear function I made? Is it maybe resetting my list so that nothing gets appended? I'm sure it's just something simple that I overlooked. Would really appreciate some help, and again, I apologize for the general question.
import os
def clear():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
num_list = []
user_nums = 0
while True:
clear()
print('Type DONE to calculate the average of the numbers you entered!')
if num_list:
print('Here are the numbers you want to find the average of:{}'.format(num_list))
try:
nums = input("What numbers do you want to find the average of? ")
if nums.upper() == 'DONE':
clear()
print('The average is: {}'.format(user_nums/len(num_list)))
float(nums)
if isinstance(nums, (float, int)):
num_list.append(nums)
user_nums += nums
except ValueError:
print('Please only enter numbers.')
Your problem has nothing to do with os. nums is a string (of type str). You think you convert it to a float, but you do not assign the result to any variable and it is lost. After the conversion, nums is still a string.
float(nums) must be nums=float(nums). When Python attempts to execute this assignment, it either succeeds (and then there is no point in checking nums's type again) or fails, and then there is an exception.

Creating a small program in python

I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.

I need to figure out how to make my program repeat. (Python coding class)

I am a beginner student in a python coding class. I have the majority of the done and the program itself works, however I need to figure out a way to make the program ask if wants a subtraction or an adding problem, and if the user would like another question. I asked my teacher for assistance and he hasn't gotten back to me, so I'm simply trying to figure out and understand what exactly I need to do.
import random
x = int(input("Please enter an integer: "))
if x < 0:
x = 0
print('Negative changed to zero')
elif x == 0:
print('Zero')
elif x == 1:
print('Single')
else:
print('More')
maximum = 10 ** x;
maximum += 1
firstnum = random.randrange(1,maximum) # return an int from 1 to 100
secondnum = random.randrange(1, maximum)
compsum = firstnum + secondnum # adds the 2 random numbers together
# print (compsum) # print for troubleshooting
print("What is the sum of", firstnum, " +", secondnum, "?") # presents problem to user
added = int(input("Your answer is: ")) # gets user input
if added == compsum: # compares user input to real answer
print("You are correct!!!")
else:
print ("Sorry, you are incorrect")
You'll want to do something like this:
def foo():
print("Doing good work...")
while True:
foo()
if input("Want to do more good work? [y/n] ").strip().lower() == 'n':
break
I've seen this construct (i.e., using a break) used more often than using a sentinel in Python, but either will work. The sentinel version looks like this:
do_good_work = True
while do_good_work:
foo()
do_good_work = input("Want to do more good work? [y/n] ").strip().lower() != 'n'
You'll want to do more error checking than me in your code, too.
Asking users for input is straightforward, you just need to use the python built-in input() function. You then compare the stored answer to some possible outcomes. In your case this would work fine:
print('Would you like to test your adding or subtracting skills?')
user_choice = input('Answer A for adding or S for subtracting: ')
if user_choice.upper() == 'A':
# ask adding question
elif user_choice.upper() == 'S':
# ask substracting question
else:
print('Sorry I did not understand your choice')
For repeating the code While loops are your choice, they will repeatedly execute a statement in them while the starting condition is true.
while True: # Condition is always satisfied code will run forever
# put your program logic here
if input('Would you like another test? [Y/N]').upper() == 'N':
break # Break statement exits the loop
The result of using input() function is always a string. We use a .upper() method on it which converts it to UPPERCASE. If you write it like this, it doesn't matter whether someone will answer N or n the loop will still terminate.
If you want the possibility to have another question asked use a while loop and ask the user for an input. If you want the user to input whether (s)he want an addition or substraction you already used the tools to ask for such an input. Just ask the user for a string.

Loop and validation in number guessing game

I have previously studied Visual Basic for Applications and am slowly getting up to speed with python this week. As I am a new programmer, please bear with me. I understand most of the concepts so far that I've encountered but currently am at a brick wall.
I've written a few functions to help me code a number guessing game. The user enters a 4 digit number. If it matches the programs generated one (I've coded this already) a Y is appended to the output list. If not, an N.
EG. I enter 4567, number is 4568. Output printed from the list is YYYN.
import random
def A():
digit = random.randint(0, 9)
return digit
def B():
numList = list()
for counter in range(0,4):
numList.append(A())
return numList
def X():
output = []
number = input("Please enter the first 4 digit number: ")
number2= B()
for i in range(0, len(number)):
if number[i] == number2[i]:
results.append("Y")
else:
results.append("N")
print(output)
X()
I've coded all this however theres a few things it lacks:
A loop. I don't know how I can loop it so I can get it to ask again. I only want the person to be able to guess 5 times. I'm imagining some sort of for loop with a counter like "From counter 1-5, when I reach 5 I end" but uncertain how to program this.
I've coded a standalone validation code snippet but don't know how I could integrate this in the loop, so for instance if someone entered 444a it should say that this is not a valid entry and let them try again. I made an attempt at this below.
while myNumber.isnumeric() == True and len(myNumber) == 4:
for i in range(0, 4)):
if myNumber[i] == progsNumber[i]:
outputList.append("Y")
else:
outputList.append("N")
Made some good attempts at trying to work this out but struggling to patch it all together. Is anyone able to show me some direction into getting this all together to form a working program? I hope these core elements that I've coded might help you help me!
To answer both your questions:
Loops, luckily, are easy. To loop over some code five times you can set tries = 5, then do while tries > 0: and somewhere inside the loop do a tries -= 1.
If you want to get out of the loop ahead of time (when the user answered correctly), you can simply use the break keyword to "break" out of the loop. You could also, if you'd prefer, set tries = 0 so loop doesn't continue iterating.
You'd probably want to put your validation inside the loop in an if (with the same statements as the while loop you tried). Only check if the input is valid and otherwise continue to stop with the current iteration of your loop and continue on to the next one (restart the while).
So in code:
answer = [random.randint(0, 9) for i in range(4)]
tries = 5
while tries > 0:
number = input("Please enter the first 4 digit number: ")
if not number.isnumeric() or not len(number) == len(answer):
print('Invalid input!')
continue
out = ''
for i in range(len(answer)):
out += 'Y' if int(number[i]) == answer[i] else 'N'
if out == 'Y' * len(answer):
print('Good job!')
break
tries -= 1
print(out)
else:
print('Aww, you failed')
I also added an else after the while for when tries reaches zero to catch a failure (see the Python docs or maybe this SO answer)

Categories