Trouble with python program (2.7.10) - python

So I'm fairly new to python and for my programming class, I have to write a program about a 100 metre race and tells if you qualified or not based on the time it took you to finish. If you're a male and you took longer than 10.18 seconds to finish; then you didn't qualify. If you're a female and it took you longer than 11.29 seconds to finish; then again, you didn't qualify.
My problem is that both messages saying if you qualified or didn't qualified appear no matter what your time was. I am using Python 2.7.10. My code so far is:
gender = raw_input("Are you Male (M) or Female (F)?: ")
time = raw_input("What time did you get for the 100m race?: ")
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"
if gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"

Raw_input returns a string. You need to do
time = float(raw_input("What time..."))
(Note that python will allow you to compare a string to a float, but it doesn't try to convert the string to match)
(Edit: And as noted by the other two answers at the time of this posting, you should use elif)

Try using elif for better handling
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
elif gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"

The else for each clause will always run because gender will always be opposite to what the user has inputted. You also need to cast the 2nd input to float to correctly compare the value to either 10.18 or 11.29.
To correct this (without refactoring):
gender = raw_input("Are you Male (M) or Female (F)?: ")
time = float(raw_input("What time did you get for the 100m race?: "))
if gender is "M" and time > 10.18:
print "Sorry, you did not qualify"
elif gender is "F" and time > 11.29:
print "Sorry, you did not qualify"
else:
print "Congratulations, you qualified!"

Take the logic step-by-step. Let's consider an example of a Female with a time of 10 seconds:
The first 'if' comes out False, because she's female (False AND anything is still False, so the time doesn't even matter). So the first "Sorry" message doesn't get printed.
But since that 'if' was not executed, the 'else' immediately following does get executed, printing the message.
That's the problem: Just because someone is not a Male who failed, doesn't mean that they are a Male who succeeded. The female we're using as an example is neither.
Then, after incorrectly printing that message, it tries all over again for the female-who-failed case, and prints the message you did want.
You need to make the logic of the program, exactly match the logic of the real-life situation. So think in detail about which decisions affect what other decisions in this case.
I'll leave the exact change up to you, since that's likely what your teacher wants you to work through and figure out.

Related

TypeError: ">” not supported between instances of "str' and int‘

I know I’m missing something with this code. Can someone please help me? I’m new to coding and I’ve struggling with this all day. I don’t want to keep emailing my instructor so maybe I can get help from here. I’m trying to get it to run through the if statements with user input and then calculate the amount but I don’t know what I’m missing.enter image description here
You should post code you're asking about as text in your question.
Going over your code with some comments:
print("Welcome") # no issue here, although Python default is single quotes, so 'Welcome'
print = input("Please enter company name:")
After that last line, print is a variable that has been assigned whatever text was entered by the user. (even if that text consists of digits, it's still going to be a text)
A command like print("You total cost is:") will no longer work at this point, because print is no longer the name of a function, since you redefined it.
num = input("Please enter number of fiber cables requested:")
This is OK, but again, num has a text value. '123' is not the same as 123. You need to convert text into numbers to work with numbers, using something like int(num) or float(num).
print("You total cost is:")
The line is fine, but won't work, since you redefined print.
if num > 500:
cost = .5
This won't work until you turn num into a number, for example:
if int(num) > 500:
...
Or:
num = int(num)
if num > 500:
...
Also, note that the default indentation depth for Python is 4 spaces. You would do well to start using that yourself. Your code will work if you don't, but others you have to work with (including future you) will thank you for using standards.
Finally:
print = ("Total cost:, num")
Not sure what you're trying to do here. But assiging to print doesn't print anything. And the value you're assigning is just the string 'Total cost:, num'. If you want to include the value of a variable in a string, you could use an f-string:
print(f"Total cost: {num}")
Or print them like this:
print("Total cost:", num) # there will be a space between printed values

If statement code not reaching either branch

2 people ask for a 1,000,000 loan, one who has good credit only has to pay a 10% deposit, the other with bad credit has to pay a 20% deposit.
I thought, couldn't I make this from an input statement? It asks the input questions (where I then respond good) and then it states "process finished with exit code 0" which I guess means that there is nothing for Python to code. Here is what I've done, what I want to happen is if you type "good" then the answer will = 10,000 but if you type "bad" then you will be given the answer 20,000.
price = 1000000
prompt1 = input('What is your credit rating, good or bad')
if prompt1=='Good':
print(1000000 * 0.1)
elif prompt1 == 'Bad':
print(1000000 * 0.2)
Edited from what Tamerjar suggested
The reason you are not able to run this code, is that the words taken from the input statement do not match the function.
So you can change the format of your code as below
I'm using the ".lower()" function in order to take the input data and transform it to be all small letters. Please let me know if this answers your question.
price = 1000000
prompt1 = input('What is your credit rating, good or bad')
prompt = prompt1.lower()
if prompt=='good':
print(price * 0.1)
elif prompt == 'bad':
print(price * 0.2)
else:
print("Wrong input word")
I added this else statement just in case a wrong word was typed into the input. In order to handle those kinds of errors.

Tkinter text entry validation in python

I have created a simple program which asks for a user's name and age. The program will then take the details from a textbox and work out how old they will be in 5 years time.
The interface is fine. It's the validation that I am having difficulty with. When a user enters a letter instead of a number the program shows an error message, but continues to run regardless. I have tried using a while True: loop but this seems to just crash the program.
Here's what I have written already:
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
if age.isalpha():
tkinter.messagebox.showinfo("Error", "The Age is invalid")
textboxAge.delete("0","end")
newAge = int(age)+5
print("Hello",name)
print("In 5 years time you will be",newAge)
I have looked at a few other tutorials but they are a little confusing. I am going to extend this by adding another elif in and the following code
elif age >= 100:
tkinter.messagebox.showinfo("Error", "You have entered a number greater than 100")
textboxAge.delete("0","end")
but this doesn't like the fact it is a string not an integer.
What would be the best way to check to see if a number has been entered into a textbox?
def calculate():
name = (textboxName.get())
age = (textboxAge.get())
try:
newAge = int(age)+5
except ValueError:
tkinter.messagebox.showinfo("Error", "The Intended Reading Age is invalid")
textboxAge.delete("0","end")
return
print("Hello",name)
print("In 5 years time you will be ",newAge)
# ...
If an error occurs somewhere in the try-section, python will not crash, but rather jump to the except part. The critical step is converting age into integer. This throws a ValueError if it is a string. In this case, the message box is shown and the text in your textbox is deleted. return then will stop the function, so the rest of it won't be processed. If nothing happens in the try-section, then except will be skipped.

PDA (Permissible Dating Age) Algorithm?

The project is to create a simple Python program that will prompt the user for his or her age and then print out the lower and upper age limits for the user's date based on the Permissible Dating Age Algorithm.
The PDA Algorithm is: d = a/2 + 7, a is your age, and d is the lowest permissible age of your date where a is an integer.
Here is the code I have so far:
import random
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdoutflush()
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
It seems to be running okay, yet nothings printing out and I'm confused as to what's going wrong with the print statements.
You weren't that far off the mark to be honest but your print statements were not faulty. Rather, they are contained within a function that you never call so they never actually run. There is also a small typo. This code will run:
import random #Not needed with current code
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdout.flush() #You missed a full-stop
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
#Something to call your function and start it off
start_program = findACompanion()
Stick with the classes, it won't take long till it falls into place. Being thrown in at the deep-end is the best way :)
You've defined a function findACompanion, but nothing is calling the function, so none of the statements within the function are being executed. You can call it yourself from the prompt:
>>> findACompanion()
There's a convention that is common in Python to detect if you are running a file as your main program and to make the call automatically, see Top-level script environment. The convention calls for the function to be called main but you can call anything you'd like.
if __name__ == "__main__":
findACompanion()

Python beginner, text-based game

I'm fairly new to the programming game; I'm 3/4 of the way through Learn Python the Hard Way and I had a question about a little text-based game I made... So in this game my guy is stranded on a desert island and you have the option(raw input) of going left right or into the jungle. After choosing a direction, you're given the option to choose how many miles to walk. Each direction is supposed to have a different end result (and mile distance).
If you enter a number that is less than the number of miles to the destination, you're prompted with a choice to either "turn around or "keep going". If you enter turn around, you're taken back to the beginning, where you're again asked to choose a direction. If you enter keep going, the program returns to miles(), where you can choose a new amount of miles to walk.
def miles():
print "How many miles do you walk?"
miles_choice = raw_input("> ")
how_much = int(miles_choice)
if how_much >= 10:
right_dest()
elif how_much < 10:
turn()
else:
print "You can't just stand here..."
miles()
Ok so here's two questions:
How would I make it so that if the user originally enters a number of miles less than the destination distance, and the second mile input + the first mile input == the amount of miles to the destination, it will add the inputs and run my destination function, not just repeat miles().
Since all three final destinations will have different distances, should I write three separate mile functions? Is there a way to make it so that depending on the original direction chosen, miles() will run the different endpoints?
I'm sorry if this doesn't make a lick of sense... I'm still learning and I'm not sure how to fully explain what I'm trying to get across.
You could store the amount of miles to walk in each direction in a dict, and then check the dict to see if the user has walked far enough:
distances = {
'right': 7,
'left': 17,
'forward': 4
}
direction_choice = raw_input("> ")
miles_choice = raw_input("> ")
if how_much >= distances['direction_choice']:
right_dest()
elif how_much < distances['direction_choice']:
turn()
else:
print "You can't just stand here..."
miles()
Be sure to properly validate and cast the user input, which I have not addressed. Good luck!
I don't fully understand the requirements (the intended behavior and constraints). However, you might consider passing a parameter to your function (through and argument) to convey the maximum number of miles which the play could go in that direction).
For example:
#!/usr/bin/env python
# ...
def miles(max_miles=10):
print "How many miles do you walk?"
while True:
miles_choice = raw_input("> ")
try:
how_much = int(miles_choice)
except ValueError, e:
print >> sys.stderr, "That wasn't a valid entry: %s" % e
continue
if max_miles > how_much > 0:
break
else:
print "That's either too far or makes no sense"
return how_much
... in this case you pass maximum valid number of miles into the function through the "max_miles" argument and you return a valid integer (between 1 and max_miles) back.
It would be the responsibility of this function's caller to then call right_dest() or turn() as appropriate.
Note that I've removed your recursive call to miles() and replace it with a while True: loop, around a try: ... except ValueError: ... validation loop. That's more appropriate than recursion in this case. The code does a break out of the loop when the value of how_much is valid.
(By the way, if you call miles() with no parameter then the argument will be set to 10 as per the "defaulted argument" feature. That's unusual to Python (and Ruby) ... but basically makes the argument optional for cases where there's a sensible default value).
#Question #1: I used Class intern variables. You will maybe need them for further programming parts and should take it to zero when you are done on one direction, to start with zero for next step/lvl.
#Question #2: Dictionaries are the best way to do so,self.dest. Parameter pos used as key to get the value from the dictionary.
class MyGame:
def __init__(self):
self.current_miles = 0
self.dest = {'Left' : 10, 'Into the jungle' : 7, 'Right' : 22}
def miles(self,pos):
print "How many miles do you walk?"
miles_choice = raw_input("> ")
self.current_miles += int(miles_choice)
if self.current_miles >= self.dest.get(pos):
self.miles("Right")
elif self.current_miles < self.dest.get(pos):
print "you went "+ str(self.current_miles) + " miles"
else:
print "You can't just stand here..."
self.miles(pos)
mg = MyGame()
mg.miles('Into the jungle')

Categories