I'm a french newbie in Python and I would like to code a program which warns us when the time (string "Day, Hours, Minutes, Seconds") is wrong (for example, 83 seconds).
I did this program:
t=input("Put day,hours,minutes,seconds: ")
t="j,h,m,s"
if int(t[6])<=0 or int(t[6])>=59:
print("Seconds wrong")
if int(t[4])<=0 or int(t[4])>=59:
print("Minutes wrong")
if int(t[2])<=0 or int(t[2])>=24:
print("Hours wrong")
if int(t[0])<=0 or int(t[0])>=31:
print("days wrong")
else:
print("OK")
But I've this error:
if t[6]<=0 or t[6]>=59:
TypeError: unorderable types: str() <= int()
So I put "int" everywhere (like "int(t[X])<=0")
but then I've this error:
if int(t[6])<=0 or int(t[6])>=59:
ValueError: invalid literal for int() with base 10: 's'
There are no digits in this string:
t="j,h,m,s"
so any attempt to do int(t[anything]) is going to fail. You can't convert a string to an integer unless the string contains a string representation of an actual integer, such as t = "1234".
Moreover, even if you had something like t = "31,11,22,45", then int(t[6]) would not give you the number of seconds, because the representation of seconds would be at indices 9 and 10. You'd need t = int(t[9:11]) in that case.
Something like this is what you're looking for:
#!/usr/bin/python
t = "31,11,22,45"
(day, hour, min, sec) = [int(elem) for elem in t.split(',')]
if not 0 <= sec <= 59:
print("Seconds wrong")
elif not 0 <= min <= 59:
print("Minutes wrong")
elif not 0 <= hour <= 23:
print("Hours wrong")
elif not 1 <= day <= 31:
print("days wrong")
else:
print("OK")
Note you either need to change all but your first if to elif, otherwise it'll print "OK" if day is correct but everything else is wrong, or you'll need to keep some kind of separate variable to store if anything is wrong, and check that at the end, such as in the following:
#!/usr/bin/python
t = "31,11,22,45"
(day, hour, min, sec) = [int(elem) for elem in t.split(',')]
time_ok = True
if not 0 <= sec <= 59:
print("Seconds wrong")
time_ok = False
if not 0 <= min <= 59:
print("Minutes wrong")
time_ok = False
if not 0 <= hour <= 23:
print("Hours wrong")
time_ok = False
if not 1 <= day <= 31:
print("Days wrong")
time_ok = False
if time_ok:
print("Time is OK")
Nice effort, but be careful with the second line:
t = "j,h,m,s"
This overwrites the user input, and assigning "j,h,m,s" to t instead. Remove it!
Also, you can't compare it using or. Just check if int(t[6]) > 59 is sufficient.
if int(t[6]) > 59:
print("seconds wrong")
A better way to get the comma-separated numbers is to use string.split() method.
t = t.split(',') #split the string in the commas
Now, you don't have to worry about the comma counts. The day would be t[0], the hours would be t[1], and so on.
Ah, also one more thing. You don't have to use if statements repeatedly there. Use it on the first time, and change the next ones with elif statements.
Full fixed code:
t = input("Put day,hours,minutes,seconds: ")
if int(t[6])>59:
print("Seconds wrong")
elif int(t[4]) < 0 or int(t[4]) > 59:
print("Minutes wrong")
elif int(t[2]) < 0 or int(t[2]) > 24:
print("Hours wrong")
elif int(t[0]) < 0 or int(t[0]) > 31:
print("days wrong")
else:
print("OK")
To be honest, as Paul mentioned, this still won't work if any input is more than one digit.
You'll have to use string.split() to achieve this.
t = input("Put day,hours,minutes,seconds: ").split(",")
if int(t[3])>59:
print("Seconds wrong")
elif int(t[2]) < 0 or int(t[2]) > 59:
print("Minutes wrong")
elif int(t[1]) < 0 or int(t[1]) > 24:
print("Hours wrong")
elif int(t[0]) < 0 or int(t[0]) > 31:
print("days wrong")
else:
print("OK")
Related
I am trying to create and if/elseif statement so that when user inputs a number it gives him the answer of how many integers he has.
message = int(input("Enter an integer:"))
if message < 0:
print("1 digit, negative")
elif message < 10:
print("1 digit")
elif message >= 10:
print ("2 digits")
elif message >= 100:
print("3 digits")
elif message >= 1000:
print("more than 3 digits")
To my knowledge the if/else statement can be used as many times as you want and it seems like it stops working after 3statement (elif message >= 10:) , but if I temporarily comment out the 3nd statement the 4th statement(elif message >= 100:) works ,but the 5 statements does not.
What am I doing wrong?
I think you meant this instead:
if message < 0:
print("negative")
elif message < 10:
print("1 digit")
elif message < 100:
print ("2 digits")
elif message < 1000:
print("3 digits")
else:
print("more than 3 digits")
Note how all of these conditions use <.
I was attempting to solve some python excercise. I came across a question and that has made me feel bored. Please will you resolve it?
A school has following rules for grading system:
Below 25 - F
25 to 45 - E
45 to 50 - D
50 to 60 - C
60 to 80 - B
Above 80 - A
Ask user to enter marks and print the corresponding grade.
print("My mark is ")
a = input()
if '25 > a':
print('F')
elif a < 25 and a > 45:
print('E')
elif 45 <= a and a >|= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
My expected result was different grades for different numbers but instead got only F for every input I do...
print("My mark is ")
a = int(input())
if a < 25:
print('F')
elif a >= 25 and a < 45:
print('E')
elif a >= 45 and a < 50:
print('D')
elif a >= 50 and a < 60:
print('C')
elif a >= 60 and a < 80:
print('B')
else:
print('A')
first of all, you should cast input to int. then, you just compare it and "a" should be the first in comparing like a > 25, not 25 < a
Multiple issues..
Remove the outside quotes of your if statements as those are strings.
elif '45 <= a and a => 50': the order must be >=
And you must compare with an int so you need to do int(input()) or another variation of converting to int type.
a = int(input('What is the grade?'))
print("My mark is ")
if 25 > a:
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
your code needs a little clean up. Dont use quotation around the condition which is supposed to be Boolean
a = input("My mark is ")
a=int(a)
if (25 > a):
print('F')
elif a <= 25 and a > 45:
print('E')
elif 45 <= a and a >= 50:
print('D')
elif 50 <= a and a >= 60:
print('C')
elif 60 <= a and a >= 80:
print('B')
else:
print('A')
So this is what I am struggling with on my assignment...
"You are to account for invalid input. Drivers must be between the ages of 16 and 105. Number of traffic violations cannot be less than 0. Display only the message “Invalid Entry” in either case"
I can get the age part right but for the life of me I cannot get the number of violations to not work... can anyone assist?
Basically what I am needing is I need:
def Invalid_Entry():
if Violation == float or Violation == str and Violation == int:
print("Invalid Entry")
to work... this is my issue. The rest of the code works exactly as it needs to work. However, I need it so when the user enters a number for number of violations it can only be a whole number and a numeric item, no "terms", if that makes sense.
Name = input("What is the customers name? ")
Age = int(input("What is the age of the customer? "))
Violations = int(input("How many violations does the customer have? "))
def main():
Violation = Number_Violations(Violations)
Price = Premium()
Invalid = Invalid_Entry()
if Age < 16 or Age >= 106:
print("Invalid Entry")
else:
print(Name, "as a ", Violation, "risk driver, your insurance will cost
", Price)
def Number_Violations(Violations):
if Violations >= 4:
return "High"
elif Violations == 0:
return "None"
elif Violations == 1:
return "Low"
elif Violations == 2 or 3:
return "Moderate"
else:
Violations != 0
return "invalid Entry"
return Violations
def Premium():
if Violations >= 4 and Age >= 25:
return "$410.00"
elif Violations >= 4 and Age < 25:
return "480.00"
elif Violations == 3 and Age >= 25:
return "390.00"
elif Violations == 3 and Age < 25:
return "450.00"
elif Violations == 2 and Age >= 25:
return "365.00"
elif Violations == 2 and Age < 25:
return "405.00"
elif Violations == 1 and Age >= 25:
return "315.00"
elif Violations == 1 and Age < 25:
return "$380.00"
elif Violations == 0 and Age >= 25:
return "275.00"
else:
return "$325"
def Invalid_Entry():
if Violation == float or Violation == str and Violation == int:
print("Invalid Entry")
main()
You could check both age and number of traffic violations at the beginning of the program, and exit if conditions are not satisfied:
if (Age < 16 or Age >= 106 or Violations<0):
print("Invalid Entry")
exit()
For that solution you will need to import exit function before executing it:
from sys import exit
*EDIT. Following our comments, here is a code that should work:
from sys import exit
Name = input("What is the customers name? ")
# enter age and violations number and check type and value
try:
Age = int(input("What is the age of the customer? "))
Violations = int((input("How many violations does the customer have? ")))
except ValueError:
exit('invalid entry')
if (Violations<0 or Age not in range(16,107)):
exit('invalid entry')
def main(name, age,violations):
driver_risk = Number_violations(violations)
price = Premium(violations,age)
print("{} as a {} risk driver, your insurance will cost {}".format(name, driver_risk, price))
def Number_violations(violations):
if violations == 0:
return "None"
elif violations == 1:
return "Low"
elif violations in [2,3]:
return "Moderate"
else:
return "High"
def Premium(violations,age):
if violations >= 4 and age >= 25:
return "$410.00"
elif violations >= 4 and age < 25:
return "480.00"
elif violations == 3 and age >= 25:
return "390.00"
elif violations == 3 and age < 25:
return "450.00"
elif violations == 2 and age >= 25:
return "365.00"
elif violations == 2 and age < 25:
return "405.00"
elif violations == 1 and age >= 25:
return "315.00"
elif violations == 1 and age < 25:
return "$380.00"
elif violations == 0 and age >= 25:
return "275.00"
else:
return "$325"
main(Name,Age,Violations)
This line of code doesn't do what you expect:
elif Violations == 2 or 3:
It should be this:
elif Violations in [2, 3]:
I am trying to do two things here.
I want to print "value entered is not a valid age" if the input is not a number in this code:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
Also, how can I repeat this program once it is done?
You could check whether input is a valid digit with isdigit method of str. For multiple times you could wrap your code to a function and call it as much as you want:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
For make this code runnig every time you should add a loop , like while loop , and add a break whenever you want end this loop or add a condition for example run 10 times,and if you want check the input is float , you can add a try section:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
It is also a good idea to arrange your cases in order, to make it easier to see what is happening (and to make sure you didn't leave an unhandled gap):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")
temp = 120
if temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Python picks the first condition that is true, and the rest of the if..elif..else branches are skipped.
120 > 85 is true, so the first test passes and 'Hot' is printed. It doesn't matter that the second test also matches after that point.
Put the > 100 test first:
if temp > 100:
print "REALLY HOT!"
elif temp > 85:
print "Hot"
elif temp > 60:
print "Comfortable"
else:
print "Cold"
Alternatively, limit the tests to exclude the upper range:
if 100 >= temp > 85:
print "Hot"
elif temp > 100:
print "REALLY HOT!"
elif temp > 60:
print "Comfortable"
else:
print "Cold"