Understanding Type Casting, Conditional Statements & Loops In Python
This is the 4th post in a series of learning the Python programming language.
User Input
User input in Python is a way for the user to provide input to a program. The input()
function is used to get input from the user. For example, the following code prompts the user to enter their name and stores it in the variable name
:
name = input("What is your name? ")
print("Hello, " + name)
The input function returns the input as a string, regardless of what type of input the user provides. This means that if the user enters a number, it will be stored as a string. This can cause problems if the program expects the input to be a different type, such as an integer or a float.
Typecasting
Typecasting is the process of converting one data type to another. In Python, we can use typecasting to convert a string to an integer or a float using the int()
and float()
functions respectively.
For example, if we want to convert the user input to an integer, we can use the following code:
age = int(input("What is your age? "))
print("You are " + str(age) + " years old.")
In this example, the user is prompted to enter their age, and the input is stored as a string. We then use the int()
function to convert the string to an integer and store it in the variable age
. We then use the str()
function to convert the integer back to a string so that it can be concatenated with the string “You are ” and ” years old.”
It’s also worth noting that, if the user inputs something that cannot be casted to the desired type, the code will raise a ValueError. We can use try-except block to handle this error and prompt the user again to input the correct value.
while True:
try:
age = int(input("What is your age? "))
break
except ValueError:
print("Please enter a valid integer.")
In this example, the user will be prompted repeatedly until they input a valid integer.
User input and typecasting are important concepts in Python programming. The
input()
function is used to get input from the user, and typecasting is used to convert the input to the desired data type.
Conditional Statements
In Python, conditional statements are used to make decisions based on certain conditions. The most commonly used conditional statements are “if,” “if-else,” and “if-elif-else.”
The “if” statement is the simplest form of a conditional statement. It allows you to check if a certain condition is true, and if it is, the code within the “if” block will be executed. For example:
x = 5
if x > 0:
print("x is positive")
In this example, the “if” statement checks if the variable “x” is greater than 0. Since it is, the code within the “if” block is executed, and the output is “x is positive.”
The “if-else” statement is an extension of the “if” statement. It allows you to specify what should happen if the condition in the “if” statement is not true. For example:
x = -5
if x > 0:
print("x is positive")
else:
print("x is not positive")
In this example, the “if” statement checks if “x” is greater than 0. Since it is not, the code within the “else” block is executed, and the output is “x is not positive.”
The “if-elif-else” statement is a more complex form of a conditional statement. It allows you to check multiple conditions, and if one of them is true, the code within the corresponding block will be executed. For example:
x = 5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
In this example, the “if” statement checks if “x” is greater than 0. Since it is, the code within the first block is executed, and the output is “x is positive.” If the first condition is not met, the program will check the next ‘elif’ condition and so on. If none of the conditions are met, the code within the “else” block is executed.
It’s also worth noting that you can have as many ‘elif’ conditions as needed and ‘else’ block is optional.
It’s important to keep in mind that once a condition is met, the code within the corresponding block will be executed, and the program will not check the remaining conditions. This means that you should order your conditions from most specific to least specific.
Conditional statements in Python allow you to make decisions based on certain conditions. “if” statements are used to check if a single condition is true, “if-else” statements are used to specify what should happen if the condition in the “if” statement is not true, and “if-elif-else” statements are used to check multiple conditions.
Loops
In Python, loops are used to execute a block of code multiple times. There are several types of loops available in Python.
for item in sequence:
# code to execute
For Loops
In Python, there are several types of for
loops that can be used to iterate over a sequence of items:
for
loop: The most basic form of afor
loop is used to iterate over a sequence of items, such as a list or a string. For example:
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
print(fruit)
In this example, the for
loop iterates over the fruits
list, and for each iteration, it assigns the current item to the variable fruit
and executes the code within the loop. The output will be:
apple
banana
mango
for-else
loop: Afor-else
loop is similar to a regularfor
loop, but it also includes anelse
block that is executed after thefor
loop completes. For example:
fruits = ['apple', 'banana', 'mango']
for fruit in fruits:
if fruit == 'banana':
break
else:
print("banana not found")
In this example, the for
loop iterates over the fruits
list, and for each iteration, it checks if the current item is equal to banana
. If it is, the break
statement is executed, and the loop is terminated. If the loop completes without finding banana
, the else
block is executed and the output will be “banana not found”
for-enumerate
loop: Theenumerate()
function is used to iterate over a sequence of items and keep track of the index of the current item. For example:
fruits = ['apple', 'banana', 'mango']
for i, fruit in enumerate(fruits):
print(i, fruit)
In this example, the enumerate()
function is used to iterate over the fruits
list and the for
loop assigns the current index to the variable i
and the current item to the variable fruit
. The output will be:
0 apple
1 banana
2 mango
for-zip
loop: The `zip() function is used to combine multiple sequences into one, and it returns an iterator of tuples. For example:
fruits = ['apple', 'banana', 'mango']
prices = [1.2, 2.5, 3.0]
for fruit, price in zip(fruits, prices):
print(fruit, price)
In this example, the zip()
function is used to combine the fruits
and prices
lists, and the for
loop assigns the current item from each list to the variables fruit
and price
respectively. The output will be:
apple 1.2
banana 2.5
mango 3.0
for-dict
loop: Afor
loop can also be used to iterate over the keys or values of a dictionary. For example:
fruits_prices = {'apple': 1.2, 'banana': 2.5, 'mango': 3.0}
for fruit in fruits_prices:
print(fruit)
In this example, the for
loop iterates over the keys of the fruits_prices
dictionary, and for each iteration, it assigns the current key to the variable fruit
and executes the code within the loop. The output will be:
apple
banana
mango
You can also use the .items()
method to access both key and value in the dict
fruits_prices = {'apple': 1.2, 'banana': 2.5, 'mango': 3.0}
for fruit,price in fruits_prices.items():
print(fruit,price)
The output will be:
apple 1.2
banana 2.5
mango 3.0
- The
range()
function is used to generate a sequence of numbers. It takes three arguments: start, stop, and step. The start and step arguments are optional, and the default values are 0 and 1 respectively. For example:
for i in range(5):
print(i)
This will generate a sequence of numbers from 0 to 4 and the output will be:
0
1
2
3
4
You can also use the range()
function with for
loop to iterate over a specific range of numbers.
for i in range(1,6):
print(i)
The output will be:
1
2
3
4
5
While Loop
There are two main types of while
loops that can be used to repeatedly execute a block of code:
while condition:
# code to execute
while
loop: Thewhile
loop repeatedly executes a block of code as long as a given condition is true. For example:
count = 0
while count < 5:
print(count)
count += 1
In this example, the while
loop will execute the code within the loop as long as the value of count
is less than 5. The output will be:
0
1
2
3
4
while-else
loop: Awhile-else
loop is similar to a regularwhile
loop, but it also includes anelse
block that is executed after thewhile
loop completes. For example:
count = 0
while count < 5:
print(count)
count += 1
else:
print("Count is greater than 5")
In this example, the while
loop will execute the code within the loop as long as the value of count
is less than 5. If the loop completes without meeting the condition, the else
block is executed and the output will be “Count is greater than 5”.
It’s important to note that while
loops can cause infinite loops if the condition is never met. It’s important to ensure that the condition will eventually be met. You can also use break
statement inside the loop to exit the loop when a certain condition is met.
In addition to the above, there is also a do-while
loop, but python doesn’t have a direct implementation for it, similar functionality can be achieved by using while True
and break
statement.
If you like the post, don’t forget to clap. If you’d like to connect, you can find me on LinkedIn.