`So I am just making something to test if I can make certain outputs based on inputs
Each time I try to enter an answer, nothing happens here
I used if elif statements with the in range() in them.
Nothing shows up when I type the answer
from random import randint
from termcolor import colored
repeat = True
from termcolor import colored
import time
import sys
import multiprocessing
print colored("Hello, this is a program to help you practice algebraic
expressions.","magenta")
print("")
time.sleep(4)
print colored("Alright let's start with something very basic...\nWhat is x
if
2x
= 32?","magenta")
prob = int(raw_input())
if int(prob) in range (16, 16):
print colored("Well done, you got the warmup correct","yellow")
elif int(prob) in range(1, 15):
print colored("Incorrect answer try again","red")
This line if int(prob) in range(16,16): is problem. Function range(x,y) generates list equals to [x,y), which means starting with x and including x, ending with y excluding y, so by that, you are asking if your number is in empty array.
Example:
list_of_numbers = range(12,16) gives us list with elements list_of_numbers = [12,13,14,15]
I have written this code removing all the functions that you haven't used and the coloured text which seemed to always error. range is generally used in "for" loops but in conditionals you need to use == if it is equal to > for greater than < less than != not equal to e.t.c.
import time
print ("Hello, this is a program to help you practice algebraic
expressions.")
print("")
time.sleep(4)
prob =int (input("Alright let's start with something very basic What is
x if 2x = 32? "))
if prob ==16:
print("Well done, you got the warmup correct")
else:
print("Incorrect answer try again")
`
Related
I created a code that takes a list from the user and then asks the user to choose from printing only the odd numbers or the even numbers. But whenever the user choice is taken, the execution freezes. Using keyboard interrupt, I find that the execution stopped in either the odd or even function. Please help !!!
here is the code:
from os import lstat
def odd(lst,oddlst):
for i in range(0,n):
while(lst[i]%2!=0):
oddlst.append(lst[i])
return oddlst
def even(lst,evenlst):
for i in range (0,n):
while(lst[i]%2==0):
evenlst.append(lst[i])
return evenlst
lst = []
oddlst = []
evenlst = []
n = int(input("enter number of elements \n"))
print("\nenter the elements \n")
for i in range(0,n):
num = int(input())
lst.append(num)
print(lst)
choice = input(" Do you want to print odd elements or even elements \n (odd/even)
\n")
if(choice=="odd"):
odd(lst,oddlst)
print(oddlst)
elif(choice=="even"):
even(lst,evenlst)
print(evenlst)
else:
print("invalid choice")
Perhaps you meant to use an if instead of a while in your odd and even functions.
The reason your execution "freezes", is that you run into an infinite loop.
In either while, the i-th element gets checked, then appended to a list. But the condition, against which you are checking, doesn't change, neither does the index i.
Changing your whiles to ifs should solve your problem.
Also, for a more elegant solution to your problem, have a look at:
https://docs.python.org/3/library/functions.html#filter
How to filter a list
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.
Hi, I'm still a beginner and a bit lost. I'm working on a project for school that requires me to write different small programs that will 'guess' the given password. This is a bruteforce program, and I need it to guess every possible combination of 4 number passwords like those on the old iPhones. My problem is that when I use random.sample it generates the same random numbers multiple times. What function can I use, or what should I change so that the random numbers within the given range don't repeat themselves? I tried doing rand.int but it gave me "TypeError: 'int' object is not iterable"
Additional questions:
- How do I get my loop to stop once n == Password4 ? It simply continues, even after the correct password is found.
- Is there a way I can count the number of fails(n != Password4) before my success (n == Password4)?
This is my code:
import random
Password4 = 1234
def crack_password():
while True:
for n in (random.sample(range(1112, 10000), 1)):
while n == Password4:
print(n, "is the password")
break
if n != Password4:
print('fail')
break
crack_password()
Update: Using a code now that does not generate random non-recurring numbers but works for the purposes I intended. Please still feel free to answer the original questions, and thank you all so much for your kindness and prompt responses.
New Code (credit goes to #roganjosh):
import datetime as dt
Password4 = 9999
def crack_password():
start = dt.datetime.now()
for n in range(10000):
password_guess = '{0:04d}'.format(n)
if password_guess == str(Password4):
end = dt.datetime.now()
print("Password found: {} in {}".format(password_guess, end - start))
break
guesses = crack_password()
If you really want to try all passwords in random order. this is more easily accomplished by
import random
digits = [str(i) for i in range(10)]
s = [''.join([a,b,c,d]) for a in digits for b in digits for c in digits for d in digits]
random.shuffle(s)
real_password = '1234'
i = 0
for code in s:
if code == real_password:
print()
print('The password is: ', code)
break
else:
i += 1
print(i, ' failures', end='\r')
You probably want to check out all possible values for a password under certain rules, e.g "4 digits" or "8 lowercase characters". Consider these answers as starting points:
Generating 3-letter strings with itertools.product for using an alphabet and generating n-length strings
itertools.permutations if you know a set of characters that don't repeat
If you just want to format integers with zero padding on the left (0000, 0001, ... 9999) see how to accomplish that with format strings.
You have two while loops, so even though you attempt to break when you find the password, the outer (first) while loop just starts it off all over again.
If you want unique guesses then you would have to look into permutations. However, since it's reasonable to assume that the password itself would be random, then random guesses of that password would be no more efficient at cracking the password than simply going through the whole list of potential passwords sequentially.
Try something like this:
import datetime as dt
Password4 = 5437
def crack_password():
start = dt.datetime.now()
for n in range(9999):
password_guess = '{0:04d}'.format(n)
if password_guess == str(Password4):
end = dt.datetime.now()
print "Password found: {} in {}".format(password_guess, end - start)
break
guesses = crack_password()
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!
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)