November 1, 2017 at 2:29 pm #790
When coding in python you should use a IDE instead of just using pythons shell. For this tutorial we used pycharm which can be downloaded and used for free here.
In this quick tutorial we will be learning about If, elif and else statements as well as for loops. These statements are fundamental to any programming language whether in PHP, Java, Ruby or python.
What are if statements?
Age = 13 #This a variable set at 13 if age < 21: #checks to see if age is under or over 21, if under 21 will print message “Cannot sell beer to you!” print("Cannot sell beer to you!") name = "James" #Creates a variable with the string James stored in it. if name is "James": #checks to see if the variable contains the name James. print ("Hello James!") #If does have string James will print specific message. The white space before the print function indicates to python that you want this function to run in this if statement. elif name is "Marucs": #This is elif statement will runs if the if statement before it was not successful print("Hi Marucs!") elif name is "Jim": #Can Have as many elif statements you want until you find the right name print("Yo Jim!") else: #This else statement can be a catch all response if the name is not used in the if or elif statements. print("Sorry your signed up!")
What are for loops?
For loop allows you to loop through a list allowing you to do things without having to re write code over and over again to get results.
foods = ['Apple', 'Bread', 'Pork', 'Burgers', "Ham", "Beans", "Pasta"] for f in foods[:5]: #This is the for loop, f is the variable that python will temp store data in each time the loop runs. [:5] has been added and will mean that the code fetch items at the start and finish the loop on the fifth item on the loop print(f) #This will print the food name each time the loop runs. The indented white space indicates that this function is part of the loop. print(len(f)) #This will print the foods character length underneath its name for each item on the foods list.
Fun(Subjective) magic number finding game
magicnumber =30 for n in range (101): #loop that makes n a number from 0-101 after each run. if n is magicnumber: #if n = the magic number then print message print(n, " Is the magic number") break #When found magic number no need to keep looping. Break stops the loop to reserve computer power. else: #this code shows that it actually has broken the code. print(n) #this prints the number that did not work to track your progress.
Finds if number can be divided by 4
for n in range (100): #Runs through a list from 0-100 using n to store each number each timne loops. if n % 4 == 0: #Looks at n and if n is divded by 4 and equals 0 means can be divided by 4 print(n, "divides by 4") #prints if equals 0 and can be divded by 4 else: print(n) #if not the normal number is printed.
You must be logged in to reply to this topic.