Advertisement
MeckeOfficial

odd/even

Sep 28th, 2021
1,033
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.52 KB | None | 0 0
  1. # while Loop to ask for a Start-Number,
  2. # restarts the Loop if User enters anything else than a Number
  3. while True:
  4.  
  5.     # trying to convert User-Input to a Number
  6.     # and breaking the Loop on Success
  7.     try:
  8.         start_num = int(input("Enter a Start-Number: "))
  9.         break
  10.  
  11.     # raising an Error if Input was not a Number
  12.     # and restarting the Loop again
  13.     except ValueError:
  14.         print("Your Input was not a valid Number.")
  15.  
  16. # same Loop as above, but with a check
  17. # if End-Number is bigger than Start-Number
  18. while True:
  19.  
  20.     # trying to convert as above
  21.     try:
  22.         end_num = int(input("Enter a End-Number: "))
  23.  
  24.         # If the Start-Number is bigger than the End-Number
  25.         # L#notify the User about the Issue and restart the Loop
  26.         if end_num <= start_num:
  27.             print("Start-Number is bigger than End-Number")
  28.             raise ValueError
  29.  
  30.         # break the Loop if everything is correct
  31.         break
  32.     except ValueError:
  33.         print("Your Input was not a valid Number.")
  34.  
  35. # List-Comprehention, very useful, watch a Tutorial about it
  36. # it is a Loop in 1 Line and transform it to a List
  37.  
  38. # this will add every Number that has Modulo 0 to even
  39. even = [i  for i in range(start_num, end_num) if i % 2 == 0 ]
  40.  
  41. # this will add every Number that has Modulo 1 to odd
  42. odd = [i  for i in range(start_num, end_num) if i % 2 == 1 ]
  43.  
  44. # Printing the Results of the above Lists
  45. print(f"Sum of all even Numbers: {sum(even)}")
  46. print(f"Sum of all odd Numbers: {sum(odd)}")
  47.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement