Python 3, task Leap year SOLVED | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Python 3, task Leap year SOLVED

I tried to solved the task with several ways but none of them did not fully work. Who has ever solved this task or know what the problem is please help. I will show my solutions right now (just copy) The below is the task: You need to make a program to take a year as input and output "Leap year" if it’s a leap year, and "Not a leap year", if it’s not. To check whether a year is a leap year or not, you need to check the following: 1) If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT leap year. 2) If the year is evenly divisible by 100, go to step 3. Otherwise, the year is a leap year. 3) If the year is evenly divisible by 400, the year is a leap year. Otherwise, it is not a leap year. Sample Input 2000 Sample Output Leap year Use the modulo operator % to check if the year is evenly divisible by a number.

21st May 2021, 6:45 AM
Елена Леващева
Елена Леващева - avatar
38 Answers
+ 6
if(((year%4==0)and (year%100!=0)) or (year%400==0)): print("Leap year") else: print("Not a leap year")
21st May 2021, 6:55 AM
sarada lakshmi
sarada lakshmi - avatar
+ 9
Your first approach goes something like this, year = int(input()) if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year") else: print("Not a leap year") else: print("Leap year") else: print("Not a leap year")
21st May 2021, 6:58 AM
sarada lakshmi
sarada lakshmi - avatar
+ 6
Yaroslav Vernigora thanks for hint. i have changed my code accordingly and i looks better 😊 #ваш код weight = int(input()) height = float(input()) bmi = weight / (height**2) if bmi < 18.5: print("Underweight") if 18.5 <= bmi < 25: print("Normal") if 25 <= bmi < 30: print("Overweight") if bmi > 30: print("Obesity")
22nd May 2021, 12:18 PM
Елена Леващева
Елена Леващева - avatar
+ 3
sarada lakshmi thanks a lot. It perfectly works. i would never do it myself year = int(input()) #ваш код if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: print("Leap year") else: print("Not a leap year") else: print("Leap year") else: print("Not a leap year")
21st May 2021, 7:11 AM
Елена Леващева
Елена Леващева - avatar
+ 3
sarada lakshmi thanks again for your second code now i finally got it too. (After hard googling)
21st May 2021, 8:45 AM
Елена Леващева
Елена Леващева - avatar
+ 3
Yaroslav Vernigora книга интересная, спасибо
21st May 2021, 1:14 PM
Елена Леващева
Елена Леващева - avatar
+ 2
year = int(input()) #ваш код """ #1 code, 2 tests are ok, 5 tests are not ok if year % 4 == 0: if year % 100 != 0: if year % 400 == 0: print("Leap year") else: print("Not a leap year") """ #2 code, 4 tests are Ok, but 3 tests are not if year % 4 != 0: print("Not a leap year") elif year % 100 == 0: print("Not a leap year") elif year % 400 != 0: print("Not a leap year") else: print("Leap year")
21st May 2021, 6:47 AM
Елена Леващева
Елена Леващева - avatar
+ 2
Yaroslav Vernigora у меня нет иллюзий на этот счёт. Я точно бы его не сделала. Я рада, что хотя бы поняла правильное решение.
21st May 2021, 8:48 AM
Елена Леващева
Елена Леващева - avatar
+ 2
😆 от чего голова прошла?
21st May 2021, 11:08 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
How to improve programming and logical skills The conditional statement Programming is more about conditions and looping.To improve logical thinking, start to think conditionally such as Yes or No,True or False.Try to question yourself or solve a problem as a conditional statement such as if...then...it's very helpful to improve your conditional reasoning power. 2. Think like a machine The machine didn't understand anything because it works on the instruction which we gave. To solve a problem, give instructions and try to follow the order. Here, instructions are nothing but logic. Machine-oriented thinking will help you to write logic in a program. 3. Solve logic puzzles Try to solve riddles and puzzles from newspapers or in a modern mobile app.Don’t get disheartened if you can't solve them at first attempt or take a long time to solve them.Remember that you are in the process of learning and improving skills.Your brain will be trained to think differently with every puzzle that you try to solve. /Matiyas/
21st May 2021, 12:35 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
Можно создавать на бумаге логические конструкции, своими словами ( если... то... иначе...) затем превращать их в код. Например эта задача даёт прямую подсказку последовательности действий. Просто надо помнить, что бывают не только программы с ветвлением одного уровня, а при правдивости одного условия можно создавать другие подуровни логики. Использовать ветвление-выбор: if, elif, else, switch - case, операторы сравнения ==, !=, операторы OR, AND. Еще в питоне мне нравится вот эта конструкция: 18.5 <= BMI < 25. Это удивительно простой и интуитивно понятный язык! Я от него тащусь! 😁
21st May 2021, 12:44 PM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
you have to learn this together logic and python. the first step is to master the basic knowledge of the syntax of the language, so that you can use logic to solve problems. if you don't have a logical solution in mind you won't be able to write a working program
22nd May 2021, 6:55 AM
Yaroslav Vernigora
Yaroslav Vernigora - avatar
+ 2
1) If the year is evenly divisible by 4, go to step 2. Otherwise, the year is NOT leap year. If year % 4 == 0: # step 2 else: output = "the year is NOT a leap year" 2) If the year is evenly divisible by 100, go to step 3. Otherwise, the year is a leap yea. if year % 100 == 0: # step 3 else: output = "the year will be a leap year" 3) If the year is divisible by 400, then the year is a leap year. Otherwise, it is not a leap year. If year % 400 == 0: output = "leap year" else: output = "not a leap year" Putting it all together If year % 4 == 0: # step 2 if year % 100 == 0: # step 3 If year % 400 == 0: output = "leap year" else: output = "not a leap year" else: output = "the year will be a leap year" else: output = "the year is NOT a leap year" print(output) Isn't it easy? ☺️ The main thing is not to panic: — "The eyes are afraid, but the hands are doing." Happy Coding!
22nd May 2021, 11:40 AM
Solo
Solo - avatar
+ 2
Vasiliy спасибо большое, есть над чем подумать. Мне условия лёгкими не кажутся. Для меня они звучат, что если все три выполняются, то високосный. Надо будет подумать.
22nd May 2021, 12:00 PM
Елена Леващева
Елена Леващева - avatar
+ 2
Елена Леващева : — "Для меня они звучат, что если все три выполняются, то високосный." Я в начале тоже так подумал ☺️ Но увидев, что тест не проходит, я вновь внимательно перечитал задание и сделал всё пошагово, что и продемонстрировал Вам. Чем и хороши тестовые задания, они помогают выявить наши слабые стороны. Толку с того что мы изучим все правила написания кода, а логически решать задачи нет, или банальная невнимательность нам не позволит полноценно использовать наши навыки. На мой взгляд это задание одно из самых лучших на SoloLearn, оно не только проверяет наши знания, но и направляет нашу логику в нужное русло.
22nd May 2021, 12:19 PM
Solo
Solo - avatar
+ 2
Vasiliy соглашусь на все сто. Лучше не скажешь. 👍👍👍
22nd May 2021, 12:24 PM
Елена Леващева
Елена Леващева - avatar
+ 2
Vasiliy спасибо, я вас услышала Внизу мой код if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: output = "Leap year" else: output = "Not a leap year" else: output ="Leap year" else: output = "Not a leap year" print(output)
22nd May 2021, 1:00 PM
Елена Леващева
Елена Леващева - avatar
+ 2
☺️ Елена Леващева , в итоге от нас требовалось только преобразовать строковое значение в числовое при вводе данных. P. S: "Мы получили шаблон решения задачи, теперь обладая теми или иными знаниями мы могли бы его минимизировать ☺️. Ух ты! Оказывается мыслить шаблонно - не значит плохо 😳." 😃
22nd May 2021, 1:26 PM
Solo
Solo - avatar
+ 2
Anoneem Games year% 4 == 0, means that the number is divisible by 4 without a remainder, i.e. 4 is its divisor. This means our year is the fourth year, and every fourth year is a leap year.
30th Jun 2021, 5:58 AM
Елена Леващева
Елена Леващева - avatar
+ 1
Algorithm for determining a leap year: 1) if the year is divisible by 4 and not divisible by 100, this is a leap year. 2) if the year is divisible by 4 and by 100 but not divisible by 400, this is not a leap year. 3) if the year is divisible by 4 and by 100 and by 400, this is a leap year. This last one can be changed with if the year is divisible by 400, this is a leap year. (i hope i am right)
21st May 2021, 8:33 AM
Елена Леващева
Елена Леващева - avatar