Can't seem to get the code to work on if player_guess in player_lucky_list:. It does not check if I had guessed the right number. Also having trouble with the task d.
d. If it is a number, and in the list, but doesn’t match
lucky_number then you find out number(s) that has max
difference as is 10, and assign the numbers that has 10
difference into list input_diff and add the lucky_number if
it was not in the list, then write out:
“your number is 10 points more or less from these
numbers : {input_diff}, do you like to try again? (type ‘Y’
= yes, ‘N’ = no)”
from datetime import datetime, date
import random
def age(born):
today = date.today()
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
player_fname = input("Name: ")
player_age = int(input("Age: "))
running = True
while running:
player_birthday = datetime.strptime(input("Birthday (format yyyymmdd): "), "%Y%m%d")
age_player = int(age(player_birthday))
if age_player == player_age:
print("Wow your age is right, let’s continue!")
running = False
else:
print("Aha, we are in 2022 and your age is not right, kindly enter it again?")
lucky_number = random.randint(1, 200)
tries_count = 0
player_lucky_list = []
n = 10
for i in range(n):
player_lucky_list.append(random.randint(0, 200))
player_lucky_guess = []
guessing = True
while guessing:
message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
print(message)
player_guess = input("Please enter number from {}: ".format(player_lucky_list))
if player_guess in player_lucky_list:
print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
elif str in player_guess:
print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
else:
print("Try again")
tries_count += 1
player_lucky_guess.append(player_guess)
print(player_lucky_guess)
Your list is storing different int values. The input function defaults to accepting strings. So you need to convert the string of "player_guess" into an int.
while guessing:
message = "Hi {}, this is your try # {}".format(player_fname, tries_count)
print(message)
player_guess = input("Please enter number from {}: ".format(player_lucky_list))
if int(player_guess) in player_lucky_list:
print("Congratulations, your lucky number is {} you got it from try # {}".format(player_guess, tries_count))
elif int(player_guess) not in player_lucky_list:
print("Sorry, wrong value, Enter a INTEGER NUMBER!!!!")
else:
print("Try again")
tries_count += 1
player_lucky_guess.append(player_guess)
print(player_lucky_guess)
Related
I'm writing this script for an assignment so I'd appriciate being talked through it rather than simply being handed an answer. Basically I'm trying to convert feet to meters, meters to feet, and provide a sum of the total converted distance in both at the end. Without the [] indexes, It was working perfectly. The new part I've only just added and am struggling with is the [] indexes, and to be honest I'm having a hell of a time groking how they work. Anyways heres the code:
MAX = 256
switch = ""
feet = [0.0] * MAX
meters = [0.0] * MAX
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if (switch == "feet" or switch == "Feet"):
ftm()
elif (switch == "meters" or switch == "Meters"):
mtf()
elif (switch == "quit" or switch == "Quit"):
end()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
feet[sum_feet] = float(input("Enter the number of feet. "))
meters[sum_meters] = feet * metersperfoot
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if (switch2 == "y" or switch2 == "Y"):
print("you converted a total of ", sum(feet), "feet")
print("And", sum(meters), "meters.")
print("Bye!")
exit()
elif (switch2 == "n" or switch2 == "N"):
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()
I did try having sum_feet + 1 and sum_meters + 1 after each result but that hadnt worked either.
You are not using the indexing in a proper way. For instance , look at the comments on your existing code:
def mtf():
try:
# Error 1. You stored all the inputs to index 0, as sum_meters is 0 always and its not incremented
# So, all the inputs are not recorded, only last one gets in index 0
meters[sum_meters] = float(input("Enter the number of meters. "))
# Error 2: You multiplied the whole list against the conversion parameter.
# Instead, you should multiply the value at current index
feet[sum_feet] = meters * feetpermeter
# This will print the whole list. Again use the current index here
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
A fixed version of your function will be like:
def mtf():
try:
# For modifying global variables in a function scope
global sum_meters
global sum_feet
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters[sum_meters] * feetpermeter
print(f"That is {feet[sum_feet]} feet.")
sum_meters += 1
sum_feet += 1
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
This fixes stands true for your other functions as well.
I also thought to give you another piece of advice, that you can use a good object oriented approach for such problems, which makes it simpler to implement. You can learn a lot about that, then you will feel more confident.
As an example, see the below code - which does almost same, but in a more crisp way.
class Converter:
FEET_PER_METER = 3.28084
METERS_PER_FOOT = 0.3048
def __init__(self):
self.feet_store = []
self.meter_store = []
self.curr_index = 0
self.menu_handlers = {
"feet": self.feet_to_meter,
"meters": self.meter_to_feet,
"quit": self.summary
}
def run_selection(self, selected):
#
selected = str.lower(selected)
if selected in self.menu_handlers:
# call the relevant function
return self.menu_handlers.get(selected)()
return False
def meter_to_feet(self):
meters_in = float(input("Enter the number of meters."))
to_feet = meters_in * self.FEET_PER_METER
self.meter_store.append(meters_in)
self.feet_store.append(to_feet)
print(f"In Feet : {to_feet}")
return to_feet
def feet_to_meter(self):
feet_in = float(input("Enter the number of feet."))
to_meters = feet_in * self.METERS_PER_FOOT
self.feet_store.append(feet_in)
self.meter_store.append(to_meters)
print(f"In Meters : {to_meters}")
return to_meters
def summary(self):
confirm = input("Are you sure you want to quit(y/n)?")
if confirm in ["y", "Y"]:
print("you converted a total of ", sum(self.feet_store), "feet")
print("And", sum(self.meter_store), "meters.")
print("Bye!")
exit()
else:
return False
def main():
converter = Converter()
while True:
choice = input("Is your measurement in meters or feet (meters/feet/quit)?")
converter.run_selection(choice)
I hope this gives you better insights.
So theres two problems with what you've tried to do here, in the lines:
meters[sum_meters] = float(input("Enter the number of meters. "))
feet[sum_feet] = meters * feetpermeter
meters * feetpermeter is multiplying an array by a number, you need to do meters[sum_meters] to get the number you want. Secondly as you said, you need to increment sum_meters each time, but because you're inside a function you will need to declare the variable as a global before you change it. Also since sum_meters and sum_feet are always going to be equal, you can just use a single variable to keep track of this:
def mtf():
try:
global index
meters[index] = float(input("Enter the number of meters. "))
feet[index] = meters[index] * feetpermeter
index += 1
print("That is", feet, "feet.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global index
feet[index] = float(input("Enter the number of feet. "))
meters[index] = feet * metersperfoot
index += 1
print("That is", meters, "meters.")
main()
except:
print("Sorry, I didn't quite get that, lets try again.")
ftm()
I would also go a little further and say that the use of lists is unnecessary for this problem, you could simply have two numbers, total_meters and total_feet and add the values as you go. This would take less memory and also remove the arbitrary limit of 256 goes that has been imposed. So I would do:
import sys
MAX = 256
switch = ""
total_feet = 0
total_meters = 0
feetpermeter = 3.28084
metersperfoot = 0.3048
sum_meters = 0
sum_feet = 0
index = 0
def main():
selector()
def selector():
while True:
print("Is your measurement in meters or feet?")
switch = input("Or would you like to quit?")
if switch == "feet" or switch == "Feet":
ftm()
elif switch == "meters" or switch == "Meters":
mtf()
elif switch == "quit" or switch == "Quit":
end()
sys.exit(0)
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
def mtf():
try:
global total_feet
global total_meters
meters = float(input("Enter the number of meters. "))
feet = meters * feetpermeter
total_meters += meters
total_feet += feet
print("That is", feet, "feet.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
mtf()
def ftm():
try:
global total_feet
global total_meters
feet = float(input("Enter the number of feet. "))
meters = feet * metersperfoot
total_meters += meters
total_feet += feet
print("That is", meters, "meters.")
main()
except Exception as e:
print(e)
print("Sorry, I didn't quite get that, lets try again.")
ftm()
def end():
while True:
switch2 = input("Are you sure you want to quit(y/n)?")
if switch2 == "y" or switch2 == "Y":
print("you converted a total of ", total_feet, "feet")
print("And", total_meters, "meters.")
print("Bye!")
exit()
elif switch2 == "n" or switch2 == "N":
print("Ok, let's try that again.")
main()
else:
print("Sorry, that wasn't one of the options.")
print("Lets try that again")
main()
I'm trying to make a lottery program that can output results after a user inputs their numbers. But I want the option to allow the user to also be able to pick "how many weeks they play for", that being, how many times the program outputs results that are randomized. Basically use the numbers they inputted to play multiple games of lottery with the same numbers x amount of times they wish. I want to know how to make my function repeat based on how many times they wish to play.
Here's my incomplete code.
import random
NUMBER_OF_PICKS = 3
MINIMUM_SELECTION = 1
MAXIMUM_SELECTION = 36
MONEY_WON = 10000
OFFSETT = 4
USER = input("Please enter your name:")
print("Hi " + USER + " good luck ")
WEEKS_PLAYED = input("How many weeks do you want to play: ")
def verify(playerNumbers, winningNumbers):
if playerNumbers == winningNumbers:
print("Congratulations! You Win ${}!".format(MONEY_WON))
print("Your numbers: ", playerNumbers, )
print("The winning lottery numbers were: ", winningNumbers)
else:
print("Sorry, you lose...")
print("Your numbers: ", playerNumbers)
print("The winning lottery numbers were: ", winningNumbers)
# 'get_user_nums', gets user numbers and puts into a sorted list for x in WEEKS_PLAYED:
def get_user_nums():
user_nums = []
while len(user_nums) < NUMBER_OF_PICKS:
nums = input("Pick a number {} through {}: ".format(MINIMUM_SELECTION, MAXIMUM_SELECTION))
try:
nums = int(nums)
except:
print("Sorry your input must be an integer!")
continue
if MINIMUM_SELECTION <= nums <= MAXIMUM_SELECTION:
if nums not in user_nums:
user_nums.append(nums)
else:
print("Sorry, you have already inputted that number")
else:
print("Sorry, Your number was not in range")
return sorted(user_nums)
# 'get_winning_nums', creates a sorted list with random nums ranging from 0-9 with a range of 3 values
def get_winning_nums():
return sorted(random.sample(range(MINIMUM_SELECTION, MAXIMUM_SELECTION), NUMBER_OF_PICKS))
# 'menu', creates the main menu to choose game or exit program
def play_pick_n():
user_nums = get_user_nums()
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
# 'main', calls the other functions
def main():
# lottery_menu()
while True:
choice = input("\nPlay?: Yes or No: ")
if choice == 'Yes':
string = "\n[Play Pick {}]".format(NUMBER_OF_PICKS) + "selected!"
dotted = '\n' + len(string) * "-"
print(dotted, string, dotted)
play_pick_n()
break
elif choice == 'No':
print("Thanks for playing!\n")
break
print("Sorry, that is not a valid input. \nPlease enter either Yes or No")
if __name__ == '__main__':
main()
Thanks for any help.
if you ant to use the same numbers for all weeks, use:
user_nums = get_user_nums()
for week in range(0, WEEKS_PLAYED):
winning_nums = get_winning_nums()
verify(user_nums, winning_nums)
You might want to move the question for the number of weeks inside your play_pick_n function, so the player can decide per bunch of numbers who long they should run.
I'm making a simple game that shows up "What number do you like" and if u write a number(for example "77") it should show up an EXCEPT but it doesn't
why?
your_name = input("What's your name: ")
this_year = 2019
your_age = int(input("How old are you: "))
year_born = this_year - your_age
print("Hello",your_name,".You are",your_age,"years old","\n\n")
year_when_you_were_born = print("That means that you were
born",year_born)
hundred_year = year_born + 100
print("And that means that you are gonna be 100 years old at the year
of",hundred_year)
number = int(input("What number do you like: "))
try:
question = str(input("Do you wanna print your name that many times:
"))
except ValueError:
print("I don't get it,type words not numbers")
else:
if question == "yes":
word = your_name * question
print(word)
number = int(input("What number do you like: ")) takes the input and converts it to an int. So 77 is fine. However, letters can not be converted to a int, so that will throw a ValueError. For that the line needs to be inside the try block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
Note that question = str(input("Do you wanna print your name that many times: ")) will not throw a ValueError, because both letters and numbers can be converted to a string. So you don't have to put it in the 'try'-block, it is better placed in the 'else' block:
try:
number = int(input("What number do you like: "))
except ValueError:
print("I don't get it,type numbers not words")
else:
question = str(input("Do you wanna print your name that many times: "))
if question == "yes":
word = your_name * question
print(word)
So here I am again, clueless as always. I'm somewhat of a novice, so this is probably biting off more than I can chew, but whatever.
The point of this program is to provide an output based off of input values from the user. It's meant to implement an input trap should the user not enter the correct input.
I'm trying to make it so the input of a letter or a non-integer value causes the message "Please enter only whole numbers." It works for the float points, but not letters. I should note that the "Enter a number between 0 and 10" message is working fine.
Also, the loop is supposed to close when the user inputs 'done', but that only results in a "ValueError: could not convert string to float: 'done'".
I haven't written this in While True format as it's more comfortable for me to stick away from that method of writing while loops.
setCount = 1
allScore = 0
done = False
while not done:
strScore = float (input ( "Enter Set#" + str(hwCount) + " score: "))
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
setCount = setCount + 1
elif ( setScore == int (strScore) and( setScore < 0 or setScore > 10)):
print ("Please enter a number between 0 and 10.")
elif setScore != "done":
print ("Please enter only whole numbers.")
else:
done = True
You immediately convert the input string to a float on the same line where you read it:
strScore = float (input ( "Enter HW#" + str(hwCount) + " score: "))
In order to accept "done" as an input, you need to keep it as a string, and convert it to float (or int) after you have done all input validation.
drop float() and strScore will be a string. Then check if it equals "done". Finally, convert it to an integer inside a try block
print ( "Enter the homework scores one at a time. Type \"done\" when finished." )
hwCount = 1
totalScore = 0
while True:
strScore = input ( "Enter HW#" + str(hwCount) + " score: ")
if strScore == "done":
break
try:
intScore = int(strScore)
except ValueError:
print ("Please enter only whole numbers.")
continue
if (intScore >=0 and intScore <=10):
totalScore += intScore
hwCount += 1
else:
print ("Please enter a number between 0 and 10.")
You should really clean your code up, all those extra spaces hurts readability. I'd suggest using PyLint (pip install pylint, pylint file.py).
I'm not going to refactor your code too much, but you need to check for 'done' before converting to a float. And you'll want to catch ValueErrors incase somebody enters an invalid answer and handle it gracefully.
print("Enter the homework scores one at a time. Type \"done\" when finished. Ctrl+c to quit at any time.")
hwCount = 1
totalScore = 0
try:
while True:
strScore = input("Enter HW#" + str(hwCount) + " score: ")
if strScore == 'done':
break #done
else:
try:
strScore = float(strScore)
except ValueError:
print('Invalid input: must be a numerical score or "done"')
continue
if (strScore == int (strScore) and strScore >=0 and strScore <=10):
totalScore = totalScore + (strScore)
hwCount = hwCount + 1
elif ( strScore == int (strScore) and( strScore < 0 or strScore > 10)):
print ("Please enter a number between 0 and 10.")
elif strScore != "done":
print ("Please enter only whole numbers.")
except KeyboardInterrupt:
pass #done
Heres a more complete version of your program, for reference. It's how I would have refactored it.
#!/usr/bin/env python3
def findmode(lst):
bucket = dict.fromkeys(lst, 0)
for item in lst:
bucket[item] += 1
return max((k for k in bucket), key=lambda x: bucket[x])
print("Enter the homework scores one at a time.")
print("Type 'done' when finished or ctrl+c to quit.")
scores = []
try:
while True:
strScore = input("Enter score: ")
if strScore == 'done':
break #done
else:
try:
strScore = int(strScore)
except ValueError:
print('Invalid input: must be a score or "done"')
continue
if (0 <= strScore <= 10):
scores.append(strScore)
else:
print("Please enter a valid score between 0 and 10.")
except KeyboardInterrupt:
pass # user wants to quit, ctrl+c
finally:
print("Total scores graded: {}".format(len(scores)))
print("Highest score: {}".format(max(scores)))
print("Lowest score: {}".format(min(scores)))
print("Mean score: {}".format(sum(scores)/len(scores)))
print("Mode score: {}".format(findmode(scores)))
#My code should take a random between 1 and 100 and let you guess it.
#This part works, but I want to add the posibility to reveal the number and then is when I get the error "could not convert string to float"
def reveal(guess):
return secret_number
import random
secret_number = random.random()*100
guess = float(input("Take a guess: ")) #This is the input
while secret_number != guess :
if guess < secret_number:
print("Higher...")
elif guess > secret_number:
print("Lower...")
guess = float(input("Take a guess: ")) #This input is here in order for the program not to print Higher or Lower without ever stopping
else:
print("\nYou guessed it! The number was " ,secret_number)
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", secret_number)
input("\n\n Press the enter key to exit")
Any help would be a great service. Also I am only programming for just a few weeks so sorry if my code looks wrong.
If you want to use float number to compare, the game may be endless because a float number has many fractional digits. Use int number.
#!/usr/bin/env python3.3
# coding: utf-8
import random
def guess_number():
try:
guess = int(input("Take a guess:"))
except ValueError:
print("Sorry, you should input a number")
guess = -1
return guess
if __name__ == '__main__':
secret_number = int(random.random() * 100)
while True:
guess = guess_number()
if guess == -1:
continue
elif guess < secret_number:
print("Lower...")
elif guess > secret_number:
print("Higher...")
else:
print("\nYou got it! The number was ", secret_number)
input("\n\nPress any key to exit.")
break # or 'import sys; sys.exit(0)'
import random
LOWEST = 1
HIGHEST = 100
def main():
print('Guess the secret number between {} and {}!'.format(LOWEST, HIGHEST))
secret = random.randint(LOWEST, HIGHEST)
tries = 0
while True:
guess = raw_input('Your guess: ').strip().lower()
if guess.isdigit():
tries += 1
guess = int(guess)
if guess < secret:
print('Higher!')
elif guess > secret:
print('Lower!')
else:
print('You got it in {} tries!'.format(tries))
break
elif guess == "reveal":
print('The secret number was {}'.format(secret))
break
else:
print('Please enter a number between {} and {}'.format(LOWEST, HIGHEST))
if __name__=="__main__":
main()
Use random.range instead of random.random.
secret_number = random.range(1,100,1)
And ...,str(secret_number)
...
else:
print("\nYou guessed it! The number was " ,str(secret_number))
if guess == "reveal": #This is where I "tried" to make the reveal thingy.
print ("Number was", str(secret_number))
...
That way you will be concatenating a string with a string. Also, you can keep random.random and only make the second change.
EDIT:
Another thing to do is to use raw_input instead of input. Then use try.
guess = raw_input("Take a guess: ")
try:
guess = float(guess)
except:
pass
This will try to convert guess into a float, and it that fails, then it will remain a string. That should solve your problem.
You could isolate concerns by defining a function that asks user for input until a float is provided:
def input_float(prompt):
while True:
try:
return float(input(prompt))
except ValueError:
print("You should input a float number. Try again.")
Then you could use it in your script:
guess = input_float("Take a guess: ")
If you want to accept 'reveal' as an input in addition to a float number:
def input_float_or_command(prompt, command='reveal'):
while True:
s = input(prompt)
if s == command:
return s
try:
return float(s)
except ValueError:
print("You should input a float number or %r. Try again." % command)