上QQ阅读APP看书,第一时间看更新
Writing Python scripts
We are now familiar with the basic concepts of Python. Now we will write an actual program or script in Python.
Ask for the input of a country name, and check whether the last character of the country is a vowel:
countryname=input("Enter country name:")
countryname=countryname.lower()
lastcharacter=countryname.strip()[-1]
if 'a' in lastcharacter:
print ("Vowel found")
elif 'e' in lastcharacter:
print ("Vowel found")
elif 'i' in lastcharacter:
print ("Vowel found")
elif 'o' in lastcharacter:
print ("Vowel found")
elif 'u' in lastcharacter:
print ("Vowel found")
else:
print ("No vowel found")
Output of the preceding code is as follows:
- We ask for the input of a country name. The input() method is used to get an input from the user. The value entered is in the string format, and in our case the countryname variable has been assigned the input value.
- In the next line, countryname.lower() specifies that the input that we receive needs to converted into all lowercase and stored in the same countryname variable. This effectively will have the same value that we entered earlier but in lowercase.
- In the next line, countryname.strip()[-1] specifies two actions in one statement:
-
- countryname.strip() ensures that the variable has all the leading and trailing extra values removed, such as new line or tab characters.
- Once we get the clean variable, remove the last character of the string, which in our case is the last character of the country name. The -1 denotes the character from right to left or end to start, whereas +1 would denote from left to right.
- Once we have the last character stored in the lastcharacter variable, all that is needed is a nested condition check and, based upon the result, print the value.
To save this program, we need to save this file as somename.py, which will specify that this program needs to be executed in Python:
The PowerShell sample code for the preceding Python task is as follows:
#PowerShell sample code
$countryname=read-host "Enter country name"
$countryname=$countryname.tolower()
$lastcharacter=$countryname[-1]
if ($lastcharacter -contains 'a')
{
write-host "Vowel found"
}
elseif ($lastcharacter -contains 'e')
{
write-host "Vowel found"
}
elseif ($lastcharacter -contains 'i')
{
write-host "Vowel found"
}
elseif ($lastcharacter -contains '0')
{
write-host "Vowel found"
}
elseif ($lastcharacter -contains 'u')
{
write-host "Vowel found"
}
else
{
write-host "No vowel found"
}
Python is very strict in terms of indentation. As we can see in the example, if we change the indentations or tabs even by a space, Python will spit out an error stating the indentation is not correct and the compilation will fail. This will result in an error and unless the indentation is fixed, the execution will not be performed.