I’m a beginner in python, and am trying to code a program to tell people what to bring in rainy/windy weather.
But when I test the code, I get as far as rain==yes and wind==no before the program stops. Is this a problem with the program or with something else?
rain = str(input('Is it raining? yes/no '))
print()
rain = rain.lower()
while rain != 'yes':
if rain != 'no':
rain = str(input('Is it raining? yes/no '))
rain = rain.lower()
print()
wind = str(input('Is it windy? yes/no '))
print()
wind = wind.lower()
while wind != 'yes':
if wind != 'no':
wind = str(input('Is it windy? yes/no '))
wind = wind.lower()
print()
if rain == 'yes' and wind == 'yes':
print('Wear a raincoat. ')
elif rain == 'yes':
print('Bring an umbrella. ')
elif wind == 'yes':
print('Wear a jersey. ')
else:
print('Wear a shirt. ')
print(':)')
while wind != 'yes':
if wind != 'no':
wind = str(input('Is it windy? yes/no '))
wind = wind.lower()
print()
This loop is infinite if wind is "no".
while wind != 'yes' is true, so the loop keeps running, but wind != 'no' is not true, so the user is not allowed to enter a different answer. The loop runs forever.
This is a better way of prompting the user for specific answers:
while True:
wind = input('Is it windy? yes/no ').lower()
if wind in ['yes', 'no']:
break
else:
print('That is not a yes/no answer. Please try again')
Related
I am learning how to make a text typed game in python. I could not get it to work. eventhough there is a water in my list (bag) it would still end the game eventhough i have it. Please help me
...
bag = [ ]
sword = ("sword")
water_bucket = ("water")
dead = False
ready = input("are you ready? ")
while dead == False:
print("this is whats inside your bag ")
print(bag)
if ready == "yes":
print("let's start our journey ")
print(
"It was a beautiful morning, you woke up in a dungeon, your quest is to find a dragon and slay his head off")
while dead == False:
if dead == True:
break
else:
first = input("Choose a path front/back/left/right")
if first == "front":
if bag == "water":
print(" You got safe because of the water bucket")
else:
dead = True
print(" You died in a hot lava")
elif first == "back":
ask2 = input("There is a sword, do you want to take it?")
if ask2 == "yes":
bag.append(sword)
print("You got a sword")
elif ask2 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
elif first == "left":
if bag == "sword":
print("You fought a dragon and win")
elif bag != "sword":
print("You fought a dragon but lost because you do not have a weapon")
dead = True
elif first == "right":
ask3 = input("Water Buckets! might be helpful, take it? ")
if ask3 == "yes":
bag.append(water_bucket)
print("You got a water bucket")
print(bag)
elif ask3 == "no":
print("you did not take it and went back to start")
else:
print("please answer with yes or no")
else:
print("not a path")
else:
print("See you next time, A journey awaits")
...
It is a text based im learning right now
from random import randint
play = "yes"
while play == "yes":
choice = int(input("Would you like to play yourself(1) or let machine(2) play? press '1' or '2': "))
if choice == 1:
print("You chose to play yourself")
num = randint(1,9999)
counter = 0
while True:
num_guess = int(input("Guess the number: "))
if num_guess == 0:
print("Player has left the game")
break
else:
if num_guess > num:
print("Your guess is too high")
elif num_guess < num:
print("Your guess is too low")
elif num_guess == num:
print("Yay,you found it")
print("It took you " + str(counter) + " tries to guess the number")
break
counter += 1
elif choice == 2:
print("You chose to let the machine play")
your_num = int(input("Enter your number: "))
lowest = 1
highest = 9999
counter = 0
machine_guess = randint(1,9999)
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
else:
while True:
print("My guess is ",machine_guess)
is_it_right = input("Is it too small(<) or too big(>) or machine found(=) the number?: ")
if is_it_right == ">":
if machine_guess > your_num:
highest = machine_guess
counter += 1
else:
print("!!!Don't cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" < " + str(your_number) + ",so you should have written '<' instead of what you wrote.Continue ")
elif is_it_right == "<":
if machine_guess < your_num:
lowest = machine_guess + 1
counter += 1
else:
print("!!!Don't Cheat!!!")
your_number = input("What was your number?: ")
print(str(machine_guess) +" > " + str(your_number) + ",so you should have written '>' instead of what you wrote.Continue ")
elif is_it_right == "=":
if machine_guess == your_num:
if your_num == machine_guess:
counter += 1
print("Yayy,I found it")
print("It took me " + str(counter) + " tries to guess the number")
else:
print("You cheated and changed the number during the game.Please play fairly")
your_number = input("What was your number?: ")
print(str(machine_guess) +" = " + str(your_number) + ",so you should have written '=' instead of what you wrote ")
break
elif is_it_right == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
machine_guess = (lowest+highest)//2
elif choice == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player has left the game")
break
request = input("Do you want to play again? Answer with 'yes' or 'no': ")
if request == "no":
print("You quitted the game")
break
elif request == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
break
This is my code for game "guess my number",here the complicated ones is me trying to make the program prevent user from cheating (It is a university task,due in 3 hours)
So choice 1 is when user decides to play game "guess my number" and 2nd choice when computer plays the game.The problem that I have is :
I can't make the code make the user input the number in range of(1,9999) and THEN continue the process
As you see I have a lot of "if ... == 0" --> .In task it is said that whenever(any of inputs) user types 0 the game has to stop.The others work well but the one in choice 2 the first if is not working
If somebody has solution for this,please help.I would be grateful
Whenever you want to ask a question repeatedly until the correct input is given, use a while loop
print("You chose to let the machine play")
your_num = -1
while your_num < 0 or your_num > 9999:
your_num = int(input("Enter your number [0..9999]: "))
1- To force the user to input a number in the range of (1,9999), you must have an a condition like:
while True:
try:
num_guess= int(input("Enter your number in range 1-9999: "))
except ValueError:
print("That's not a number!")
else:
if 1 <= num_guess <= 9999:
break
else:
print("Out of range. Try again")
Edit: I didn't understand which input you wanted to keep in the range of 1-9999. I gave answer with num_guess but you can use it with your_num, too.
2- Add play = "no" line to the condition when the user inputs 0:
if your_num == 0:
you_sure = input("Are you sure you want to leave the game? yes or no: ")
if you_sure == "yes":
print("Player left the game")
play = "no"
break
I have written some code where I have to write a program that asks the user for a row of pancakes with them either being letter A or B where the code has to tell the user how many flips it takes to make all the pancakes A where the user has to input how many pancakes can be flipped at once all in a row. If the pancakes can't be flipped and be all letter As the code has to output This couldn't be done. Would you like to try again?.
The code currently outputs the following:
Enter the row and the side of the pancakes A/B): BBBB
How many pancakes can flipped at one time? 2
It took 0 flips.
Would you like to run this program again?
where it should output the following:
Enter the row and the side of the pancakes (A/B): BBBB
How many pancakes can flipped at one time? 2
And it shouldn't tell the user if they want to play again as the pancakes haven't been fully flipped to A's.
My code is below:
i = True
flips = 0
while i == True:
pancakes = list(input('Enter the row and the side of the pancakes (A/B): '))
flipper = int(input('How many pancakes can be flipped at one time? '))
i = False
if 'O' in pancakes:
flips = flips + 1
for x in range(flipper):
if pancakes[x] == 'A':
pancakes[x] = 'B'
pancakes = (''.join(pancakes))
if flips == 1:
print('It took 1 flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
if flips == 0:
print('It took', flips, 'flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
if flips > 1:
print('It took', flips, 'flip.')
play = input("Would you like to run this program again? ")
if play == 'Yes' or play == 'yes' or play == 'Y' or play == 'y':
i = True
else:
quit()
An issue with the code is it currently doesn't output the correct number of flips correctly.
Thanks.
Here's my code to solve this problem...
while True:
pancakes = input('Enter the row and the side of the pancakes (A/B): ')
flipper = int(input('How many pancakes can be flipped at one time? '))
result, possible = 0, True
for row in pancakes.split('B'):
cnt, rem = divmod(len(row), flipper)
if rem != 0:
possible = False
break
result += cnt
if possible:
print('It took %d flips.' % result)
resp = input('Would you like to run this program again? ')
else:
resp = input("This couldn't be done. Would you like to try again? ")
if resp.lower() not in ['yes', 'y']:
break
I am still working with the same code as before (I will post lower), I just need help converting the first 10-15 lines to pseudocode so I have an idea on how to do it myself.
Code works, indents are weird because I quickly added spaces to put into code.
Apologies for the non professional code, I am still new to python!
Also, please don't do the whole of the pseudocode, just upto the end of the first while true loop so I can figure it out and do the rest myself. thank you :)
#Taran Gill - S1714318
#Please Open in Python and not IDLE
#Code for car hire
import sys
import pc
from datetime import date
import time
import os
def restart_program():
python = sys.executable
os.execl(python, python, * sys.argv)
#Opening Statement
while True:
opening = input("Welcome, would you like to hire a car? Please state
'Yes' or 'No'\n")
if opening.lower() == 'yes':
print ("Thats good! First we need to take some details")
break
if opening.lower() == 'no':
print ("Hope you have a good day!")
print ("Exiting...")
time.sleep(1)
sys.exit()
break
else:
print ("Invalid answer")
print ("Restarting...")
time.sleep(1)
restart_program()
continue
#Asks user for First Name
correct_name1 = False
while correct_name1 == False:
firstName = input("Please enter your First Name\n")
if (firstName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your First Name is", firstName.title())
while True:
correct1 = input("Is this correct?\n")
if correct1.lower() == "yes":
correct_name1 = True
break
if correct1.lower() == "no":
correct_name1 = False
break
else:
print ("Please say yes or no")
#Asks user for Last Name
correct_name2 = False
while correct_name2 == False:
lastName = input("Please enter your Last Name\n")
if (lastName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your Last Name is", lastName.title())
while True:
correct2 = input("Is this correct?\n")
if correct2.lower() == "yes":
correct_name2 = True
break
if correct2.lower() == "no":
correct_name2 = False
break
else:
print ("Please say yes or no")
#Asks user for House Number
correct_name3 = False
while correct_name3 == False:
try:
houseNumber = int(input("Please enter your House Number\n"))
if houseNumber < 1 or houseNumber > 2500:
print ("Please put a number in between 1 and 2500")
continue
print ("Your House Number is", houseNumber)
except ValueError:
print ("Invalid Format")
continue
while True:
correct3 = input("Is this correct?\n")
if correct3.lower() == "yes":
correct_name3 = True
break
if correct3.lower() == "no":
correct_name3 = False
break
else:
print ("Please say yes or no")
#Asks user for Street Name
correct_name4 = False
while correct_name4 == False:
try:
streetName = input("Please enter your Street Name\n")
if (len(streetName) <=4 or streetName.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print ("Your Street Name is", streetName.title())
except ValueError:
print ("Invalid Format")
continue
while True:
correct4 = input("Is this correct?\n")
if correct4.lower() == "yes":
correct_name4 = True
break
if correct4.lower() == "no":
correct_name4 = False
break
else:
print ("Please say yes or no")
#Asks user for City
correct_name5 = False
while correct_name5 == False:
try:
city = input("Please enter your City\n")
if (len(city) <3 or city.replace (' ','').isalpha()==False):
print("Not Acceptable")
continue
print("Your City is",city.title())
except ValueError:
print ("Invalid Format")
continue
while True:
correct5 = input("Is this correct?\n")
if correct5.lower() == "yes":
correct_name5 = True
break
if correct5.lower() == "no":
correct_name5 = False
break
else:
print ("Please say yes or no")
#Asks user for Post Code
correct_name6 = False
while correct_name6 == False:
postcode = input ("Please enter your Post Code\n")
try:
checkpc = pc.parse_uk_postcode(postcode)
except ValueError:
print ("Invalid Post Code, Please try again")
continue
else:
print ("Your Post Code is", postcode.upper())
while True:
correct6 = input("Is this correct?\n")
if correct6.lower() == "yes":
correct_name6 = True
break
if correct6.lower() == "no":
correct_name6 = False
break
else:
print ("Please say yes or no")
#Asks user for Date Of Hire
correct_name7 = False
while correct_name7 == False:
dateOfHire = input("Please enter the date of start of hire in the format - dd/mm/yyyy\n")
try:
valid_date = time.strptime(dateOfHire, '%d/%m/%Y')
except ValueError:
print("Invalid format, please try again")
continue
else:
print("The date of start of hire is", dateOfHire)
while True:
correct7 = input("Is this correct?\n")
if correct7.lower() == "yes":
correct_name7 = True
break
if correct7.lower() == "no":
correct_name7 = False
break
else:
print ("Please say yes or no")
#Asks the user for the Amount of Days they would like to hire the car for
correct_name8 = False
while correct_name8 == False:
try:
amountOfDays = int(input("Please enter the amount of days you would like to hire for\n"))
if amountOfDays <1 or amountOfDays > 100:
print ("Please enter a sensible number!")
continue
except ValueError:
print ("Invalid Format")
continue
else:
print ("The amount of days you would like to hire the vehicle is", amountOfDays, "days")
while True:
correct8 = input("Is this correct?\n")
if correct8.lower() == "yes":
correct_name8 = True
break
if correct8.lower() == "no":
correct_name8 = False
break
else:
print ("Please say yes or no")
#Tells the user what the prices are for each vehicle
print ("""
Estate costs 50 pounds a day
Saloon costs 60 pounds a day
Sports costs 70 pounds a day
There will be an additional 10 pound charge for each day
if the estimated miles is above 100 miles
""")
#Asks the user what vehicle they want
correct_name9 = False
while correct_name9 == False:
car = input("Would you like an Estate, Saloon or Sports?\n")
if car.lower() in ["estate", "saloon", "sports"]:
print("The car you have chosen is", car.title())
else:
print ("Invalid car, please try again")
continue
while True:
correct9 = input("Is this correct?\n")
if correct9.lower() == "yes":
correct_name9 = True
break
if correct9.lower() == "no":
correct_name9 = False
break
else:
print ("Please say yes or no")
#Asks the user how many miles they think they will do in a day
correct_name10 = False
while correct_name10 == False:
try:
estMiles = int(input("How many miles do you think you will do in a day?\n"))
if estMiles < 1 or estMiles > 1500:
print ("Please enter a sensible number!")
continue
except ValueError:
print ("Invalid Format")
continue
else:
print ("The amount of miles you think you will do in a day is", estMiles)
while True:
correct10 = input("Is this correct?\n")
if correct10.lower() == "yes":
correct_name10 = True
break
if correct10.lower() == "no":
correct_name10 = False
break
else:
print ("Please say yes or no")
#Calculations for each vehicle
if car == "estate":
calculation = 50 * amountOfDays
elif car == "saloon":
calculation = 60 * amountOfDays
elif car == "sports":
calculation = 70 * amountOfDays
if estMiles > 100:
calculation = calculation + (10*amountOfDays)
print ("It will cost you", calculation, "pounds.")
#Lets the user decide if they want to input another vehicle or exit
while True:
answer = input("Type restart to start over, type exit to exit program\n")
if answer.lower() == 'restart':
print ("Restarting...")
time.sleep(1)
restart_program()
elif answer.lower() == 'exit':
print ("Exiting...")
time.sleep(1)
sys.exit
break
else:
print ("Invalid Format, Please try again")
continue
In Pseudo code? I'd try and read up a bit on Python, its really not hard to understand what is going on. Basically:
import imports various python modules needed in this code.
def restart_program(): defines a function which you can run later in the code with restart_program()
While True: means do something forever, or until break
.lower() is the lowercase version of the string
If you're using this code as a basis, it is not particularly pythonic, it uses a style like an old linear basic program, with an overuse of While True loops. There is definitely much shorter and more readable ways of writing the same program.
EDIT: Thank you, the question has been answered!
The program works properly, asides from the fact that it does not loop to allow the user to play a new game. ie, after entering too many, too few, or the perfect amount of change, the program asks "Try again (y/n)?: " as it should. But I can't find out why it doesn't loop... And when it loops, it doesn't need to include the large paragraph about explaining the game. Just the line about "Enter coins that add up to "+str(number)+" cents, one per line." Any tips?
#Setup
import random
playagain = "y"
#Main Loop
if (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
By using break, you're completely leaving the while loop and never checking the playagain condition. If you want to see if the user wants to play again put the 'playagain' check in another while loop.
#Setup
import random
playagain = "y"
#Main Loop
while (playagain == "y"):
number = random.randint(1,99) #Generation of how many cents
total = 0 #Running sum of guessed coins.
print("The purpose of this exercise is to enter a number of coin values")
print("that add up to a displayed target value. \n")
print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
print("Hit return after the last entered coin value.\n")
print("Enter coins that add up to "+str(number)+" cents, one per line.\n")
while (True):
if (total == 0):
word = "first"
else:
word = "next"
guess = str(input("Enter "+str(word)+" number: ")) #Records coin value
#Entry Validation
if (guess == ""): #When user is done guessing.
if (total < number):
print("Sorry - you only entered "+str(total)+" cents.\n")
break
elif (total > number):
print("Sorry - total amount exceeds "+str(number)+" cents.\n")
break
else:
print("Correct!")
break
elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25):
total = total + int(guess)
else:
print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.
You set playagain to y/n, but the code doesn't go back around to the beginning if playagain is equal to 'y'. Try making if playagain == "y" into while playagain == "y". That way, it goes through the first time and keeps going back to the beginning if playagain is still set to "y".
Also, indent your last line (playagain = str(....)) so it's part of the while playagain == "y" loop. If it's not, then the code will be stuck in an infinite loop because playagain isn't being changed inside the while loop.
Indent the last line as far as the while True line. And change the if (playagain == "y"): to a
while (playagain == "y"):
Your "Main loop" is not a loop, it is just an if statement. Also it is better to use raw_input because input will eval your input. Try something along the lines of this:
playagain = 'y'
#Main loop
while playagain == 'y':
print "do gamelogic here..."
playagain = raw_input("Try again (y/n)?: ")
Inside your gamelogic, you could use a boolean to check wether you need to print the game explanation:
show_explanation = True
while playagain == 'y':
if show_explanation:
print "how to play is only shown once..."
show_explanation = False
print "Always do this part of the code"
...
playagain = raw_input("Try again (y/n)?: ")