YouTip LogoYouTip

Python3 Step1

# Python3.x First Steps in Programming In the previous tutorials, we have already learned some basic Python3 syntax. Now, let's try some examples. Printing a string: ## Example print("Hello, world!") The output is: Hello, world! Printing the value of a variable: ## Example i =256*256 print('The value of i is:', i) The output is: The value of i is: 65536 Defining a variable and performing simple mathematical operations: ## Example x =3 y =2 z = x + y print(z) The output is: 5 Defining a list and printing its elements: ## Example my_list =['google','','taobao'] print(my_list)# Outputs "google" print(my_list)# Outputs "" print(my_list)# Outputs "taobao" The output is: google taobao Using a for loop to print numbers from 0 to 4: ## Example for i in range(5): print(i) The output is: 01234 Printing different results based on a condition: ## Example x =6 if x >10: print("x is greater than 10") else: print("x is less than or equal to 10") The output is: x is less than or equal to 10 Now, let's try to write a Fibonacci sequence. The Fibonacci sequence is a classic mathematical problem where each number is the sum of the two preceding ones. ## Example (Python 3.0+) #!/usr/bin/python3# Fibonacci series: Fibonacci sequence# The sum of two elements defines the next a, b = 0, 1 while b<10: print(b)a, b = b, a+b The calculation of the code `a, b = b, a+b` works by first evaluating the right-hand side expression, then simultaneously assigning the values to the left-hand side. It is equivalent to: n=b m=a+b a=n b=m Executing the above program, the output is: 112358 This example introduces several new features. The first line contains a multiple assignment: variables `a` and `b` simultaneously get new values 0 and 1. The last line uses the same method again. You can see that the expression on the right-hand side is executed before the assignment takes place. The order of execution for the right-hand side expressions is from left to right. You can also use a for loop to achieve this: ## Example n =10 a, b =0,1 for i in range(n): print(b) a, b = b, a + b ### The `end` keyword The `end` keyword can be used to print the output on the same line, or to add different characters at the end of the output. Here is an example: ## Example (Python 3.0+) #!/usr/bin/python3# Fibonacci series: Fibonacci sequence# The sum of two elements defines the next a, b = 0, 1 while b>> a=10;b=388;c=98>>> print(a,b,c,sep='@')10@388@98(javascript:;)
← Python3 Conditional StatementsPython3 List β†’