so im a python beginner and i cant find a way to put a input varible in a random like so,
import time
import random
choice = input('easy (max of 100 number), medium(max of 1000) or hard (max of 5000)? Or custom)')
time.sleep(2)
if choice == 'custom':
cus = input(' max number?')
print ('okey dokey!')
eh = 1
cuss = random.randrange(0, (cus))
easy = random.randint(0, 100)
medium = random.randint(0, 1000)
hard = random.randint (0, 5000)
if choice == 'easy' or 'medium' or 'hard' or cus:
while eh == 1:
esy = int(input('what do you think the number is?)'))
if esy > easy:
time.sleep(2)
print ('too high!')
elif esy == easy:
print (' CORRECT!')
break
elif esy < easy:
print ('TOO low')
is there any way i can put a number that someone typed in a random, like in line 9?
There are multiple things wrong with your code. You're using ('s with print, which suggests you're using python3. This means that when you do cus = input(), cus is now a string. You probably want to do cus = int(input())
Doing choice == 'easy' or 'medium' or 'hard' or cus will always be True; I have no idea why people keep doing this in Python, but you need to do choice == 'easy' or choice == 'medium' or choice == 'hard' or choice == 'cus'. Of course, a better way to do it is with a dictionary.
values = {'easy': 100, 'medium': 1000, 'hard': 5000}
And then do
value = values.get(choice)
if not value:
value = int(input("Please enter custom value"))
And then you can do
randomvalue = random.randint(1,value)
Convert your variable cus to an int and pass it as you normally would
cuss = random.randrange(0, int(cus))
Related
So I am trying to make it that if a number is below 50, my code will print out Freestyle and if it is in the range of 51-100 that it will print breaststroke, and finally if it is above 101 that it will print out butterfly.
I am trying to get this and set it up for my swim mates and and for my coach to use to make practice more fun.
Edit I do not receive any output.
This is currently my code:
import random
def swimming():
x = random.randint(1, 150)
if x <= 50:
print("Freestyle")
elif x >= range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
import random
def swimming():
x = random.randint(1, 150)
if x < 51:
print("Freestyle")
elif x >51 and x<100:
print("Breaststroke")
else:
print("Butterfly")
swimming()
This will give you output.
Since you did not post your own code, here's some quick code I whipped up that I think will do what you want:
def fun(x):
if x < 51: # Below 51 (0-50)
print("Freestyle")
elif x > 100: # Above 100 (101+)
print("Butterfly")
else: # In between (51-100)
print("Breaststroke")
Where x is a number that you put into the function as a parameter.
Your code only call for "def", which means "define" (or at least, my interpretation). To do that (ie, "running the script"), you also need to call it out in the end. Furthermore, range is like a list, not a specific 2 points, so calling >= range doesn't work.
Your code should look like this (minimum change)
import random
def swimming():
x = random.randint(1, 150)
if x <= 50:
print("Freestyle")
elif x in range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
swimming()
Note, at this point, it will return a random value, not specified by the user. If you actually want to input a value, check what style you want to swim, and loop back, it should be more like this
import random
def swimming():
print('What is your number?')
try:
x = float(input())
if x <= 50:
print("Freestyle")
elif x in range(51, 100):
print("Breaststroke")
else:
print("Butterfly")
except:
print('Input a number please')
while True:
answer = input('Do you want to continue? (Y/N)\n')
if answer.lower() == 'y' or answer.lower() == 'yes':
swimming()
else:
print('Thank you for playing.')
input('Press enter to exit.')
break
The "try" and "except" in the def block is to make sure that the input is a number (either an integer or a decimal). The "while True" loop is for "continuously working" (as long as you enter "y" or "yes" or "Y" or "YES"). If you don't like that, delete the whole chunk, and just keep "swimming()"
Keep up the good work.
def swimming():
for i in range(5):
x=random.randint(1,150)
if x<=50:
print("Freestyle")
elif x>=51 and x<=100:
print("Breaststroke")
else:
print("Butterfly")
swimming()
you can use the first for loop to take the inputs as much as you want. i think it is more easy to use the logical operators with this.
I need users to be able to type x to exit if they get a question wrong.
I've tried changing the input to a string and then if the answer isn't x then convert the string to an integer with int(user_ans) and even making another value and with ans_string == int(user_ans). Is there any way to add a break to the end if they type x?
if level == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
if user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
else:
print("Try again")
I expect the program to still function but also be for the user to quit.
Just use a try block to see whether the input is a number and change what you do. Something like this:
is_int = false
user_ans = input()
try:
ans_int = int(user_ans)
is_int = true
except:
is_int = false
if is_int:
# Do what you need with the integer
if ans_int == 1:
solution = number_one + number_two
print("What is", number_one, "plus", number_two)
user_ans = int(input())
elif user_ans == solution:
print("Correct")
number_one = random.randrange(1,10)
number_two = random.randrange(1,10)
rounds = rounds + 1
elif user_ans == "x":
# Do what you need to do if it is an "x"
else:
print("Try again")
You can first get the user's input into a variable, like with inStr = input('Enter input: '). Then, you can check it to see if it's 'x'; if it is, you can use sys.exit() (or some other function), and if it's not, you can then cast it to a number and use it. inNum = int(inStr)
By checking the variable first and then casting it, you don't have to worry about what happens if your code tries to run int('x').
If you really want to cast your input to int right away, though, you can use try and except to catch a ValueError, which is what int() will throw if you give it a non-number input. This won't specifically check for 'x' - just for some invalid input.
Whenever you run the game and start guessing it asks first what is guess #0? I'm trying to get it to display "what is guess #1?" but. at the same time keep the number of guesses equal to the number guessed (if that makes sense). Here's my code so far:
import random
def play_game(name, lower=1, upper=10):
secret = random.randint(lower, upper)
tries = 0
print("-----------------------------\n"
"Welcome, {}!\n"
"I am thinking of a number\n"
"between {} and {}.\n"
"Let's see how many times it\n"
"will take you to guess!\n"
"-----------------------------".format(name, lower, upper))
# Main loop
guessing_numbers = True
while guessing_numbers:
guess = input("What is guess #{}?\n".format(tries))
while not guess.isdigit():
print("[!] Sorry, that isn't a valid input.\n"
"[!] Please only enter numbers.\n")
guess = input("What is guess #{}?\n".format(tries))
guess = int(guess)
tries += 1
if guess < secret:
print("Too low. Try again!")
elif guess > secret:
print("Too high. Try again!")
else:
guessing_numbers = False
if tries == 1:
guess_form = "guess"
else:
guess_form = "guesses"
print("--------------------------\n"
"Congratulations, {}!\n"
"You got it in {} {}!\n"
"--------------------------\n".format(name,tries,guess_form))
if tries < 3:
# Randomly chooses from an item in the list
tries_3 = ["Awesome job!","Bravo!","You rock!"]
print (random.choice(tries_3))
# ---
elif tries < 5:
tries_5 = ["Hmmmmmpff...","Better luck next time.","Ohhh c'mon! You can do better than that."]
print (random.choice(tries_5))
elif tries < 7:
tries_7 = ["You better find something else to do..","You can do better!","Maybe next time..."]
print (random.choice(tries_7))
else:
tries_8 = ["You should be embarrassed!","My dog could do better. Smh...","Even I can do better.."]
print (random.choice(tries_8))
choice = input("Would you like to play again? Y/N?\n")
if "y" in choice.lower():
return True
else:
return False
def main():
name = input("What is your name?\n")
playing = True
while playing:
playing = play_game(name)
if __name__ == "__main__":
main()
I have the number of "tries" set to 0 at the beginning. However, if I set that to 1 then play the game and it only takes me 3 tries it will display that it took me 4 tries. so I'm not sure what to do. Still somewhat new to python so I would love some help
Anywhere that you have input("What is guess #{}?\n".format(tries)), use guess = input("What is guess #{}?\n".format(tries+1)). (adding +1 to tries in the expression, but not changing the variable itself)
I wrote the Python code below that is supposed to "guess" a number between 1 and 100, you just have to tell it if the number you're thinking of is higher or lower. But for some reason when I try playing it, it always gets stuck when I tell it that my number is higher after telling it that it's lower or vice versa:
import random
import time
import math
correct = 0
goon = 'yes'
biggest = 100
smallest = 1
tries = 10
print 'Hi!'
time.sleep(0.5)
print 'I´m going to try and guess your number'
time.sleep(0.5)
print 'Just tell me if your number is bigger or smaller than what I guessed'
time.sleep(0.5)
print 'And of course you have to tell me when I´m right, ok?'
time.sleep(0.5)
print 'Type "b" if your number is smaller than what I guessed and type "s" if it´s bigger. When I´m right, type "r".'
time.sleep(0.5)
print 'Oh by the way, your number should be between 1 and 100.'
if goon == 'no' or goon == 'No' or goon == 'n':
print 'Ok, see you soon!'
else:
while goon == 'yes' or goon == 'Yes' or goon == 'y':
guess = random.randint(1,100)
print guess
answer = raw_input()
while correct == 0:
if answer == 'r':
correct = 1
endhooray = random.randint(1, 3)
if endhooray == 1:
print 'Yay, I got it!'
elif endhooray == 2:
print 'Finally!'
elif endhooray == 3:
print 'See, I´m good at this!'
elif answer == 'b':
smallest = guess
difference = 100 - guess
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
elif guess > biggest:
while tries == 10:
add = random.randint(1, difference)
guess = guess + add
if guess < biggest:
print guess
answer = raw_input()
tries == 1000000
elif answer == 's':
biggest = guess
difference = guess - 100
difference = difference * -1
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
elif guess < smallest:
while tries == 10:
subtract = random.randint(1, difference)
guess = guess - subtract
if guess > smallest:
print guess
answer = raw_input()
tries = 100000
else:
print 'Oops, I don´t know what that means'
break
I took the liberty to simplify your code. This should do the job:
import random
import time
# your intro here
correct = False
min_, max_ = 0, 100
while not correct:
guess = random.randint(min_, max_)
answer = raw_input("Is your number %d? (b/s/r): " % guess)
if answer == "b":
min_ = guess+1
print "Ok, I'll aim higher!"
elif answer == "s":
max_ = guess
print "Ok, I'll aim lower!"
elif answer == "r":
hooray = random.choice(["Yay, I got it!", "Finally!", "See, I'm good at this!"])
print hooray
correct = True
else:
print "Oops, I don't know what that means!"
I am having trouble finding a way to get the user to repeat the code without having to exit out the shell. This is what I have so far.
import random
randomNum = random.randint(1, 10)
start = True
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#The code cant be both less than and greater than. The or function allows this
while (answer > randomNum) or (answer < randomNum):
if (answer == randomNum + 1):
print "Super Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#First one
elif (answer == randomNum + 2):
print "Pretty Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Second one
elif (answer == randomNum + 3):
print "Fairly Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Third one
elif (answer == randomNum + 4):
print "Not Really Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Fourth one
elif (answer == randomNum + 5):
print "Far"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Fifth one
elif (answer == randomNum - 5):
print "Far"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Sixth one
elif (answer == randomNum - 4):
print "Not Really Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Seventh one
elif (answer == randomNum - 3):
print "Fairly Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Eighth one
elif (answer == randomNum - 2):
print "Pretty Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Nineth one
elif (answer == randomNum - 1):
print "Super Close"
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
#Tenth one
else:
print "Good Job!"
print randomNum
if (start == True):
answerAgain = raw_input("Do you want to restart this program ? ")
if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
#Empty space because I don't know what to put in here.
else:
print "See ya next time!"
I would like to know how to get all of this code to apply to one variable or to repeat without me having to write it 50 times.
I recommend enclosing the whole thing in a while loop.
start = True
while start == True:
"""your code here"""
answerAgain = raw_input("Do you want to restart this program ? ")
if answerAgain == ("Yes", "yes", "ya", "Ya", "Okay", "Sure", "Si", "Start"):
start = True
else:
start = False
That way your entire code will run again if start == True.
I would also recommend that you use a list for your responses.
responses = ["Super Close", "Pretty Close", "Fairly Close", "Not Really Close", "Far"]
That way you can map to the appropriate response using the difference:
print responses[abs(answer - randomNum) - 1]
Put code in while loop to repeat it.
start = True
while start:
# code
if answerAgain.lower() in ('no', 'niet', 'bye'):
start = False
If you use the absolute value between the number the user provides and your random number, you only have to document half as many cases (i.e. -1 and +1 get treated the same).
Rather than asking for their new answer in after each case, move this code to the top of the main loop since it's requests at the start of the program and following all 'wrong' answers.
For usage, you'll probably want to convert all 'word' answers to lowercase, as case doesn't appear to matter in the case.
You can use quit() to cleanly exit the program.
So maybe like this:
import random
while(True):
randomNum = random.randint(1, 10)
answer = 0
while abs(answer - randomNum) > 0:
answer = int(input("Try to guess a random number between 1 and 10. "))
if abs(answer - randomNum) == 1:
print("Super Close")
elif abs(answer - randomNum) == 2:
print("Pretty Close")
# the other cases ...
# gets here if abs(answer - randonNum) == 0, i.e. they guessed right
print("Good Job!", randomNum)
answerAgain = input("Do you want to restart this program ? ")
if answerAgain.lower() in ["yes", "ya", "y", "okay", "sure", "si", "start"]:
pass
else:
print("See ya next time!")
quit()