Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
If statement help
#1
Hello! I am very new to Python. I am trying to create a program that takes user input for the number of exercises and types of exercises and returns a random sample from the respective list. However the output I get does not print out the random sample of exercises. I am not sure what I am doing wrong or how to make the final random sample print out. Any help is greatly appreciated!

from random import sample

Upper_List=['25 push ups', '12 shoulder press ups', '12 tricep dips']
Lower_List= ['25 jump squats', '25 calf raises', '20 lunges']
Full_Body_List = ['25 push ups', '25 jump squats', '12 shoulder press ups', '20 leg lifts', '25 calf raises', '20 lunges']

number = int(input('Number of Exercises:'))

workout_type=input("Upper, Lower, or Full Body?")

if workout_type == "Upper":
    print(sample(Upper_List, number))
elif workout_type == 'Lower':
    print(sample(Lower_List, number))
elif workout_type=="Full Body":
    print(sample(Full_Body_List, number))
OUTPUT:

Number of Exercises: 3
Upper, Lower, or Full Body? Upper
[Finished in 4.28s]
Reply
#2
It seems your input isn't matching the conditions. Since there's a space between the question mark and your input and no space after the question mark in the input() string, I'm guessing the input is " Upper" not "Upper".

For an input like this, use a loop to ensure the program will only proceed once an acceptable input has been entered.

Also, consider using str.lower() and use lowercase strings to check the input. This will allow for "Upper", "UPPER", "UpPer", etc. instead of only "Upper" to be accepted.

Finally, explore using dictionaries to store the lists so you can avoid the if...elif...else statement.

from random import sample

workouts = {
    "upper": ['25 push ups', '12 shoulder press ups', '12 tricep dips'],
    "lower": ['25 jump squats', '25 calf raises', '20 lunges'],
    "full body": ['25 push ups', '25 jump squats', '12 shoulder press ups', '20 leg lifts', '25 calf raises', '20 lunges']
}

while True:
    number = int(input('Number of Exercises:'))
 
    workout_type=input("Upper, Lower, or Full Body?").lower()
    if workout_type in workouts.keys():
        exercises = sample(workouts[workout_type], number)
        break

print(exercises)
Reply
#3
It worked ok for me with no changes to your code
Output:
Number of Exercises:3 Upper, Lower, or Full Body?Upper ['25 push ups', '12 shoulder press ups', '12 tricep dips']
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020