I can't figure out why this is getting an error that states that 'Yes' is not specified. What does that mean? Why won't this work? The fuelEconomy input statement works and the function works as well. For some reason I can't get the while statement to accept the 'Yes' input to execute the function.
# This program is to calculate fueld economy
def main ():
fuelEconomy = input ("Do you want to calculate your fuel economy? ")
print (fuelEconomy)
while fuelEconomy == Yes:
Economy ()
fuelEconomy = input ("Do you want to calculate another?")
#This function is the input and calculation for the program
def Economy ():
mileage = int (input ("Input mileage "))
gallons = int (input ("Input gallons used "))
economy = mileage/gallons
print ('Your economy is', economy, 'MPG')
main ()
It needs to be a string.
while fuelEconomy == 'Yes':
However your code still won't actually work, because that is now an infinite loop as the value of fuelEconomy cannot change within the loop. You probably meant for the next line to also be inside the loop.
Related
I'm trying to create a game that is kind of along the lines of the game mastermind.
I have a section where the user has to either guess the number or type "exit" to stop the game. How do i make it so that the code allows both an integer and string input?
The code is:
PlayerNum = int(input("Type your number in here:"))
if PlayerNum == "exit":
print "The number was:",RandNum1,RandNum2,RandNum3,RandNum4
print "Thanks for playing!
exit()
If anyone could help that would be great.
Thanks. :D
you can use isdigit() function to check whether input is int or string.
Let user has input "32" then "32".isdigit() will return True but if user has input "exit" then "exit".isdigit() will return False.
player_input = input("enter the number")
if player_input.isdigit():
# Do stuff for integer
else:
# Do stuff for string
PlayerNum = input("Type your number in here:")
Well You can remove the int so that it takes both integet and string as input
Integer and String classifications are specific to Python (they are functions). When the user types in their response, that would be interpreted by the system as stdin (standard input).
Once the stdin is entered by the user and allocated under the PlayerNum variable, you are free to convert it to an int/str/bytes as you please.
I am new to python, My first project that I am still working on is a kind of a game in which you throw a dice and stuff like that, so it's pretty much a dice simulator.
Before the user actually starts the game I have made the program ask them questions like; "Type 'start' on keyboard to begin the game, and this I am doing with raw_input.
Here's the problem:- I want to make only the input 'start' possible to write, if something else is written, the game doesn't start. I hope you understand me
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name);
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
You just need if_else
from random import randint
min = 0
max = 6
start=raw_input("Welcome to the dice game, type 'start' on your keyboard to start the game:")
if start=='start':
print("------------------------------------------------------------------------------------------")
name=raw_input("Okey, let's go! Before we can start you must type your name here: ")
print ("Hey %s, I guess we're ready to play!!" % name)
print("The whole game concept is basically to throw a dice and get as high number as possible!")
print("--------------------------------------------------------------------------------------------")
ja=raw_input("Would you like to throw the dice? Type 'yes' if so:")
print "Your number is:", randint(min, max)
print ("Thank you for playing!")
else:
print("XYZ message")
I am new to programming and trying to get a head start on my class next semester. I am trying to show the total cost and then print it. Where am I going wrong?
print('Would you like a rental car?')
rental = (input('Yes or No? '))
if rental.lower() == yes:
car = float(input('Dollar Amount?'))
else:
print('Thank You!')
print('Would you need a flight?')
flight = (input('Yes or No '))
if flight.lower() == yes:
plane = float(input('Dollar Amount? '))
else:
print('Thank You!')
print('Would need a hotel?')
hotel = (input('Yes or No? '))
if hotel.lower() == yes:
room = float(input('Dollar Amount? '))
sum = travel (room + plane + car)
print('This is the total amount that it may cost you, ' + travel '!')
Problem 1
Fix your indentation. Python uses indentation to define what block code is executed in (i.e. in an if statement, or after it). Here's what you should do:
Select all (cmd / ctrl + a), and then keep pressing (cmd / ctrl + [) to de-indent. Do this until nothing is indented.
On any line you want in an if / else statement, press the TAB key at the start of that line.
Problem 2
The input function (which gets user input) returns a string. You then try to compare this to an undefined variable yes. Replace the yes in your if statements with "yes" or 'yes' to ensure you are comparing two strings.
Problem 3
Remember to end all of your strings, with a closing quotation mark. You forgot one printing "Thank You" after the "Would you need a flight?" question.
Replace: print('Thank you.) with print('Thank you.')
Problem 4
Second-to-last line, you define sum, which is never used. Then, you try to use the undefined travel function to add up your three variables. This line of code, in general, makes no sense. I am assuming that you meant this:
travel = (room + plane + car)
Problem 5
You can't concat floats / ints to strings.
This should be the final line:
print('This is the total amout that it is may cost you, '+str(travel)+'!')
Also, you forgot the concat operator (+) when appending the exclamation mark.
Final Code:
Here is the working version of your code:
print('Would you like a rental car?')
rental = (input('Yes or No? '))
if rental.lower() == 'yes':
car = float(input('Dollar Amount?'))
else:
print('Thank You!')
print('Would you need a flight?')
flight = (input('Yes or No '))
if flight.lower() == 'yes':
plane = float(input('Dollar Amount? '))
else:
print('Thank You!')
print('Would need a hotel?')
hotel = (input('Yes or No? '))
if hotel.lower() == 'yes':
room = float(input('Dollar Amount? '))
travel = (room + plane + car)
print('This is the total amout that it is may cost you, ' + str(travel)+ '!')
Recommendations:
This works, but it could be better. Here are a few recommendations, which will help you not only with this project, but also with further ones:
You can combine your print and input functions together, since input basically prints and then waits for input. To format it like you have now, simply include a newline character, \n. For example, instead of
print('Would you like a rental car?')
rental = (input('Yes or No? '))
you could do
rental = input("Would you like a rental car?\nYes or No?")
These lines could actually be simplified further. You don't need to define the variable rental, but instead you can just use its' output directly in the if statement, i.e.
if input("Would you like a rental care?\nYes or No?").lower() == "yes" :
...
Learn to use try / catch statements to catch errors. When entering the amount for a travel expense, the user has to type a number. But what if they type a string instead? Your program would crash. Learn how to use try / catch statements to prevent this from happening (https://docs.python.org/3/tutorial/errors.html)
There's not really much apart from that. These were all just beginners mistakes, and soon you'll be writing good code that works well :D
I was also impressed to see how you handled the "yes" / "no" user input by converting the answers to lower case and then checking them, which is something that a lot of people of your skill level neglect to do.
I am a novice python code writer and i am starting small with a fuel conversion program. The program asks for your name and then converts a miles per gallon rate or a kilometers per litre rate. Currently, the program runs fine until it gets to the convert to MPG line. then once you press y, it does nothing. funny thing is, no syntax error has been returned. please help as i cannot find anything on it :(
import time
y = 'y', 'yes', 'yep', 'yea', 'ye'
n = 'n', 'no', 'nup', 'nay'
name = str(input("Hey, User, whats your name? "))
time.sleep(1.5)
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
time.sleep(1.5)
str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if y is True:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = (galls/miles)
print("The MPG Rate is: ", int(mpgc))
time.sleep(2)
print("test print")
if y is (not True):
input(str("Would you like to convert KPL instead? (y/n): "))
time.sleep(1.5)
if y is True:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = ( litres / kilometers )
print("The KPL Rate is: ", int(kplc))
time.sleep(3)
exit()
if y is not True:
print("No worries")
time.sleep(1.5)
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
time.sleep(1.5)
print("Have a good day!")
time.sleep(1.5)
exit()
else :
print("Sorry, invalid response. Try again")
exit()
elif not y:
print("Please use y/n to answer" )
time.sleep(2)
elif not n:
print("Please use y/n to answer" )
time.sleep(2)
sorry if you think that is bad but i just started python and i need some help :)
Severely trimmed down and indentation fixed (I think....)
if y is True and similarly if y is not True make no sense here.
Also, speaking of is.. is and == may be work as equivalent expressions sometimes for checking for "equality", but not necessarily. == checks for equality whereas is checks for object identity. You should use == for checking for equality between two objects. Except for None in which case it's generally preferred to use is instead of == for this.
You're converting to str in a bunch of places unnecessarily. They're already strings.
In your mpg conversion you already have a floating point number (possibly an int). There's no need to convert to an int here. Suppose mpg is < 1. Then int casting will make this return zero
Your math is also backwards. miles per gallon. Similarly, kilometers per gallon.
name = input("Hey, User, whats your name? ")
print("Alright", name, "Welcome the the *gravynet* Fuel Efficiency Converter!")
mpg = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if mpg in y:
miles = int(input("How far did you travel (in miles): "))
galls = int(input("How much fuel did you consume (in gallons): "))
mpgc = miles / galls
print("The MPG Rate is: ", mpgc)
else:
kpl = input("Would you like to convert KPL instead? (y/n): ")
if kpl in y:
kilometers = int(input("How far did you travel (in kilometers): "))
litres = int(input("How much fuel did you consume (in litres): "))
kplc = kilometers / litres
print("The KPL Rate is: ", kplc)
else:
print("No worries")
print("Thanks", name, "for using *gravynet* Fuel Efficiency Coverter")
print("Have a good day!")
The is keyword in python checks if two variables point to the same location in memory. y will never point to the same memory location as the singleton True because it's value is a string. I suspect what you mean to do is something like
inp = str(input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): "))
if inp in y:
...
You cannot directly take y as pressed from the keyboard, you have to take it as an input(Pressing enter would be required), store it, check if it satisfies the conditions, then apply the logic.
I see you tried to define y and n as a tuple (deliberately or not), In that case I assume you also want to take those other words as yes or or too.
In that case you can apply this logic;
inp = input("Would you like to convert the fuel efficiency of your motor vehcile? (Miles Per Gallon) (y/n): ")
if inp in y: # Check if inp corresponds any of the words defined in y
# Things to do if `yes` or anything similar entered.
Some notes:
You don't need to use str() after you take input if you are using
Python3 (Which seems you are). Because input() returns string.
In somewhere you did something like this:
input(str("Would you like to convert KPL instead? (y/n): "))
Which is even more reduntant because the value you entered is already
a string.
You also didn't assign some inputs to any variable throughout the
code. You should assign them If you are to use them later.
Please take care of these issues.
I'm trying to write a program to calculate densities, and I have tried to create a while loop the prevents the user from entering nothing or a non-number for the volume.
But when I run the program the it just loops "You have to type a value" forever. I've tried the same code in a for loop and it does work after inputing 2 numbers.
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while Volume == ("") or type(Volume) != int:
print("You have to type a value")
Volume = input()
return float(Volume)
This solution is written assuming you are using Python 3. The problem in your code is that you are assuming that if you type in a number, the input method will return a type int. This is incorrect. You will always get a string back from your input.
Furthermore, if you try to cast int around your input to force an int, your code will raise if you enter a string, with:
ValueError: invalid literal for int() with base 10:
So, what I suggest you do to make your implementation easier is to make use of try/exceptinstead to attempt to convert your value to a float. If it does not work, you prompt the user to keep entering a value until they do. Then you simply break your loop and return your number, type casted to a float.
Furthermore, because of the use of the try/except, you no longer need to put in a conditional check in your while loop. You simply can set your loop to while True and then break once you have satisfied your condition in your code.
Observe the code below re-written with what I mentioned above:
def GetVolume():
print("How many cublic cm of water does the item displace")
Volume = input()
while True:
try:
Volume = float(Volume)
break
except:
print("You have to type a value")
Volume = input()
return Volume
def GetVolume():
Volume = input("How many cublic cm of water does the item displace")
while not Volume.replace('.', '').replace(',', '').isdigit():
Volume = input("You have to type a value")
return float(Volume)
x = GetVolume()
print(x)
You have to modify your while because is validating that is str or different than int. An input will always be an str by default unless you modified the type with int() or float() in your case.
You can use 'try' instead to check for this:
while True:
x = input("How many cubic cm of water does the item displace")
try:
x = float(x)
break
except ValueError:
pass
print('out of loop')