0% found this document useful (0 votes)
5 views3 pages

Python Basics and Exercises Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views3 pages

Python Basics and Exercises Guide

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

ENSA-Kenitra Module : Compétences Numériques

LAB 2 : Python First Steps


For Exercises 1 and 2, predict the result of each instruction first. Then, open the
Python terminal in PyCharm, run the instruction, compare the actual output with
your prediction, and briefly explain why that result appears.
1. First Python commands

Instruction to type Result obtained + comment or explanation


type(20 + 1)

type(20 / 3)
print(20 // 3)

type(20 // 3)
20%3

5.45*10

2**4

(3+2)*5

3+2*5

result = 3 + 5 * 2 ** 3 - 4 / 2
print(result)

result = (10 + 5) * 3 - 8 / 2 ** 2 + 1
print(result)

2. Data Types

Instruction to type Result obtained + comment or explanation


type(3)

type(1.5)

int(3.6)

type("bonjour")

type(‘3’)

Pr. Mehdia AJANA Chapters2&3 – Python Overview and Basic Syntax 1


ENSA-Kenitra Module : Compétences Numériques

int(‘3’)

int(‘a’)

float("4")
b = 3.14
print(type(b))
c = True
print(type(c))

d = "Python"
print(type(d))
a = input("Enter your
height: ")
print(type(a))

a = float(input("Enter
your height: "))
print(type(a))

3. Exercises :

3.1. Write a script that asks the user for the day, month, and year, then displays the date as
follows:
Today’s Date is : 12/12/2023.

3.2. Write a Python program that asks the user to enter a number and then:
 Checks whether the number is positive, negative, or zero.
 Also determines whether the number is even or odd (only if it’s not zero).

3.3. Write a Python program that takes a student's score as input and outputs the
corresponding grade based on the following grading scale:
Score ≥ 90: Grade A
Score 80-89: Grade B
Score 70-79: Grade C
Score 60-69: Grade D
Score < 60: Grade F

Ensure that the input is valid (i.e., the score should be between 0 and 100).
If the input is invalid, print an error message like "Invalid score!"

3.4. Weather Decision System: Write a Python program that asks the user to input the
current weather conditions and decides whether a person should go for a walk based on
the following:

Pr. Mehdia AJANA Chapters2&3 – Python Overview and Basic Syntax 2


ENSA-Kenitra Module : Compétences Numériques

 If it's raining, the person should stay indoors.


 If it's windy but not raining, the person should only go for a walk if the
temperature is above 20°C. Otherwise, they should stay indoors.
 If it's neither raining nor windy, the person should go for a walk if the
temperature is above 10°C. Otherwise, they should stay indoors because it's too
cold.

Instructions:

 Ask the user for weather input:


o is it raining? (True/False)?
o is it windy? (True/False)
o What is the temperature?

Example Output:

 "Stay indoors, it's raining."


 "Go for a walk, it's windy but warm."
 "Go for a walk, the weather is fine."
 …

3.5. Count Vowels and Consonants in a string: Write a program that asks the user to input
a string, then uses a loop to count the number of vowels and consonants in the string.
You should remove the spaces from the input string and also consider uppercase and
lowercase letters.

[Link] a String : Write a program that reverses a given string entered by the user
using a loop. Do not use Python's slicing feature for this task.

3.7. Split a String: Split the string: "Life is not a bed of roses" into 3 parts of your choice.
Then, reassemble these parts in reverse order. Do not use Python's built-in split()
method. For example split the string into parts: “Life is”, “not a bed”, “of roses”
and reassemble them in reverse order.

Pr. Mehdia AJANA Chapters2&3 – Python Overview and Basic Syntax 3

Common questions

Powered by AI

Python handles user input with the 'input()' function, which reads input as a string. To utilize this data type for numerical operations, explicit type casting is necessary, such as using 'int()' for integers or 'float()' for floating-point numbers. For example, if a numerical value like height is required for computations, the input collected can be cast using 'float(input("Enter your height:")). This ensures correct data types are used in calculations .

The order of operations in Python follows PEMDAS/BODMAS (Parentheses/Brackets, Exponents/Orders, Multiplication and Division (left to right), Addition and Subtraction (left to right)). This means calculations enclosed in parentheses are evaluated first, followed by exponentiation. Multiplication and division are then performed from left to right, and finally addition and subtraction from left to right. Misplacing parentheses or misunderstanding these rules can alter the intended result of expressions .

To count vowels and consonants accurately, convert the input string to lowercase or uppercase to ensure case-insensitivity. Also, remove any spaces to focus only on letters. Implementing a loop that checks each character against vowel and consonant sets will facilitate the counting. Ignoring non-alphabet characters and summing up vowels and consonants separately ensures consistency across different types of inputs .

Python suggests implementing a weather decision system using a series of conditional statements (if-elif-else) to handle multiple conditions. For instance, the system should first check if it's raining and advise staying indoors. If it's not raining, it should check if it's windy and determine if walking conditions are favorable based on temperature thresholds. This layered approach efficiently narrows down the conditions and provides appropriate decisions based on comprehensive input assessments .

When designing a Python script for date input, considerations include format consistency and user guidance. Prompt clarity, such as separate queries for day, month, and year, assists user input accuracy. Using correct data types like integers for numeric entries and ensuring bounds (e.g., month range 1-12) help maintain valid inputs. The final display must format the date in a user-friendly manner, showing clear patterns like 'DD/MM/YYYY' to prevent misinterpretation .

To reverse a string without using Python's slicing feature, one can iterate over the string from the end to the start, appending each character to a new string or list. This can be done using a loop that decreases the index value from the length of the string minus one down to zero, or by using constructs like 'reversed()' function with ''.join()' to efficiently gather the characters in reverse order manually .

Converting string data types to numeric types in Python, such as using 'int()' or 'float()', can raise 'ValueError' if the string content is non-numeric (e.g., 'abc' or an empty string). Mitigation involves using exception handling (try-except blocks) to catch these errors and validate inputs prior to conversion. Providing user prompts for correction or displaying error messages can also enhance robustness and user experience .

The type of the result obtained from the expression '20/3' in Python is '<class 'float'>' because division in Python using the '/' operator always results in a floating-point number, even if the division result is a whole number .

Python determines the grade output based on conditional statements that compare the score against predefined ranges: 90 and above results in 'Grade A', 80-89 gives 'Grade B', 70-79 yields 'Grade C', 60-69 generates 'Grade D', and below 60 results in 'Grade F'. Input validation is crucial as it ensures the score is within the expected range of 0 to 100, preventing incorrect grading and errors during execution. Without validation, inputs like negative numbers or numbers over 100 could lead to incorrect grade assignments and logically invalid results .

The modulo operator '%' in Python returns the remainder of a division operation. By using the expression 'number % 2', we check if the remainder is zero. If true, the number is even, otherwise it is odd. For example, the instruction '5 % 2' returns 1, indicating that 5 is an odd number, whereas '4 % 2' returns 0, showing that 4 is even .

You might also like